feat: allow translation of statuses (#76)

This commit is contained in:
Daniel Roe 2022-11-25 00:14:16 +00:00 committed by GitHub
parent bef89502a1
commit 8586d58b84
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 70 additions and 1 deletions

47
composables/translate.ts Normal file
View file

@ -0,0 +1,47 @@
import type { Status } from 'masto'
export interface TranslationResponse {
translatedText: string
detectedLanguage: {
confidence: number
language: string
}
}
const config = useRuntimeConfig()
export async function translateText(text: string) {
const { translatedText } = await $fetch<TranslationResponse>(config.public.translateApi, {
method: 'POST',
body: {
q: text,
source: 'auto',
target: navigator.language.replace(/-.*$/, ''),
format: 'html',
api_key: '',
},
})
return translatedText
}
const translations = new WeakMap<Status, { visible: boolean; text: string }>()
export function useTranslation(status: Status) {
if (!translations.has(status))
translations.set(status, reactive({ visible: false, text: '' }))
const translation = translations.get(status)!
async function toggle() {
if (!translation.text)
translation.text = await translateText(status.content)
translation.visible = !translation.visible
}
return {
enabled: !!config.public.translateApi,
toggle,
translation,
}
}