Files
fancy/fancy-frontend/components/home.tsx
T
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

338 lines
11 KiB
TypeScript

"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import dynamic from "next/dynamic";
import { useSearchParams } from "next/navigation";
import { useTranslations } from "next-intl";
import { ArrowLeftRightIcon } from "lucide-react";
import Main from "@/components/main";
import { PropertyDialog } from "@/components/propertyDialog";
import { TranslationCard } from "@/components/translationCard";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Marker, MarkerContent, MarkerIcon } from "@/components/ui/marker";
import { Spinner } from "@/components/ui/spinner";
import { LOOKUP_DEBOUNCE_MS, useDebouncedValue } from "@/hooks/useDebouncedValue";
import { TRANSLATION_DEBOUNCE_MS, useTranslation } from "@/hooks/useTranslation";
import { DEFAULT_SOURCE_LANG, DEFAULT_TARGET_LANG, LANGUAGES } from "@/lib/languages";
import { setLanguages } from "@/app/actions/setLanguages";
import { parseLanguage } from "@/types/api";
import type { CollocationsResult, DictionaryResult, ExamplesResult, Fetched, Language } from "@/types/api";
import type { UiLanguage } from "@/types/language";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import Header from "./header";
import { Item, ItemActions, ItemContent } from "./ui/item";
import { Skeleton } from "./ui/skeleton";
function CollectionsListLoading() {
return (
<Item variant="muted" className="md:w-1/5">
<Skeleton className="rounded-lg w-5 h-5" />
<ItemContent>
<Skeleton className="w-4/5 h-5" />
</ItemContent>
<ItemActions>
<Skeleton className="rounded-lg w-5 h-5" />
</ItemActions>
</Item>
);
}
function WordDefinitionLoading() {
const t = useTranslations("Home");
return (
<Marker>
<MarkerIcon>
<Spinner />
</MarkerIcon>
<MarkerContent>{t("loadingDefinition")}</MarkerContent>
</Marker>
);
}
function CollocationsLoading() {
const t = useTranslations("Home");
return (
<div className="flex flex-col gap-4">
<h3 className="font-semibold">{t("collocations")}</h3>
<Marker>
<MarkerIcon>
<Spinner />
</MarkerIcon>
<MarkerContent>{t("generatingCollocations")}</MarkerContent>
</Marker>
</div>
);
}
function ExamplesLoading() {
const t = useTranslations("Home");
return (
<div className="flex flex-col gap-4">
<h3 className="font-semibold">{t("usageExamples")}</h3>
<Marker>
<MarkerIcon>
<Spinner />
</MarkerIcon>
<MarkerContent>{t("generatingExamples")}</MarkerContent>
</Marker>
</div>
);
}
const CollectionsListPanel = dynamic(
() => import("@/components/collectionsList").then((mod) => mod.CollectionsList),
{
ssr: false,
loading: () => <CollectionsListLoading />,
}
);
const WordDefinitionPanel = dynamic(
() => import("@/components/wordDefinition").then((mod) => mod.WordDefinition),
{
ssr: false,
loading: () => <WordDefinitionLoading />,
}
);
const CollocationsPanel = dynamic(
() => import("@/components/collocations").then((mod) => mod.Collocations),
{
ssr: false,
loading: () => <CollocationsLoading />,
}
);
const ExamplesPanel = dynamic(
() => import("@/components/examples").then((mod) => mod.Examples),
{
ssr: false,
loading: () => <ExamplesLoading />,
}
);
interface Selection {
word: string;
lang: Language;
srcText?: string;
}
const WORD_ONLY_PATTERN = /^[\p{L}'-]+$/u;
function languageFromParam(value: string | null): UiLanguage | null {
const id = value ? parseLanguage(value) : null;
return id ? LANGUAGES.find((l) => l.id === id) ?? null : null;
}
function fallbackLanguage(id: Language): UiLanguage {
return LANGUAGES.find((l) => l.id !== id) ?? LANGUAGES[0];
}
import type { User } from "@/types/api";
interface HomeProps {
user: User | null;
rememberedSourceLang?: UiLanguage | null;
rememberedTargetLang?: UiLanguage | null;
}
export default function Home({ user, rememberedSourceLang, rememberedTargetLang }: HomeProps) {
const searchParams = useSearchParams();
const [sourceLang, setSourceLang] = useState<UiLanguage>(
() => languageFromParam(searchParams.get("sourceLang")) ?? rememberedSourceLang ?? DEFAULT_SOURCE_LANG
);
const [targetLang, setTargetLang] = useState<UiLanguage>(() => {
const fromUrl = languageFromParam(searchParams.get("targetLang"));
if (fromUrl && fromUrl.id !== sourceLang.id) return fromUrl;
const stored =
rememberedTargetLang && rememberedTargetLang.id !== sourceLang.id
? rememberedTargetLang
: null;
return stored ?? LANGUAGES.find((l) => l.id !== sourceLang.id) ?? DEFAULT_TARGET_LANG;
});
const [sourceText, setSourceText] = useState(() => searchParams.get("text") ?? "");
const [selection, setSelection] = useState<Selection | null>(null);
const [activeTab, setActiveTab] = useState("definition");
const [definitionResult, setDefinitionResult] = useState<Fetched<DictionaryResult> | null>(null);
const [collocationsResult, setCollocationsResult] = useState<Fetched<CollocationsResult> | null>(null);
const [examplesResult, setExamplesResult] = useState<Fetched<ExamplesResult> | null>(null);
const t = useTranslations("Home");
const { translatedText, result, isLoading, error } = useTranslation(
sourceText,
sourceLang.id,
targetLang.id
);
useEffect(() => {
const timeoutId = setTimeout(() => {
const params = new URLSearchParams();
if (sourceText.trim()) params.set("text", sourceText.trim());
params.set("sourceLang", sourceLang.id);
params.set("targetLang", targetLang.id);
window.history.replaceState(null, "", `/?${params.toString()}`);
}, TRANSLATION_DEBOUNCE_MS);
return () => clearTimeout(timeoutId);
}, [sourceText, sourceLang.id, targetLang.id]);
const isSingleWord = useMemo(() => {
if (!sourceText.trim()) return false;
const words = sourceText.trim().split(/\s+/);
return words.length === 1 && WORD_ONLY_PATTERN.test(words[0]);
}, [sourceText]);
const definition: Selection | null = useMemo(() => {
if (selection && selection.srcText === sourceText) return selection;
if (isSingleWord) {
return {
word: sourceText.trim(),
lang: sourceLang.id,
};
}
return null;
}, [selection, sourceText, isSingleWord, sourceLang.id]);
const debouncedDefinition = useDebouncedValue(
definition,
definition?.srcText ? 0 : LOOKUP_DEBOUNCE_MS
);
const selectSourceWord = useCallback(
(word: string) => setSelection({ word, lang: sourceLang.id, srcText: sourceText }),
[sourceLang.id, sourceText]
);
const selectTargetWord = useCallback(
(word: string) => setSelection({ word, lang: targetLang.id, srcText: sourceText }),
[targetLang.id, sourceText]
);
const handleSourceChange = useCallback(
(lang: UiLanguage) => {
setSourceLang(lang);
setSelection(null);
if (lang.id === targetLang.id) setTargetLang(fallbackLanguage(lang.id));
void setLanguages(lang.id, lang.id === targetLang.id ? fallbackLanguage(lang.id).id : targetLang.id);
},
[targetLang.id]
);
const handleTargetChange = useCallback(
(lang: UiLanguage) => {
setTargetLang(lang);
setSelection(null);
if (lang.id === sourceLang.id) setSourceLang(fallbackLanguage(lang.id));
void setLanguages(lang.id === sourceLang.id ? fallbackLanguage(lang.id).id : sourceLang.id, lang.id);
},
[sourceLang.id]
);
const handleSwap = useCallback(() => {
setSourceLang(targetLang);
setTargetLang(sourceLang);
setSourceText(translatedText);
void setLanguages(targetLang.id, sourceLang.id);
}, [sourceLang, targetLang, translatedText]);
const handleTabChange = useCallback((value: unknown) => {
if (typeof value === "string") setActiveTab(value);
}, []);
return (
<Main>
<Header user={user} />
<div className="flex flex-col md:flex-row gap-2 w-full items-stretch">
<TranslationCard
variant="source"
lang={sourceLang}
onLangChange={handleSourceChange}
excludeLangId={targetLang.id}
placeholder={t("sourcePlaceholder")}
text={sourceText}
onTextChange={setSourceText}
onSelectWord={selectSourceWord}
/>
<Button variant="outline" size="icon-lg" className="self-center shrink-0" onClick={handleSwap}>
<ArrowLeftRightIcon />
</Button>
<TranslationCard
variant="target"
lang={targetLang}
onLangChange={handleTargetChange}
excludeLangId={sourceLang.id}
placeholder={t("translatedPlaceholder")}
text={translatedText}
isLoading={isLoading}
error={error}
onSelectWord={selectTargetWord}
footerExtra={
result && (
<PropertyDialog
response={result}
definition={debouncedDefinition ? definitionResult : null}
examples={debouncedDefinition ? examplesResult : null}
collocations={debouncedDefinition ? collocationsResult : null}
/>
)
}
/>
</div>
{debouncedDefinition && <CollectionsListPanel lang={debouncedDefinition.lang} word={debouncedDefinition.word} />}
{debouncedDefinition && (
<Tabs value={activeTab} onValueChange={handleTabChange}>
<TabsList>
<TabsTrigger value="definition">{t("definition")}</TabsTrigger>
<TabsTrigger value="examples">{t("usageExamples")}</TabsTrigger>
<TabsTrigger value="collocations">{t("collocations")}</TabsTrigger>
</TabsList>
<TabsContent value="definition">
<Card>
<CardContent className="flex flex-col gap-4">
<WordDefinitionPanel
key={`${debouncedDefinition.lang}:${debouncedDefinition.word}:definition`}
word={debouncedDefinition.word}
lang={debouncedDefinition.lang}
onResult={setDefinitionResult}
/>
</CardContent>
</Card>
</TabsContent>
<TabsContent value="collocations">
<Card>
<CardContent className="flex flex-col gap-4">
<CollocationsPanel
key={`${debouncedDefinition.lang}:${debouncedDefinition.word}:collocations`}
word={debouncedDefinition.word}
lang={debouncedDefinition.lang}
onResult={setCollocationsResult}
/>
</CardContent>
</Card>
</TabsContent>
<TabsContent value="examples">
<Card>
<CardContent className="flex flex-col gap-4">
<ExamplesPanel
key={`${debouncedDefinition.lang}:${debouncedDefinition.word}:examples`}
word={debouncedDefinition.word}
lang={debouncedDefinition.lang}
onResult={setExamplesResult}
/>
</CardContent>
</Card>
</TabsContent>
</Tabs>
)}
</Main>
);
}