Something went wrong. Try again.
Mirror — see github.com/blacksky-algorithms/blacksky.community
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458import {useCallback, useMemo} from 'react'import {Platform, type StyleProp, type TextStyle, View} from 'react-native'import {type AppBskyFeedDefs, AppBskyFeedPost} from '@atproto/api'import {Trans, useLingui} from '@lingui/react/macro'
import {HITSLOP_30} from '#/lib/constants'import {useTranslate} from '#/lib/translation'import { type TranslationFunction, type TranslationFunctionParams,} from '#/lib/translation'import { codeToLanguageName, getPostLanguageTags, isPostInLanguage, languageName,} from '#/locale/helpers'import {LANGUAGES} from '#/locale/languages'import {useLanguagePrefs} from '#/state/preferences'import {atoms as a, flatten, native, useTheme, web} from '#/alf'import {Button} from '#/components/Button'import {ArrowRight_Stroke2_Corner0_Rounded as ArrowRightIcon} from '#/components/icons/Arrow'import {TimesLarge_Stroke2_Corner0_Rounded as XIcon} from '#/components/icons/Times'import {Warning_Stroke2_Corner0_Rounded as WarningIcon} from '#/components/icons/Warning'import {createStaticClick, Link} from '#/components/Link'import {Loader} from '#/components/Loader'import * as Select from '#/components/Select'import {Text} from '#/components/Typography'import {useAnalytics} from '#/analytics'import {IS_WEB} from '#/env'import * as bsky from '#/types/bsky'
const X_ICON_OFFSET = 16
export function TranslatedPost({ hideTranslateLink = false, post, postTextStyle = a.text_md,}: { hideTranslateLink?: boolean post: AppBskyFeedDefs.PostView postTextStyle?: StyleProp<TextStyle>}) { const langPrefs = useLanguagePrefs() const {clearTranslation, translate, translationState} = useTranslate({ key: post.uri, })
const record = useMemo<AppBskyFeedPost.Record | undefined>(() => { return bsky.dangerousIsType<AppBskyFeedPost.Record>( post.record, AppBskyFeedPost.isRecord, ) ? post.record : undefined }, [post]) const initialTranslationParams = useMemo<TranslationFunctionParams>(() => { return { text: record?.text || '', expectedTargetLanguage: langPrefs.primaryLanguage, possibleSourceLanguages: getPostLanguageTags(post), } }, [post, record, langPrefs]) const needsTranslation = useMemo(() => { if (hideTranslateLink) return false return !isPostInLanguage(post, [langPrefs.primaryLanguage]) }, [hideTranslateLink, post, langPrefs.primaryLanguage])
switch (translationState.status) { case 'loading': return <TranslationLoading /> case 'success': return ( <TranslationResult translate={translate} clearTranslation={clearTranslation} initialTranslationParams={initialTranslationParams} postTextStyle={postTextStyle} resultSourceLanguage={ translationState.sourceLanguage ?? null // Fallback primarily for iOS } translatedText={translationState.translatedText} /> ) case 'error': return ( <TranslationError translate={translate} clearTranslation={clearTranslation} message={translationState.message} initialTranslationParams={initialTranslationParams} /> ) default: return ( needsTranslation && ( <TranslationLink translate={translate} initialTranslationParams={initialTranslationParams} /> ) ) }}
function TranslationLoading() { const t = useTheme()
return ( <View style={[a.gap_md, a.mt_sm, a.align_start]}> <View style={[a.flex_row, a.align_center, a.gap_xs]}> <Text style={[a.text_sm, t.atoms.text_contrast_medium]}> <Trans>Translating</Trans> </Text> <Loader size="xs" fill={t.atoms.text_contrast_medium.color} /> </View> </View> )}
function TranslationLink({ translate, initialTranslationParams,}: { translate: TranslationFunction initialTranslationParams: TranslationFunctionParams}) { const t = useTheme() const {t: l} = useLingui()
const handleTranslate = useCallback(() => { void translate(initialTranslationParams) }, [initialTranslationParams, translate])
return ( <View style={[ a.gap_md, a.mt_sm, a.align_start, a.flex_row, a.align_center, a.gap_xs, ]}> <Link role={IS_WEB ? 'link' : 'button'} {...createStaticClick(() => { handleTranslate() })} label={l`Translate`} hoverStyle={[ native({opacity: 0.5}), web([a.underline, {textDecorationColor: t.palette.primary_500}]), ]} hitSlop={HITSLOP_30}> <Text style={[a.text_sm, {color: t.palette.primary_500}]}> <Trans>Translate</Trans> </Text> </Link> </View> )}
function TranslationError({ translate, clearTranslation, message, initialTranslationParams,}: { translate: TranslationFunction clearTranslation: () => void message: string initialTranslationParams: TranslationFunctionParams}) { const t = useTheme() const {t: l} = useLingui()
const handleFallback = () => { void translate({ ...initialTranslationParams, forceGoogleTranslate: true, }) }
return ( <View style={[ a.p_md, a.mt_sm, a.border, a.rounded_lg, a.gap_xs, t.atoms.border_contrast_high, ]}> <View style={[ a.flex_row, a.align_start, a.gap_xs, { paddingRight: X_ICON_OFFSET, }, ]}> <WarningIcon size="sm" fill={t.atoms.text_contrast_medium.color} /> <Text style={[ a.flex_1, a.text_xs, a.leading_snug, t.atoms.text_contrast_high, ]}> {message} </Text>
<Button label={l`Hide translation`} hitSlop={HITSLOP_30} hoverStyle={native({opacity: 0.5})} style={[a.absolute, a.z_10, {top: 0, right: 0}]} onPress={clearTranslation}> <XIcon size="sm" fill={t.atoms.text_contrast_medium.color} /> </Button> </View> <View style={[a.flex_row, a.align_center]}> <Link {...createStaticClick(() => { handleFallback() })} label={l`Try Google Translate`} hoverStyle={[ native({opacity: 0.5}), web([a.underline, {textDecorationColor: t.palette.primary_500}]), ]} hitSlop={HITSLOP_30}> <Text style={[ a.text_xs, a.font_medium, a.leading_snug, {color: t.palette.primary_500}, ]}> <Trans>Try Google Translate</Trans> </Text> </Link> </View> </View> )}
function TranslationResult({ clearTranslation, translate, postTextStyle, resultSourceLanguage, translatedText, initialTranslationParams,}: { clearTranslation: () => void translate: TranslationFunction postTextStyle?: StyleProp<TextStyle> resultSourceLanguage: string | null translatedText: string initialTranslationParams: TranslationFunctionParams}) { const t = useTheme() const langPrefs = useLanguagePrefs() const {i18n, t: l} = useLingui()
const langName = resultSourceLanguage ? codeToLanguageName(resultSourceLanguage, i18n.locale) : undefined
const flattenedStyle = flatten(postTextStyle) ?? {} const fontSize = flattenedStyle.fontSize
return ( <View> <View style={[ a.p_md, a.mt_sm, a.border, a.rounded_lg, a.gap_xs, t.atoms.border_contrast_high, ]}> <View style={[ a.flex_row, a.align_center, a.flex_wrap, { paddingRight: X_ICON_OFFSET, }, ]}> {langName ? ( <> <Text style={[ a.text_xs, a.leading_snug, t.atoms.text_contrast_medium, ]}> {langName}{' '} </Text> <ArrowRightIcon size="xs" fill={t.atoms.text_contrast_medium.color} /> <Text style={[ a.text_xs, a.leading_snug, t.atoms.text_contrast_medium, ]}> {' '} {codeToLanguageName( langPrefs.primaryLanguage, langPrefs.appLanguage, )} </Text> </> ) : ( <Text style={[a.text_xs, a.leading_snug, t.atoms.text_contrast_medium]}> <Trans>Translated</Trans> </Text> )} {resultSourceLanguage != null && ( <> <Text style={[ a.text_xs, a.font_medium, a.leading_snug, t.atoms.text_contrast_medium, ]}> {' '} ·{' '} </Text> <TranslationLanguageSelect resultSourceLanguage={resultSourceLanguage} translate={translate} initialTranslationParams={initialTranslationParams} /> </> )}
<Button label={l`Hide translation`} hitSlop={HITSLOP_30} hoverStyle={native({opacity: 0.5})} style={[a.absolute, a.z_10, {top: 0, right: 0}]} onPress={clearTranslation}> <XIcon size="sm" fill={t.atoms.text_contrast_medium.color} /> </Button> </View> <Text emoji selectable style={[a.leading_snug, {fontSize}]}> {translatedText} </Text> </View> </View> )}
function TranslationLanguageSelect({ translate, resultSourceLanguage, initialTranslationParams,}: { translate: TranslationFunction resultSourceLanguage: string initialTranslationParams: TranslationFunctionParams}) { const t = useTheme() const ax = useAnalytics() const {t: l} = useLingui() const langPrefs = useLanguagePrefs()
const items = useMemo( () => LANGUAGES.filter( (lang, index, self) => !langPrefs.primaryLanguage.startsWith(lang.code2) && // Don't show the current language as it would be redundant index === self.findIndex(t => t.code2 === lang.code2), // Remove dupes (which will happen due to multiple code3 values mapping to the same code2) ) .sort((a, b) => { // Prioritize sourceLanguage at the top if (a.code2 === resultSourceLanguage) return -1 if (b.code2 === resultSourceLanguage) return 1 // Localized sort return languageName(a, langPrefs.appLanguage).localeCompare( languageName(b, langPrefs.appLanguage), langPrefs.appLanguage, ) }) .map(l => ({ label: languageName(l, langPrefs.appLanguage), // The viewer may not be familiar with the source language, so localize the name value: l.code2, })), [langPrefs, resultSourceLanguage], )
const handleChangeTranslationLanguage = (sourceLangCode: string) => { ax.metric('translate:override', { os: Platform.OS, possibleSourceLanguages: initialTranslationParams.possibleSourceLanguages, expectedSourceLanguage: sourceLangCode, expectedTargetLanguage: initialTranslationParams.expectedTargetLanguage, resultSourceLanguage, }) void translate({ text: initialTranslationParams.text, expectedTargetLanguage: initialTranslationParams.expectedTargetLanguage, expectedSourceLanguage: sourceLangCode, possibleSourceLanguages: initialTranslationParams.possibleSourceLanguages, }) }
return ( <Select.Root value={resultSourceLanguage} onValueChange={handleChangeTranslationLanguage}> <Select.Trigger label={l`Change the source language`}> {({props}) => { return ( <Button label={props.accessibilityLabel} {...props} hitSlop={HITSLOP_30} hoverStyle={native({opacity: 0.5})}> <Text style={[ a.text_xs, a.font_medium, a.leading_snug, t.atoms.text_contrast_high, ]}> <Trans>Change</Trans> </Text> </Button> ) }} </Select.Trigger> <Select.Content label={l`Select the source language`} renderItem={({label, value}) => ( <Select.Item value={value} label={label}> <Select.ItemIndicator /> <Select.ItemText>{label}</Select.ItemText> </Select.Item> )} items={items} /> </Select.Root> )}