mirror of
https://github.com/tooot-app/app
synced 2025-06-05 22:19:13 +02:00
Fixed #529
This commit is contained in:
@ -1,5 +1,6 @@
|
||||
import { ParseHTML } from '@components/Parse'
|
||||
import CustomText from '@components/Text'
|
||||
import detectLanguage from '@helpers/detectLanguage'
|
||||
import getLanguage from '@helpers/getLanguage'
|
||||
import { useTranslateQuery } from '@utils/queryHooks/translate'
|
||||
import { StyleConstants } from '@utils/styles/constants'
|
||||
@ -7,38 +8,44 @@ import { useTheme } from '@utils/styles/ThemeManager'
|
||||
import * as Localization from 'expo-localization'
|
||||
import React, { useContext, useEffect, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Pressable } from 'react-native'
|
||||
import { Platform, Pressable } from 'react-native'
|
||||
import { Circle } from 'react-native-animated-spinkit'
|
||||
import detectLanguage from 'react-native-language-detection'
|
||||
import StatusContext from './Context'
|
||||
|
||||
const TimelineTranslate = () => {
|
||||
const { status, highlighted } = useContext(StatusContext)
|
||||
const { status, highlighted, copiableContent } = useContext(StatusContext)
|
||||
if (!status || !highlighted) return null
|
||||
|
||||
const { t } = useTranslation('componentTimeline')
|
||||
const { colors } = useTheme()
|
||||
|
||||
const text = status.spoiler_text ? [status.spoiler_text, status.content] : [status.content]
|
||||
const backupTextProcessing = (): string[] => {
|
||||
const text = status.spoiler_text ? [status.spoiler_text, status.content] : [status.content]
|
||||
|
||||
for (const i in text) {
|
||||
for (const emoji of status.emojis) {
|
||||
text[i] = text[i].replaceAll(`:${emoji.shortcode}:`, ' ')
|
||||
for (const i in text) {
|
||||
for (const emoji of status.emojis) {
|
||||
text[i] = text[i].replaceAll(`:${emoji.shortcode}:`, ' ')
|
||||
}
|
||||
text[i] = text[i]
|
||||
.replace(/(<([^>]+)>)/gi, ' ')
|
||||
.replace(/@.*? /gi, ' ')
|
||||
.replace(/#.*? /gi, ' ')
|
||||
.replace(/http(s):\/\/.*? /gi, ' ')
|
||||
}
|
||||
text[i] = text[i]
|
||||
.replace(/(<([^>]+)>)/gi, ' ')
|
||||
.replace(/@.*? /gi, ' ')
|
||||
.replace(/#.*? /gi, ' ')
|
||||
.replace(/http(s):\/\/.*? /gi, ' ')
|
||||
return text
|
||||
}
|
||||
const text = copiableContent?.current.content
|
||||
? [copiableContent?.current.content]
|
||||
: backupTextProcessing()
|
||||
|
||||
const [detectedLanguage, setDetectedLanguage] = useState<string>('')
|
||||
const [detectedLanguage, setDetectedLanguage] = useState<{
|
||||
language: string
|
||||
confidence: number
|
||||
}>({ language: status.language || '', confidence: 0 })
|
||||
useEffect(() => {
|
||||
const detect = async () => {
|
||||
const result = await detectLanguage(text.join(`\n\n`)).catch(() => {
|
||||
// No need to log language detection failure
|
||||
})
|
||||
result?.detected && setDetectedLanguage(result.detected.slice(0, 2))
|
||||
const result = await detectLanguage(text.join('\n\n'))
|
||||
result && setDetectedLanguage(result)
|
||||
}
|
||||
detect()
|
||||
}, [])
|
||||
@ -50,20 +57,36 @@ const TimelineTranslate = () => {
|
||||
|
||||
const [enabled, setEnabled] = useState(false)
|
||||
const { refetch, data, isLoading, isSuccess, isError } = useTranslateQuery({
|
||||
source: detectedLanguage,
|
||||
source: detectedLanguage.language,
|
||||
target: targetLanguage,
|
||||
text,
|
||||
options: { enabled }
|
||||
})
|
||||
|
||||
const devView = () => {
|
||||
return __DEV__ ? (
|
||||
<CustomText fontStyle='S' style={{ color: colors.secondary }}>{` Source: ${
|
||||
detectedLanguage?.language
|
||||
}; Confidence: ${
|
||||
detectedLanguage?.confidence.toString().slice(0, 5) || 'null'
|
||||
}; Target: ${targetLanguage}`}</CustomText>
|
||||
) : null
|
||||
}
|
||||
|
||||
if (!detectedLanguage) {
|
||||
return null
|
||||
return devView()
|
||||
}
|
||||
if (Localization.locale.slice(0, 2).includes(detectedLanguage)) {
|
||||
return null
|
||||
if (
|
||||
Platform.OS === 'ios' &&
|
||||
Localization.locale.slice(0, 2).includes(detectedLanguage.language.slice(0, 2))
|
||||
) {
|
||||
return devView()
|
||||
}
|
||||
if (settingsLanguage?.slice(0, 2).includes(detectedLanguage)) {
|
||||
return null
|
||||
if (
|
||||
Platform.OS === 'android' &&
|
||||
settingsLanguage?.slice(0, 2).includes(detectedLanguage.language.slice(0, 2))
|
||||
) {
|
||||
return devView()
|
||||
}
|
||||
|
||||
return (
|
||||
@ -102,9 +125,6 @@ const TimelineTranslate = () => {
|
||||
})
|
||||
: t('shared.translate.default')}
|
||||
</CustomText>
|
||||
<CustomText>
|
||||
{__DEV__ ? ` Source: ${detectedLanguage}; Target: ${targetLanguage}` : undefined}
|
||||
</CustomText>
|
||||
{isLoading ? (
|
||||
<Circle
|
||||
size={StyleConstants.Font.Size.M}
|
||||
@ -113,6 +133,7 @@ const TimelineTranslate = () => {
|
||||
/>
|
||||
) : null}
|
||||
</Pressable>
|
||||
{devView()}
|
||||
{data && data.error === undefined
|
||||
? data.text.map((d, i) => <ParseHTML key={i} content={d} size={'M'} numberOfLines={999} />)
|
||||
: null}
|
||||
|
10
src/helpers/detectLanguage.ts
Normal file
10
src/helpers/detectLanguage.ts
Normal file
@ -0,0 +1,10 @@
|
||||
import detect from 'react-native-language-detection'
|
||||
|
||||
const detectLanguage = async (
|
||||
text: string
|
||||
): Promise<{ language: string; confidence: number } | null> => {
|
||||
const possibleLanguages = await detect(text).catch(() => {})
|
||||
return possibleLanguages ? possibleLanguages.filter(lang => lang.confidence > 0.5)?.[0] : null
|
||||
}
|
||||
|
||||
export default detectLanguage
|
@ -6,7 +6,7 @@ import { createNativeStackNavigator } from '@react-navigation/native-stack'
|
||||
import haptics from '@root/components/haptics'
|
||||
import { useAppDispatch } from '@root/store'
|
||||
import ComposeRoot from '@screens/Compose/Root'
|
||||
import formatText from '@screens/Compose/utils/formatText'
|
||||
import { formatText } from '@screens/Compose/utils/processText'
|
||||
import { RootStackScreenProps } from '@utils/navigation/navigators'
|
||||
import { useTimelineMutation } from '@utils/queryHooks/timeline'
|
||||
import { updateStoreReview } from '@utils/slices/contextsSlice'
|
||||
|
@ -15,7 +15,7 @@ import { PanGestureHandler } from 'react-native-gesture-handler'
|
||||
import { SwipeListView } from 'react-native-swipe-list-view'
|
||||
import { useSelector } from 'react-redux'
|
||||
import ComposeContext from '../utils/createContext'
|
||||
import formatText from '../utils/formatText'
|
||||
import { formatText } from '../utils/processText'
|
||||
import { ComposeStateDraft, ExtendedAttachment } from '../utils/types'
|
||||
|
||||
export interface Props {
|
||||
|
@ -8,7 +8,7 @@ import { useTranslation } from 'react-i18next'
|
||||
import { TextInput } from 'react-native'
|
||||
import { useSelector } from 'react-redux'
|
||||
import ComposeContext from '../../utils/createContext'
|
||||
import formatText from '../../utils/formatText'
|
||||
import { formatText } from '../../utils/processText'
|
||||
|
||||
const ComposeSpoilerInput: React.FC = () => {
|
||||
const { composeState, composeDispatch } = useContext(ComposeContext)
|
||||
|
@ -10,7 +10,7 @@ import { useTranslation } from 'react-i18next'
|
||||
import { Alert } from 'react-native'
|
||||
import { useSelector } from 'react-redux'
|
||||
import ComposeContext from '../../utils/createContext'
|
||||
import formatText from '../../utils/formatText'
|
||||
import { formatText } from '../../utils/processText'
|
||||
import { uploadAttachment } from '../Footer/addAttachment'
|
||||
|
||||
const ComposeTextInput: React.FC = () => {
|
||||
|
@ -3,7 +3,7 @@ import haptics from '@components/haptics'
|
||||
import ComponentHashtag from '@components/Hashtag'
|
||||
import React, { useContext, useEffect } from 'react'
|
||||
import ComposeContext from '../utils/createContext'
|
||||
import formatText from '../utils/formatText'
|
||||
import { formatText } from '../utils/processText'
|
||||
|
||||
type Props = { item: Mastodon.Account & Mastodon.Tag }
|
||||
|
||||
|
@ -1,7 +1,9 @@
|
||||
import apiInstance, { InstanceResponse } from '@api/instance'
|
||||
import detectLanguage from '@helpers/detectLanguage'
|
||||
import { ComposeState } from '@screens/Compose/utils/types'
|
||||
import { RootStackParamList } from '@utils/navigation/navigators'
|
||||
import * as Crypto from 'expo-crypto'
|
||||
import { getPureContent } from './processText'
|
||||
|
||||
const composePost = async (
|
||||
params: RootStackParamList['Screen-Compose'],
|
||||
@ -9,6 +11,13 @@ const composePost = async (
|
||||
): Promise<InstanceResponse<Mastodon.Status>> => {
|
||||
const formData = new FormData()
|
||||
|
||||
const detectedLanguage = await detectLanguage(
|
||||
getPureContent([composeState.spoiler.raw, composeState.text.raw].join('\n\n'))
|
||||
)
|
||||
if (detectedLanguage) {
|
||||
formData.append('language', detectedLanguage.language)
|
||||
}
|
||||
|
||||
if (composeState.replyToStatus) {
|
||||
try {
|
||||
await apiInstance<Mastodon.Status>({
|
||||
|
@ -150,7 +150,7 @@ const formatText = ({ textInput, composeDispatch, content, disableDebounce = fal
|
||||
})
|
||||
children.push(_content)
|
||||
contentLength = contentLength + _content.length
|
||||
|
||||
getPureContent(content)
|
||||
composeDispatch({
|
||||
type: textInput,
|
||||
payload: {
|
||||
@ -161,4 +161,18 @@ const formatText = ({ textInput, composeDispatch, content, disableDebounce = fal
|
||||
})
|
||||
}
|
||||
|
||||
export default formatText
|
||||
const getPureContent = (content: string): string => {
|
||||
const tags = linkify.match(content)
|
||||
if (!tags) {
|
||||
return content
|
||||
}
|
||||
|
||||
let _content = content
|
||||
for (const tag of tags) {
|
||||
_content = _content.replace(tag.raw, '')
|
||||
}
|
||||
|
||||
return _content.replace(/\s\s+/g, ' ')
|
||||
}
|
||||
|
||||
export { formatText, getPureContent }
|
Reference in New Issue
Block a user