2023-01-08 15:21:09 +09:00
|
|
|
import type { mastodon } from 'masto'
|
2022-11-25 09:14:16 +09:00
|
|
|
|
|
|
|
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()
|
2023-01-16 18:55:00 +09:00
|
|
|
const status = $ref({
|
|
|
|
success: false,
|
|
|
|
error: '',
|
|
|
|
text: '',
|
2022-11-25 09:14:16 +09:00
|
|
|
})
|
2023-01-16 18:55:00 +09:00
|
|
|
try {
|
|
|
|
const response = await $fetch<TranslationResponse>(config.public.translateApi, {
|
|
|
|
method: 'POST',
|
|
|
|
body: {
|
|
|
|
q: text,
|
|
|
|
source: from ?? 'auto',
|
|
|
|
target: to ?? languageCode,
|
|
|
|
format: 'html',
|
|
|
|
api_key: '',
|
|
|
|
},
|
|
|
|
})
|
|
|
|
status.success = true
|
|
|
|
status.text = response.translatedText
|
|
|
|
}
|
|
|
|
catch (err) {
|
|
|
|
// TODO: improve type
|
|
|
|
status.error = (err as { data: { error: string } }).data.error
|
|
|
|
}
|
|
|
|
return status
|
2022-11-25 09:14:16 +09:00
|
|
|
}
|
|
|
|
|
2023-01-16 18:55:00 +09:00
|
|
|
const translations = new WeakMap<mastodon.v1.Status | mastodon.v1.StatusEdit, { visible: boolean; text: string; success: boolean; error: string }>()
|
2022-11-25 09:14:16 +09:00
|
|
|
|
2023-01-08 15:21:09 +09:00
|
|
|
export function useTranslation(status: mastodon.v1.Status | mastodon.v1.StatusEdit) {
|
2022-11-25 09:14:16 +09:00
|
|
|
if (!translations.has(status))
|
2023-01-16 18:55:00 +09:00
|
|
|
translations.set(status, reactive({ visible: false, text: '', success: false, error: '' }))
|
2022-11-25 09:14:16 +09:00
|
|
|
|
|
|
|
const translation = translations.get(status)!
|
|
|
|
|
|
|
|
async function toggle() {
|
2023-01-06 01:48:20 +09:00
|
|
|
if (!('language' in status))
|
|
|
|
return
|
|
|
|
|
2023-01-16 18:55:00 +09:00
|
|
|
if (!translation.text) {
|
|
|
|
const { success, text, error } = await translateText(status.content, status.language)
|
|
|
|
translation.error = error
|
|
|
|
translation.text = text
|
|
|
|
translation.success = success
|
|
|
|
}
|
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,
|
|
|
|
}
|
|
|
|
}
|