this repo has no description
1import {useCallback} from 'react'
2import * as IntentLauncher from 'expo-intent-launcher'
3
4import {useOpenLink} from '#/lib/hooks/useOpenLink'
5import {getTranslatorLink} from '#/locale/helpers'
6import {IS_ANDROID} from '#/env'
7
8/**
9 * @deprecated Will always link out to Google Translate. Prefer `useTranslate`.
10 */
11export function useGoogleTranslate() {
12 const openLink = useOpenLink()
13
14 return useCallback(
15 async (text: string, targetLangCode: string, sourceLanguage?: string) => {
16 const translateUrl = getTranslatorLink(
17 text,
18 targetLangCode,
19 sourceLanguage,
20 )
21 if (IS_ANDROID) {
22 try {
23 // use `getApplicationIconAsync` to determine if the translate app is installed
24 if (
25 !(await IntentLauncher.getApplicationIconAsync(
26 'com.google.android.apps.translate',
27 ))
28 ) {
29 throw new Error('Translate app not installed')
30 }
31
32 // TODO: this should only be called one at a time, use something like
33 // RQ's `scope` - otherwise can trigger the browser to open unexpectedly when the call throws -sfn
34 await IntentLauncher.startActivityAsync(
35 'android.intent.action.PROCESS_TEXT',
36 {
37 type: 'text/plain',
38 extra: {
39 'android.intent.extra.PROCESS_TEXT': text,
40 'android.intent.extra.PROCESS_TEXT_READONLY': true,
41 },
42 // note: to skip the intermediate app select, we need to specify a
43 // `className`. however, this isn't safe to hardcode, we'd need to query the
44 // package manager for the correct activity. this requires native code, so
45 // skip for now -sfn
46 // packageName: 'com.google.android.apps.translate',
47 // className: 'com.google.android.apps.translate.TranslateActivity',
48 },
49 )
50 } catch (err) {
51 if (__DEV__) console.error(err)
52 // most likely means they don't have the translate app
53 await openLink(translateUrl)
54 }
55 } else {
56 await openLink(translateUrl)
57 }
58 },
59 [openLink],
60 )
61}