feat: improve posts translation logic (#1211)

This commit is contained in:
Alex 2023-01-16 17:55:00 +08:00 committed by GitHub
parent 3b73d11fd3
commit d745bd0583
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 78 additions and 23 deletions

View file

@ -11,24 +11,37 @@ export interface TranslationResponse {
export const languageCode = process.server ? 'en' : navigator.language.replace(/-.*$/, '')
export async function translateText(text: string, from?: string | null, to?: string) {
const config = useRuntimeConfig()
const { translatedText } = await $fetch<TranslationResponse>(config.public.translateApi, {
method: 'POST',
body: {
q: text,
source: from ?? 'auto',
target: to ?? languageCode,
format: 'html',
api_key: '',
},
const status = $ref({
success: false,
error: '',
text: '',
})
return translatedText
try {
const response = await $fetch<TranslationResponse>(config.public.translateApi, {
method: 'POST',
body: {
q: text,
source: from ?? 'auto',
target: to ?? languageCode,
format: 'html',
api_key: '',
},
})
status.success = true
status.text = response.translatedText
}
catch (err) {
// TODO: improve type
status.error = (err as { data: { error: string } }).data.error
}
return status
}
const translations = new WeakMap<mastodon.v1.Status | mastodon.v1.StatusEdit, { visible: boolean; text: string }>()
const translations = new WeakMap<mastodon.v1.Status | mastodon.v1.StatusEdit, { visible: boolean; text: string; success: boolean; error: string }>()
export function useTranslation(status: mastodon.v1.Status | mastodon.v1.StatusEdit) {
if (!translations.has(status))
translations.set(status, reactive({ visible: false, text: '' }))
translations.set(status, reactive({ visible: false, text: '', success: false, error: '' }))
const translation = translations.get(status)!
@ -36,8 +49,12 @@ export function useTranslation(status: mastodon.v1.Status | mastodon.v1.StatusEd
if (!('language' in status))
return
if (!translation.text)
translation.text = await translateText(status.content, status.language)
if (!translation.text) {
const { success, text, error } = await translateText(status.content, status.language)
translation.error = error
translation.text = text
translation.success = success
}
translation.visible = !translation.visible
}