Call useTranslate once and pass down translate function
This commit is contained in:
@@ -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)
|
||||
|
||||
@@ -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],
|
||||
|
||||
@@ -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>
|
||||
|
||||
Reference in New Issue
Block a user