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