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