Files
Ivan Rezchikov 628dd6384b
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
version 1
2026-09-18 00:45:51 +03:00

93 lines
2.6 KiB
TypeScript

"use client";
import { useCallback } from "react";
import { getExamples } from "@/lib/api";
import { useResource } from "@/hooks/useResource";
import { resolveApiErrorMessage } from "@/lib/useApiErrorMessage";
import type { ExamplesResult, 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() ? (
<span key={i} className="px-1 py-0.5 rounded-sm bg-accent text-accent-foreground">
{part}
</span>
) : (
<span key={i}>{part}</span>
),
)}
</>
);
}
interface ExamplesProps {
word: string;
lang: Language;
onResult?: (result: Fetched<ExamplesResult>) => void;
}
export function Examples({ word, lang, onResult }: ExamplesProps) {
const cacheKey = `example:${lang}:${word.toLowerCase()}`;
const report = useCallback(
(data: ExamplesResult) =>
onResult?.({
...data,
fetched_at: new Date().toISOString(),
}),
[onResult]
);
const state = useResource<ExamplesResult>(
cacheKey,
() => getExamples(lang, word),
report
);
const t = useTranslations("Examples");
const tApi = useTranslations("ApiErrors");
const errorMessage = resolveApiErrorMessage(
state.error,
(kind) => (kind === "not-found" ? t("notFound") : tApi(kind)),
t("failed")
);
return (
<div className="flex flex-col gap-4">
<h3 className="font-semibold">{t("title")}</h3>
{state.status === "loading" && (
<Marker>
<MarkerIcon>
<Spinner />
</MarkerIcon>
<MarkerContent className="shimmer">{t("loading")}</MarkerContent>
</Marker>
)}
{state.status === "error" && (
<p className="text-muted-foreground">{errorMessage}</p>
)}
{state.status === "done" && (
<div className="flex flex-col gap-2">
{state.data?.examples.map((example, i) => (
<div key={i} className="flex flex-row gap-2 items-start">
<h5 className="text-muted-foreground shrink-0 tabular-nums">{i + 1}.</h5>
<div className="flex flex-col gap-1">
<p><HighlightWord text={example} word={word} /></p>
</div>
</div>
))}
</div>
)}
</div>
);
}