1
0
mirror of https://github.com/elk-zone/elk synced 2024-12-03 01:08:07 +09:00
elk/composables/masto/translate.ts

51 lines
1.3 KiB
TypeScript
Raw Normal View History

2023-01-08 15:21:09 +09:00
import type { mastodon } from 'masto'
export interface TranslationResponse {
translatedText: string
detectedLanguage: {
confidence: number
language: string
}
}
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: '',
},
})
return translatedText
}
2023-01-08 15:21:09 +09:00
const translations = new WeakMap<mastodon.v1.Status | mastodon.v1.StatusEdit, { visible: boolean; text: string }>()
2023-01-08 15:21:09 +09:00
export function useTranslation(status: mastodon.v1.Status | mastodon.v1.StatusEdit) {
if (!translations.has(status))
translations.set(status, reactive({ visible: false, text: '' }))
const translation = translations.get(status)!
async function toggle() {
2023-01-06 01:48:20 +09:00
if (!('language' in status))
return
if (!translation.text)
translation.text = await translateText(status.content, status.language)
translation.visible = !translation.visible
}
return {
enabled: !!useRuntimeConfig().public.translateApi,
toggle,
translation,
}
}