refactor: tidy composables
This commit is contained in:
parent
bf8070c4b9
commit
e0741d58a9
14 changed files with 177 additions and 175 deletions
50
composables/masto/translate.ts
Normal file
50
composables/masto/translate.ts
Normal file
|
@ -0,0 +1,50 @@
|
|||
import type { Status, StatusEdit } 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
|
||||
}
|
||||
|
||||
const translations = new WeakMap<Status | StatusEdit, { visible: boolean; text: string }>()
|
||||
|
||||
export function useTranslation(status: Status | StatusEdit) {
|
||||
if (!translations.has(status))
|
||||
translations.set(status, reactive({ visible: false, text: '' }))
|
||||
|
||||
const translation = translations.get(status)!
|
||||
|
||||
async function toggle() {
|
||||
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,
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue