"use client"; import { useCallback } from "react"; import { getCollocations } from "@/lib/api"; import { useResource } from "@/hooks/useResource"; import { resolveApiErrorMessage } from "@/lib/useApiErrorMessage"; import type { CollocationsResult, Fetched, Language } from "@/types/api"; import { Spinner } from "./ui/spinner"; import { Marker, MarkerContent, MarkerIcon } from "./ui/marker"; import { useTranslations } from "next-intl"; function HighlightWord({ text, word }: { text: string; word: string }) { const escapedWord = word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); const regex = new RegExp(`(${escapedWord})`, "gi"); return ( <> {text.split(regex).map((part, i) => part.toLowerCase() === word.toLowerCase() ? ( {part} ) : ( {part} ), )} > ); } interface CollocationsProps { word: string; lang: Language; onResult?: (result: Fetched) => void; } export function Collocations({ word, lang, onResult }: CollocationsProps) { const cacheKey = `col:${lang}:${word.toLowerCase()}`; const report = useCallback( (data: CollocationsResult) => onResult?.({ ...data, fetched_at: new Date().toISOString(), }), [onResult] ); const state = useResource( cacheKey, () => getCollocations(lang, word), report ); const t = useTranslations("Collocations"); const tApi = useTranslations("ApiErrors"); const errorMessage = resolveApiErrorMessage( state.error, (kind) => (kind === "not-found" ? t("notFound") : tApi(kind)), t("failed") ); return ( {t("title")} {state.status === "loading" && ( {t("loading")} )} {state.status === "error" && ( {errorMessage} )} {state.status === "done" && ( {state.data?.collocations.map((collocation, i) => ( {i + 1}. ))} )} ); }
{errorMessage}