2022-11-25 00:14:16 +00:00
|
|
|
import type { Status } from 'masto'
|
|
|
|
|
|
|
|
export interface TranslationResponse {
|
|
|
|
translatedText: string
|
|
|
|
detectedLanguage: {
|
|
|
|
confidence: number
|
|
|
|
language: string
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const config = useRuntimeConfig()
|
|
|
|
|
2022-11-25 11:24:19 +00:00
|
|
|
export const languageCode = process.server ? 'en' : navigator.language.replace(/-.*$/, '')
|
|
|
|
export async function translateText(text: string, from?: string | null, to?: string) {
|
2022-11-25 00:14:16 +00:00
|
|
|
const { translatedText } = await $fetch<TranslationResponse>(config.public.translateApi, {
|
|
|
|
method: 'POST',
|
|
|
|
body: {
|
|
|
|
q: text,
|
2022-11-25 11:24:19 +00:00
|
|
|
source: from ?? 'auto',
|
|
|
|
target: to ?? languageCode,
|
2022-11-25 00:14:16 +00:00
|
|
|
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)
|
2022-11-25 11:24:19 +00:00
|
|
|
translation.text = await translateText(status.content, status.language)
|
2022-11-25 00:14:16 +00:00
|
|
|
|
|
|
|
translation.visible = !translation.visible
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
enabled: !!config.public.translateApi,
|
|
|
|
toggle,
|
|
|
|
translation,
|
|
|
|
}
|
|
|
|
}
|
2022-11-25 11:24:19 +00:00
|
|
|
|