Call useTranslate once and pass down translate function

This commit is contained in:
DS Boyce
2026-03-03 12:46:47 -08:00
parent 5d22e727c8
commit f39e449683
4 changed files with 39 additions and 35 deletions
+6 -20
View File
@@ -1,28 +1,14 @@
import {createContext} from 'react'
import {type TranslationState} from './types'
import {type TranslationFunctionParams, type TranslationState} from './types'
export const Context = createContext<{
translationState: Record<string, TranslationState>
translate: (parameters: {
key: string
/**
* The text to be translated.
*/
text: string
/**
* The language to translate the text into.
*/
targetLangCode: string
/**
* The source language of the text. Will auto-detect if not provided.
*/
sourceLangCode?: string
/**
* Whether to force the use of Google Translate. Default is false.
*/
forceGoogleTranslate?: boolean
}) => Promise<void>
translate: (
parameters: TranslationFunctionParams & {
key: string
},
) => Promise<void>
clearTranslation: (key: string) => void
acquireTranslation: (key: string) => () => void
} | null>(null)
+2 -7
View File
@@ -8,7 +8,7 @@ import {useGoogleTranslate} from '#/lib/hooks/useGoogleTranslate'
import {logger} from '#/logger'
import {useAnalytics} from '#/analytics'
import {Context} from './context'
import {type TranslationState} from './types'
import {type TranslationFunctionParams, type TranslationState} from './types'
/**
* Attempts on-device translation via @bsky.app/expo-translate-text.
@@ -94,12 +94,7 @@ export function useTranslate({key}: {key: string}) {
)
const translate = useCallback(
async (params: {
text: string
targetLangCode: string
sourceLangCode?: string
forceGoogleTranslate?: boolean
}) => {
async (params: TranslationFunctionParams) => {
return context.translate({...params, key})
},
[key, context],
+23
View File
@@ -9,3 +9,26 @@ export type TranslationState =
sourceLanguage: TranslationTaskResult['sourceLanguage']
targetLanguage: TranslationTaskResult['targetLanguage']
}
export type TranslationFunctionParams = {
/**
* The text to be translated.
*/
text: string
/**
* The language to translate the text into.
*/
targetLangCode: string
/**
* The source language of the text. Will auto-detect if not provided.
*/
sourceLangCode?: string
/**
* Whether to force the use of Google Translate. Default is false.
*/
forceGoogleTranslate?: boolean
}
export type TranslationFunction = (
parameters: TranslationFunctionParams,
) => Promise<void>