Build and Deploy / test-backend (push) Successful in 1m11s
Build and Deploy / lint-frontend (push) Successful in 21s
Build and Deploy / build-backend (push) Successful in 58s
Build and Deploy / deploy (push) Canceled after 0s
Build and Deploy / build-frontend (push) Canceled after 5m38s
91 lines
2.5 KiB
TypeScript
91 lines
2.5 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect, useRef, useState } from "react";
|
|
import { translateText } from "@/lib/api";
|
|
import type { ApiError } from "@/lib/api";
|
|
import type { Fetched, Language, TranslationResult } from "@/types/api";
|
|
|
|
export const TRANSLATION_DEBOUNCE_MS = 800;
|
|
|
|
const CACHE_LIMIT = 50;
|
|
|
|
const resultCache = new Map<string, Fetched<TranslationResult>>();
|
|
|
|
interface TranslationState {
|
|
key: string;
|
|
result?: Fetched<TranslationResult>;
|
|
error?: unknown;
|
|
}
|
|
|
|
export function useTranslation(
|
|
text: string,
|
|
from: Language,
|
|
to: Language
|
|
): {
|
|
translatedText: string;
|
|
result: Fetched<TranslationResult> | null;
|
|
isLoading: boolean;
|
|
error: ApiError | null;
|
|
} {
|
|
const [state, setState] = useState<TranslationState | null>(null);
|
|
|
|
const trimmed = text.trim();
|
|
const key = trimmed ? `${from}:${to}:${trimmed}` : null;
|
|
const initialKeyRef = useRef(key);
|
|
const cached = key ? resultCache.get(key) : undefined;
|
|
const settled = cached ?? (state?.key === key ? state.result : undefined);
|
|
const stateError = state?.key === key ? state.error : undefined;
|
|
|
|
const isLoading = key !== null && !cached && !settled && !stateError;
|
|
|
|
useEffect(() => {
|
|
if (!key || cached || stateError) return;
|
|
|
|
const controller = new AbortController();
|
|
|
|
const delayMs = key === initialKeyRef.current ? 0 : TRANSLATION_DEBOUNCE_MS;
|
|
|
|
const timeoutId = setTimeout(async () => {
|
|
try {
|
|
const data = await translateText(
|
|
{ text: trimmed, from, to },
|
|
controller.signal
|
|
);
|
|
|
|
if (controller.signal.aborted) return;
|
|
|
|
if (data.translations.length > 0) {
|
|
const enriched: Fetched<TranslationResult> = {
|
|
...data,
|
|
fetched_at: new Date().toISOString(),
|
|
};
|
|
resultCache.set(key, enriched);
|
|
if (resultCache.size > CACHE_LIMIT) {
|
|
resultCache.delete(resultCache.keys().next().value!);
|
|
}
|
|
setState({ key, result: enriched });
|
|
} else {
|
|
setState({ key });
|
|
}
|
|
} catch (err) {
|
|
if (!controller.signal.aborted) {
|
|
console.error("Translation failed:", err);
|
|
setState({ key, error: err });
|
|
}
|
|
}
|
|
}, delayMs);
|
|
|
|
return () => {
|
|
clearTimeout(timeoutId);
|
|
controller.abort();
|
|
};
|
|
}, [key, cached, stateError, trimmed, from, to]);
|
|
|
|
return {
|
|
translatedText: settled?.translations.join("") ?? "",
|
|
result: settled ?? null,
|
|
isLoading,
|
|
error: (stateError as ApiError) ?? null,
|
|
};
|
|
}
|