diff --git a/src/lib/translation/index.tsx b/src/lib/translation/index.tsx index 928485b41b..f64f90635f 100644 --- a/src/lib/translation/index.tsx +++ b/src/lib/translation/index.tsx @@ -194,49 +194,55 @@ export function Provider({children}: React.PropsWithChildren) { await googleTranslate(text, targetLangCode, sourceLangCode) return } + const translateAfterAnimation = async () => { + try { + const result = await attemptTranslation( + text, + targetLangCode, + sourceLangCode, + ) + ax.metric('translate:result', { + method: 'on-device', + os: Platform.OS, + sourceLanguage: result.sourceLanguage, + targetLanguage: result.targetLanguage, + }) + LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut) + setTranslationState(prev => ({ + ...prev, + [key]: { + status: 'success', + translatedText: result.translatedText, + sourceLanguage: result.sourceLanguage, + targetLanguage: result.targetLanguage, + }, + })) + } catch (e) { + logger.error('Failed to translate post on device', {safeMessage: e}) + // On-device translation failed (language pack missing or user + // dismissed the download prompt). Fall back to Google Translate. + ax.metric('translate:result', { + method: 'fallback-alert', + os: Platform.OS, + sourceLanguage: sourceLangCode ?? null, + targetLanguage: targetLangCode, + }) + LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut) + setTranslationState(prev => ({ + ...prev, + [key]: {status: 'idle'}, + })) + await googleTranslate(text, targetLangCode, sourceLangCode) + } + } + LayoutAnimation.configureNext( + LayoutAnimation.Presets.easeInEaseOut, + () => void translateAfterAnimation(), + ) setTranslationState(prev => ({ ...prev, [key]: {status: 'loading'}, })) - try { - const result = await attemptTranslation( - text, - targetLangCode, - sourceLangCode, - ) - ax.metric('translate:result', { - method: 'on-device', - os: Platform.OS, - sourceLanguage: result.sourceLanguage, - targetLanguage: result.targetLanguage, - }) - LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut) - setTranslationState(prev => ({ - ...prev, - [key]: { - status: 'success', - translatedText: result.translatedText, - sourceLanguage: result.sourceLanguage, - targetLanguage: result.targetLanguage, - }, - })) - } catch (e) { - logger.error('Failed to translate post on device', {safeMessage: e}) - // On-device translation failed (language pack missing or user - // dismissed the download prompt). Fall back to Google Translate. - ax.metric('translate:result', { - method: 'fallback-alert', - os: Platform.OS, - sourceLanguage: sourceLangCode ?? null, - targetLanguage: targetLangCode, - }) - LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut) - setTranslationState(prev => ({ - ...prev, - [key]: {status: 'idle'}, - })) - await googleTranslate(text, targetLangCode, sourceLangCode) - } }, [ax, googleTranslate], )