197 lines
5.0 KiB
TypeScript
197 lines
5.0 KiB
TypeScript
import { ref, computed } from "vue";
|
|
import type { Ref } from "vue";
|
|
import type { TranslationResponse } from "~/types/translation";
|
|
import { supportedLanguages } from "~/utils/languages";
|
|
|
|
interface UseTranslationOptions {
|
|
initialSource?: string;
|
|
initialTarget?: string;
|
|
model?: Ref<string>;
|
|
}
|
|
|
|
function detectBrowserLanguage(): string {
|
|
if (typeof navigator !== "undefined") {
|
|
const browserLang = navigator.language.toLowerCase();
|
|
const langCode = browserLang.split("-")[0];
|
|
|
|
const matchedLang = supportedLanguages.find(
|
|
(lang) => lang.code === langCode,
|
|
);
|
|
if (matchedLang) {
|
|
return matchedLang.code;
|
|
}
|
|
|
|
if (browserLang.startsWith("en")) {
|
|
return "en";
|
|
}
|
|
}
|
|
return "en";
|
|
}
|
|
|
|
const detectedLang = detectBrowserLanguage();
|
|
const defaultSource = detectedLang;
|
|
const defaultTarget = detectedLang === "en" ? "es" : "en";
|
|
|
|
export function useTranslation(options: UseTranslationOptions = {}) {
|
|
const sourceText = ref("");
|
|
const translatedText = ref("");
|
|
const sourceLang = ref(options.initialSource || defaultSource);
|
|
const targetLang = ref(options.initialTarget || defaultTarget);
|
|
const isLoading = ref(false);
|
|
const error = ref<string | null>(null);
|
|
const charCount = computed(() => sourceText.value.length);
|
|
const wordCount = computed(() => {
|
|
const text = sourceText.value.trim();
|
|
return text ? text.split(/\s+/).length : 0;
|
|
});
|
|
|
|
const isReadyToTranslate = computed(() => {
|
|
return sourceText.value.trim().length > 0 && !isLoading.value;
|
|
});
|
|
|
|
async function translate() {
|
|
if (!isReadyToTranslate.value) {
|
|
return;
|
|
}
|
|
|
|
isLoading.value = true;
|
|
error.value = null;
|
|
translatedText.value = "";
|
|
|
|
try {
|
|
const response = await fetch("/api/translate", {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
},
|
|
body: JSON.stringify({
|
|
text: sourceText.value,
|
|
source: sourceLang.value,
|
|
target: targetLang.value,
|
|
...(options.model ? { model: options.model.value } : {}),
|
|
}),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const errorBody = await response.json().catch(() => ({}));
|
|
throw new Error(
|
|
errorBody.statusMessage || "Translation request failed",
|
|
);
|
|
}
|
|
|
|
const result: TranslationResponse = await response.json();
|
|
translatedText.value = result.translatedText;
|
|
} catch (e) {
|
|
if (e instanceof Error) {
|
|
error.value = e.message;
|
|
} else {
|
|
error.value = "An unknown error occurred";
|
|
}
|
|
} finally {
|
|
isLoading.value = false;
|
|
}
|
|
}
|
|
|
|
async function translateWithStreaming(
|
|
options: {
|
|
onChunk?: (chunk: string) => void;
|
|
onComplete?: (fullText: string) => void;
|
|
} = {},
|
|
) {
|
|
if (!isReadyToTranslate.value) {
|
|
return;
|
|
}
|
|
|
|
isLoading.value = true;
|
|
error.value = null;
|
|
translatedText.value = "";
|
|
|
|
try {
|
|
const response = await fetch("/api/translate-stream", {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
},
|
|
body: JSON.stringify({
|
|
text: sourceText.value,
|
|
source: sourceLang.value,
|
|
target: targetLang.value,
|
|
...(options.model ? { model: options.model.value } : {}),
|
|
}),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const errorBody = await response.json().catch(() => ({}));
|
|
throw new Error(
|
|
errorBody.statusMessage || "Streaming translation request failed",
|
|
);
|
|
}
|
|
|
|
if (!response.body) {
|
|
throw new Error("No response body");
|
|
}
|
|
|
|
const reader = response.body.getReader();
|
|
const decoder = new TextDecoder();
|
|
let accumulatedText = "";
|
|
|
|
while (true) {
|
|
const { done, value } = await reader.read();
|
|
if (done) break;
|
|
|
|
const chunk = decoder.decode(value);
|
|
const lines = chunk.split("\n").filter((line) => line.trim());
|
|
|
|
for (const line of lines) {
|
|
try {
|
|
const parsed = JSON.parse(line);
|
|
if (parsed.response) {
|
|
accumulatedText += parsed.response;
|
|
translatedText.value = accumulatedText;
|
|
options.onChunk?.(parsed.response);
|
|
}
|
|
} catch {}
|
|
}
|
|
}
|
|
|
|
options.onComplete?.(accumulatedText);
|
|
} catch (e) {
|
|
if (e instanceof Error) {
|
|
error.value = e.message;
|
|
} else {
|
|
error.value = "An unknown error occurred";
|
|
}
|
|
} finally {
|
|
isLoading.value = false;
|
|
}
|
|
}
|
|
|
|
function swapLanguages() {
|
|
const temp = sourceLang.value;
|
|
sourceLang.value = targetLang.value;
|
|
targetLang.value = temp;
|
|
}
|
|
|
|
function clearInput() {
|
|
sourceText.value = "";
|
|
translatedText.value = "";
|
|
error.value = null;
|
|
}
|
|
|
|
return {
|
|
sourceText,
|
|
translatedText,
|
|
sourceLang,
|
|
targetLang,
|
|
isLoading,
|
|
error,
|
|
charCount,
|
|
wordCount,
|
|
isReadyToTranslate,
|
|
translate,
|
|
translateWithStreaming,
|
|
swapLanguages,
|
|
clearInput,
|
|
};
|
|
}
|