version 1
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

This commit is contained in:
Ivan Rezchikov
2026-09-18 00:45:51 +03:00
commit 628dd6384b
149 changed files with 11478 additions and 0 deletions
+9
View File
@@ -0,0 +1,9 @@
node_modules
.next
.git
.env
.env.*
Dockerfile
.dockerignore
tsconfig.tsbuildinfo
README.md
+9
View File
@@ -0,0 +1,9 @@
<!-- BEGIN:nextjs-agent-rules -->
# This is NOT the Next.js you know
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.
This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.
<!-- END:nextjs-agent-rules -->
+1
View File
@@ -0,0 +1 @@
@AGENTS.md
+30
View File
@@ -0,0 +1,30 @@
FROM oven/bun:1 AS builder
WORKDIR /app
COPY bun.lock package.json ./
RUN bun install --frozen-lockfile
COPY . .
RUN bun run build
FROM node:22 AS runtime
WORKDIR /app
ENV NODE_ENV=production \
NEXT_TELEMETRY_DISABLED=1
COPY --from=builder /app/package.json /app/bun.lock \
/app/next.config.ts /app/tsconfig.json /app/next-env.d.ts /app/postcss.config.mjs \
./
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/.next ./.next
COPY --from=builder /app/public ./public
COPY --from=builder /app/i18n ./i18n
COPY --from=builder /app/messages ./messages
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
CMD wget -q --spider http://localhost:3000/ || exit 1
CMD ["node_modules/.bin/next", "start", "-H", "0.0.0.0", "-p", "3000"]
+36
View File
@@ -0,0 +1,36 @@
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
@@ -0,0 +1,152 @@
"use client";
import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import { InfoIcon, MenuIcon } from "lucide-react";
import {
Dialog,
DialogClose,
DialogContent,
DialogFooter,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import {
Field,
FieldGroup,
FieldLabel,
FieldSet,
} from "@/components/ui/field";
import { CollectionResult } from "@/types/api";
import { formatDate } from "@/lib/formatDate";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { deleteCollection, updateCollection } from "@/lib/api";
import { resolveApiErrorMessage } from "@/lib/useApiErrorMessage";
import { Spinner } from "@/components/ui/spinner";
export function MenuDialog({ collection }: { collection: CollectionResult }) {
const router = useRouter();
const [open, setOpen] = useState(false);
const [name, setName] = useState(collection.name);
const [error, setError] = useState<string | null>(null);
const [isDeleting, startDelete] = useTransition();
const [isUpdating, startUpdate] = useTransition();
const tt = useTranslations("Time");
const t = useTranslations("CollectionMenu");
const tc = useTranslations("Common");
const tl = useTranslations("Languages");
const tApi = useTranslations("ApiErrors");
const isAuto = collection.type === "auto";
const isBusy = isDeleting || isUpdating;
const handleDelete = () => {
setError(null);
startDelete(async () => {
try {
await deleteCollection(collection.id);
router.push("/collections");
} catch (err) {
setError(resolveApiErrorMessage(err, (kind) => tApi(kind), t("deleteFailed")));
}
});
};
const handleUpdate = () => {
setError(null);
startUpdate(async () => {
try {
await updateCollection(collection.id, name);
router.refresh();
setOpen(false);
} catch (err) {
setError(resolveApiErrorMessage(err, (kind) => tApi(kind), t("updateFailed")));
}
});
};
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger
render={
<Button variant="outline" size="icon">
<MenuIcon />
</Button>
}
/>
<DialogContent>
<DialogTitle>{t("title")}</DialogTitle>
{isAuto && (
<Alert>
<InfoIcon />
<AlertTitle>{t("autoTitle")}</AlertTitle>
<AlertDescription>{t("autoDescription")}</AlertDescription>
</Alert>
)}
{error && (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<FieldSet className="w-full">
<FieldGroup>
<div className="flex flex-col gap-2">
<Field className="mb-1">
<FieldLabel htmlFor="name">{t("nameLabel")}</FieldLabel>
<Input
id="name"
type="text"
placeholder={t("namePlaceholder")}
value={name === "history" ? tc("history") : name}
onChange={(e) => setName(e.target.value)}
disabled={isAuto || isBusy}
/>
</Field>
<div className="flex flex-row items-center justify-between">
<h5 className="font-medium">{t("language")}</h5>
<h5>{tl(collection.lang)}</h5>
</div>
<div className="flex flex-row items-center justify-between">
<h5 className="font-medium">{t("wordCount")}</h5>
<h5>{collection.words.length}</h5>
</div>
<div className="flex flex-row items-center justify-between">
<h5 className="font-medium">{t("lastUpdate")}</h5>
<h5>{formatDate(collection.updated_at, tt)}</h5>
</div>
<div className="flex flex-row items-center justify-between">
<h5 className="font-medium">{t("created")}</h5>
<h5>{formatDate(collection.created_at, tt)}</h5>
</div>
</div>
</FieldGroup>
</FieldSet>
<DialogFooter>
<div className="flex flex-row items-start justify-between w-full">
<div className="flex flex-row gap-2 items-center">
<Button onClick={handleUpdate} disabled={isAuto || isBusy || name.trim() === collection.name}>
{isUpdating && <Spinner />}{tc("update")}
</Button>
<DialogClose
render={<Button variant="outline" disabled={isBusy} />}
>
{tc("cancel")}
</DialogClose>
</div>
<Button variant="destructive" onClick={handleDelete} disabled={isAuto || isBusy}>
{isUpdating && <Spinner />}{t("delete")}
</Button>
</div>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,70 @@
import HeaderWithAuth from "@/components/headerWithAuth";
import Main from "@/components/main";
import { ArrowLeftIcon } from "lucide-react";
import Link from "next/link";
import { notFound } from "next/navigation";
import { isApiError } from "@/lib/api";
import { getCollection } from "@/lib/serverApi";
import { LANGUAGES } from "@/lib/languages";
import type { CollectionResult } from "@/types/api";
import { MenuDialog } from "./menuDialog";
import { getTranslations } from "next-intl/server";
import { WordsSearch } from "./wordsSearch";
export default async function CollectionPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const tCollections = await getTranslations("Collections");
const tc = await getTranslations("Common");
const tl = await getTranslations("Languages");
const tApi = await getTranslations("ApiErrors");
let collection: CollectionResult;
try {
collection = await getCollection(id);
} catch (err) {
if (isApiError(err) && err.kind === "not-found") notFound();
const message = isApiError(err) ? tApi(err.kind) : tc("somethingWrong");
return (
<Main>
<HeaderWithAuth />
<p className="text-destructive">{message}</p>
</Main>
);
}
const language = LANGUAGES.find((l) => l.id === collection.lang);
const words = [...collection.words].reverse();
return (
<Main>
<HeaderWithAuth />
<Link href="/collections" className="flex items-center gap-1.5 text-muted-foreground w-fit">
<ArrowLeftIcon size={16} /><p>{tCollections("title")}</p>
</Link>
<div className="flex flex-row items-start justify-between">
<div className="flex flex-col gap-2.5 justify-between">
<h2 className="font-semibold">{collection.name === "history" ? tc("history") : collection.name}</h2>
<div className="flex flex-row gap-8">
<h3 className="font-medium">{collection.words.length} {collection.words.length === 1 ? tc("word") : tc("words")}</h3>
{language && <div className="flex flex-row gap-2.5 items-center">
<h3 className="font-medium">{tl(language.id)}</h3>
</div>}
</div>
</div>
<MenuDialog collection={collection} />
</div>
<WordsSearch
words={words}
lang={collection.lang}
collectionId={collection.id}
isRemovable={collection.type === "user"}
placeholder={tc("search")}
noWordsLabel={tCollections("noWords")}
noResultsLabel={tCollections("noSearchResults")}
/>
</Main>
);
}
@@ -0,0 +1,27 @@
"use client";
import { useTransition } from "react";
import { XIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { deleteWordFromCollection } from "@/lib/api";
import { Spinner } from "@/components/ui/spinner";
export function RemoveWordButton({ collectionId, word }: { collectionId: string; word: string }) {
const router = useRouter();
const [isPending, startTransition] = useTransition();
const handleClick = () => {
startTransition(async () => {
try {
await deleteWordFromCollection(collectionId, word);
router.refresh();
} catch {
}
});
};
return (
isPending ? <Spinner className="text-muted-foreground" /> :
<XIcon size={18} onClick={handleClick} className="text-muted-foreground cursor-pointer" />
);
}
@@ -0,0 +1,74 @@
"use client";
import Link from "next/link";
import { useMemo } from "react";
import { ArrowRightIcon } from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { lookupDictionary } from "@/lib/api";
import { useResource } from "@/hooks/useResource";
import { useTranslations } from "next-intl";
import type { DictionaryResult, Language } from "@/types/api";
import { RemoveWordButton } from "./removeWordButton";
export function WordCard({
word,
lang,
collectionId,
isRemovable,
}: {
word: string;
lang: Language;
collectionId: string;
isRemovable: boolean;
}) {
const td = useTranslations("Definition");
const key = `dict:${lang}:${word.toLowerCase()}`;
const state = useResource<DictionaryResult>(key, () => lookupDictionary(lang, word));
const definition = useMemo(() => {
if (state.status !== "done" || !state.data) return undefined;
const entry = state.data.entries[0];
if (!entry) return null;
return {
text: entry.senses[0]?.definition ?? null,
quantity: entry.senses.length,
};
}, [state]);
return (
<Card size="sm" className="h-full flex flex-col">
<CardHeader>
<div className="flex flex-row items-center justify-between">
<CardTitle><h4>{word}</h4></CardTitle>
<div className="flex flex-row items-center gap-2">
{isRemovable && <RemoveWordButton collectionId={collectionId} word={word} />}
<Link href={`/?text=${encodeURIComponent(word)}&sourceLang=${lang}`}>
<ArrowRightIcon size={18} className="text-muted-foreground" />
</Link>
</div>
</div>
</CardHeader>
<CardContent className="flex-1">
{state.status === "loading" ? (
<div className="flex flex-col gap-2">
<Skeleton className="w-full h-4" />
<Skeleton className="w-2/3 h-4" />
</div>
) : state.status === "error" || !definition?.text ? (
<h5 className="text-muted-foreground italic">{td("notFound")}</h5>
) : (
<div className="flex flex-col gap-2">
<h5 className="text-muted-foreground line-clamp-3">
{definition.text}
{definition.quantity > 1 && (
<span className="italic"> {td("otherDefinitions", { count: definition.quantity - 1 })}</span>
)}
</h5>
</div>
)}
</CardContent>
</Card>
);
}
@@ -0,0 +1,69 @@
"use client";
import { useMemo, useState } from "react";
import { InputGroup, InputGroupAddon, InputGroupInput } from "@/components/ui/input-group";
import { SearchIcon } from "lucide-react";
import type { Language } from "@/types/api";
import { WordCard } from "./wordCard";
interface WordsSearchProps {
words: string[];
lang: Language;
collectionId: string;
isRemovable: boolean;
placeholder: string;
noWordsLabel: string;
noResultsLabel: string;
}
export function WordsSearch({
words,
lang,
collectionId,
isRemovable,
placeholder,
noWordsLabel,
noResultsLabel,
}: WordsSearchProps) {
const [query, setQuery] = useState("");
const filtered = useMemo(() => {
const q = query.trim().toLowerCase();
if (!q) return words;
return words.filter((w) => w.toLowerCase().includes(q));
}, [words, query]);
return (
<div className="flex flex-col gap-4">
<InputGroup className="max-w-sm">
<InputGroupInput
placeholder={placeholder}
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
<InputGroupAddon>
<SearchIcon />
</InputGroupAddon>
</InputGroup>
{words.length === 0 ? (
<p className="text-muted-foreground mx-auto">{noWordsLabel}</p>
) : filtered.length === 0 ? (
<p className="text-muted-foreground mx-auto">{noResultsLabel}</p>
) : (
<div className="grid md:grid-cols-4 gap-4">
{filtered.map((word) => (
<div key={word}>
<WordCard
word={word}
lang={lang}
collectionId={collectionId}
isRemovable={isRemovable}
/>
</div>
))}
</div>
)}
</div>
);
}
@@ -0,0 +1,111 @@
"use client";
import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import { PlusIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogFooter,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Field, FieldGroup, FieldLabel, FieldSet } from "@/components/ui/field";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Spinner } from "@/components/ui/spinner";
import { LanguageSelect } from "@/components/languageSelect";
import { createCollection } from "@/lib/api";
import { resolveApiErrorMessage } from "@/lib/useApiErrorMessage";
import { DEFAULT_SOURCE_LANG } from "@/lib/languages";
import type { UiLanguage } from "@/types/language";
export function CreateCollectionDialog() {
const router = useRouter();
const t = useTranslations("Collections");
const tc = useTranslations("Common");
const tApi = useTranslations("ApiErrors");
const [open, setOpen] = useState(false);
const [name, setName] = useState("");
const [lang, setLang] = useState<UiLanguage>(DEFAULT_SOURCE_LANG);
const [error, setError] = useState<string | null>(null);
const [isPending, startTransition] = useTransition();
const reset = () => {
setName("");
setLang(DEFAULT_SOURCE_LANG);
setError(null);
};
const handleCreate = () => {
const trimmed = name.trim();
if (!trimmed) return;
setError(null);
startTransition(async () => {
try {
const collection = await createCollection(trimmed, lang.id);
setOpen(false);
reset();
router.push(`/collections/${collection.id}`);
} catch (err) {
setError(resolveApiErrorMessage(err, (kind) => tApi(kind), t("createFailed")));
}
});
};
return (
<Dialog
open={open}
onOpenChange={(next) => {
setOpen(next);
if (!next) reset();
}}
>
<DialogTrigger
render={
<Button variant="outline" size="icon-sm">
<PlusIcon />
</Button>
}
/>
<DialogContent>
<DialogTitle>{t("createTitle")}</DialogTitle>
{error && (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<FieldSet className="w-full">
<FieldGroup>
<Field>
<FieldLabel htmlFor="collection-name">{t("nameLabel")}</FieldLabel>
<Input
id="collection-name"
type="text"
placeholder={t("namePlaceholder")}
value={name}
onChange={(e) => setName(e.target.value)}
disabled={isPending}
/>
</Field>
<Field>
<FieldLabel>{t("languageLabel")}</FieldLabel>
<LanguageSelect value={lang} onChange={setLang} />
</Field>
</FieldGroup>
</FieldSet>
<DialogFooter>
<Button onClick={handleCreate} disabled={isPending || !name.trim()}>
{isPending && <Spinner />}
{tc("create")}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,81 @@
import HeaderWithAuth from "@/components/headerWithAuth";
import Main from "@/components/main";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import Link from "next/link";
import { isApiError } from "@/lib/api";
import { getCollections } from "@/lib/serverApi";
import type { CollectionResult } from "@/types/api";
import { formatDate, type RelativeTimeTranslator } from "@/lib/formatDate";
import { getTranslations } from "next-intl/server";
import { CreateCollectionDialog } from "./createCollectionDialog";
type Translator = (key: string, values?: Record<string, string | number | Date>) => string;
function CollectionCard({ collection, tc, tt, tl }: { collection: CollectionResult; tc: Translator; tt: RelativeTimeTranslator; tl: Translator }) {
return (
<Card size="sm" className="justify-between">
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle><h4>{collection.name === "history" ? tc("history") : collection.name}</h4></CardTitle>
<h5 className="flex flex-row gap-0.5 items-center text-muted-foreground">
{tl(collection.lang)}
</h5>
</div>
<CardDescription>
<p>{collection.words.length} {collection.words.length === 1 ? tc("word") : tc("words")} &bull; {tc("updated")} {formatDate(collection.updated_at, tt)}</p>
</CardDescription>
</CardHeader>
{collection.words.length > 0 && (<CardContent>
<div className="flex flex-wrap gap-1.5 items-center">
{[...collection.words].reverse().slice(0, 3).map((w) => (
<Badge key={w} variant="outline">{w}</Badge>
))}
{collection.words.length > 3 && <h6 className="text-muted-foreground">{tc("andMore", { count: collection.words.length - 3 })}</h6>}
</div>
</CardContent>)}
<CardFooter className="flex gap-2">
<Link href={`/collections/${collection.id}`} className="w-full">
<Button variant="outline" size="sm" className="w-full">{tc("seeAll")}</Button>
</Link>
</CardFooter>
</Card>
);
}
export default async function Collections() {
const tt = await getTranslations("Time");
const tc = await getTranslations("Common");
const tl = await getTranslations("Languages");
const tCollections = await getTranslations("Collections");
const tApi = await getTranslations("ApiErrors");
let collections: CollectionResult[] = [];
let error: string | null = null;
try {
collections = await getCollections();
} catch (err) {
error = isApiError(err) ? tApi(err.kind) : tc("somethingWrong");
}
return (
<Main>
<HeaderWithAuth />
<div className="flex flex-row items-center gap-4">
<h2 className="font-semibold">{tCollections("title")}</h2>
<CreateCollectionDialog />
</div>
{error ? (
<p className="text-muted-foreground">{error}</p>
) : (
<div className="grid md:grid-cols-4 gap-4">
{collections.map((c) => (
<CollectionCard key={c.id} collection={c} tc={tc} tt={tt} tl={tl} />
))}
</div>
)}
</Main>
);
}
+10
View File
@@ -0,0 +1,10 @@
import { redirect } from "next/navigation";
import { getUser } from "@/lib/session";
import { UserProvider } from "@/providers/userProvider";
export default async function ProtectedLayout({ children }: { children: React.ReactNode }) {
const user = await getUser();
if (!user) redirect("/oauth/login");
return <UserProvider user={user}>{children}</UserProvider>;
}
+21
View File
@@ -0,0 +1,21 @@
"use server";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { backendFetch } from "@/lib/backend";
export async function logout() {
const store = await cookies();
const token = store.get("session")?.value;
if (token) {
try {
await backendFetch("/api/auth/session", { method: "DELETE" });
} catch {
// Ignore connection errors; still clear the local session.
}
}
store.delete("session");
redirect("/");
}
@@ -0,0 +1,10 @@
"use server";
import { cookies } from "next/headers";
import { Language } from "@/types/api";
export async function setLanguages(sourceLang: Language, targetLang: Language) {
const store = await cookies();
store.set("sourceLang", sourceLang, { path: "/", maxAge: 60 * 60 * 24 * 365 });
store.set("targetLang", targetLang, { path: "/", maxAge: 60 * 60 * 24 * 365 });
}
+10
View File
@@ -0,0 +1,10 @@
"use server";
import { cookies } from "next/headers";
import { LANGUAGE_CODES } from "@/types/api";
export async function setLocale(locale: string) {
if (!(LANGUAGE_CODES as readonly string[]).includes(locale)) return;
const store = await cookies();
store.set("locale", locale, { path: "/", maxAge: 60 * 60 * 24 * 365 });
}
+41
View File
@@ -0,0 +1,41 @@
import { NextRequest, NextResponse } from "next/server";
import { backendFetch } from "@/lib/backend";
import { cookies } from "next/headers";
const CACHE_REVALIDATE = 60 * 60 * 24;
const CACHEABLE_RESOURCES = /^\/api\/(dictionary|collocations|examples)\//;
function isCacheableResource(method: string, pathname: string, search: string) {
return method === "GET" && !search && CACHEABLE_RESOURCES.test(pathname);
}
async function handler(request: NextRequest, { params }: { params: Promise<{ path: string[] }> }) {
const { path } = await params;
const pathname = `/api/${path.join("/")}`;
const hasBody = !["GET", "HEAD"].includes(request.method);
const hasSession = (await cookies()).get("session")?.value !== undefined;
const resource =
isCacheableResource(request.method, pathname, request.nextUrl.search) && !hasSession;
const response = await backendFetch(`${pathname}${request.nextUrl.search}`, {
method: request.method,
headers: hasBody
? { "Content-Type": request.headers.get("content-type") ?? "application/json" }
: undefined,
body: hasBody ? await request.text() : undefined,
next: resource ? { revalidate: CACHE_REVALIDATE } : undefined,
});
const headers = new Headers();
const contentType = response.headers.get("content-type");
if (contentType) headers.set("Content-Type", contentType);
if (resource && response.ok) headers.set("Cache-Control", `public, s-maxage=${CACHE_REVALIDATE}`);
return new NextResponse(await response.text(), {
status: response.status,
headers,
});
}
export { handler as GET, handler as POST, handler as PATCH, handler as DELETE };
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

+185
View File
@@ -0,0 +1,185 @@
@import "tailwindcss";
@import "tw-animate-css";
@import "shadcn/tailwind.css";
@custom-variant dark (&:is(.dark *));
@theme {
--text-xs--line-height: 1.5;
--text-sm--line-height: 1.45;
--text-base--line-height: 1.5;
--text-lg--line-height: 1.4;
--text-xl--line-height: 1.35;
--text-2xl--line-height: 1.3;
--text-3xl--line-height: 1.25;
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-sans);
--font-mono: var(--font-geist-mono);
--font-heading: var(--font-sans);
--color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar: var(--sidebar);
--color-chart-5: var(--chart-5);
--color-chart-4: var(--chart-4);
--color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1);
--color-ring: var(--ring);
--color-input: var(--input);
--color-border: var(--border);
--color-destructive: var(--destructive);
--color-accent-foreground: var(--accent-foreground);
--color-accent: var(--accent);
--color-muted-foreground: var(--muted-foreground);
--color-muted: var(--muted);
--color-secondary-foreground: var(--secondary-foreground);
--color-secondary: var(--secondary);
--color-primary-foreground: var(--primary-foreground);
--color-primary: var(--primary);
--color-popover-foreground: var(--popover-foreground);
--color-popover: var(--popover);
--color-card-foreground: var(--card-foreground);
--color-card: var(--card);
--radius-sm: calc(var(--radius) * 0.6);
--radius-md: calc(var(--radius) * 0.8);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) * 1.4);
--radius-2xl: calc(var(--radius) * 1.8);
--radius-3xl: calc(var(--radius) * 2.2);
--radius-4xl: calc(var(--radius) * 2.6);
}
:root {
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
--card: oklch(1 0 0);
--card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.205 0 0);
--primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.97 0 0);
--secondary-foreground: oklch(0.205 0 0);
--muted: oklch(0.97 0 0);
--muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.97 0 0);
--accent-foreground: oklch(0.205 0 0);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.87 0 0);
--chart-2: oklch(0.556 0 0);
--chart-3: oklch(0.439 0 0);
--chart-4: oklch(0.371 0 0);
--chart-5: oklch(0.269 0 0);
--radius: 0.625rem;
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: oklch(0.205 0 0);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.97 0 0);
--sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0);
}
.dark {
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--card: oklch(0.205 0 0);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.205 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.922 0 0);
--primary-foreground: oklch(0.205 0 0);
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.556 0 0);
--chart-1: oklch(0.87 0 0);
--chart-2: oklch(0.556 0 0);
--chart-3: oklch(0.439 0 0);
--chart-4: oklch(0.371 0 0);
--chart-5: oklch(0.269 0 0);
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.269 0 0);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.556 0 0);
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
button:not(:disabled), [role="button"]:not(:disabled) {
cursor: pointer;
}
html {
@apply font-sans;
}
}
h1 {
font-size: clamp(1.5rem, 1.3446rem + 0.663vw, 1.875rem);
line-height: 1.15;
letter-spacing: -0.03em;
}
h2 {
font-size: clamp(1.25rem, 1.1464rem + 0.442vw, 1.5rem);
line-height: 1.2;
letter-spacing: -0.025em;
}
h3 {
font-size: clamp(1.125rem, 1.0732rem + 0.221vw, 1.25rem);
line-height: 1.3;
letter-spacing: -0.02em;
}
h4 {
font-size: clamp(1rem, 0.9482rem + 0.221vw, 1.125rem);
line-height: 1.35;
letter-spacing: -0.02em;
}
h5 {
font-size: clamp(0.875rem, 0.6982rem + 0.221vw, 0.875rem);
line-height: 1.4;
letter-spacing: -0.015em;
}
h6 {
font-size: clamp(0.6875rem, 0.6616rem + 0.111vw, 0.75rem);
line-height: 1.4;
letter-spacing: -0.01em;
}
p {
font-size: 1rem;
line-height: 1.5;
letter-spacing: -0.011em;
}
+39
View File
@@ -0,0 +1,39 @@
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import { cookies } from "next/headers";
import "./globals.css";
import { cn } from "@/lib/utils";
import { NextIntlClientProvider } from "next-intl";
import { ThemeProvider } from "@/components/themeProvider";
import { LANGUAGE_CODES } from "@/types/api";
const inter = Inter({
weight: ["400", "500", "600"],
subsets: ["latin", "latin-ext", "cyrillic"],
variable: "--font-sans"
});
export const metadata: Metadata = {
title: "Fancy",
};
export default async function RootLayout({ children }: LayoutProps<"/">) {
const requested = (await cookies()).get("locale")?.value ?? "";
const lang = LANGUAGE_CODES.includes(requested as (typeof LANGUAGE_CODES)[number])
? requested
: "en";
return (
<html
lang={lang}
className={cn("h-full", "antialiased", "font-sans", inter.variable)}
suppressHydrationWarning
>
<body className="min-h-full flex flex-col selection:bg-zinc-300/50 dark:selection:bg-blue-400/50">
<ThemeProvider attribute="class" defaultTheme="system" enableSystem disableTransitionOnChange>
<NextIntlClientProvider>{children}</NextIntlClientProvider>
</ThemeProvider>
</body>
</html>
);
}
@@ -0,0 +1,62 @@
import { NextResponse } from "next/server";
import { cookies } from "next/headers";
export async function GET(req: Request) {
const url = new URL(req.url);
const code = url.searchParams.get("code");
const state = url.searchParams.get("state");
const oauthError = url.searchParams.get("error");
const cookieStore = await cookies();
const storedState = cookieStore.get("oauth_state")?.value;
const verifier = cookieStore.get("oauth_verifier")?.value;
const fail = (reason: string) => {
const response = NextResponse.redirect(
new URL(`/oauth/error?reason=${reason}`, url.origin)
);
response.cookies.delete("oauth_verifier");
response.cookies.delete("oauth_state");
return response;
};
if (oauthError || !code || !state || !verifier) return fail("auth_failed");
if (state !== storedState) return fail("state_mismatch");
const tokenResponse = await fetch(process.env.KOTOSOFT_ID_TOKEN_URL!, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "authorization_code",
code,
client_id: process.env.CLIENT_ID!,
client_secret: process.env.CLIENT_SECRET!,
redirect_uri: process.env.REDIRECT_URI!,
code_verifier: verifier,
}),
});
if (!tokenResponse.ok) return fail("token_exchange_failed");
const { access_token } = await tokenResponse.json();
const sessionResponse = await fetch(`${process.env.BACKEND_URL}/api/auth/session`, {
method: "POST",
headers: { Authorization: `Bearer ${access_token}` },
});
if (!sessionResponse.ok) return fail("session_failed");
const { session_token } = await sessionResponse.json();
const response = NextResponse.redirect(new URL("/collections", url.origin));
response.cookies.set("session", session_token, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
path: "/",
maxAge: 60 * 60 * 24 * 30,
});
response.cookies.delete("oauth_verifier");
response.cookies.delete("oauth_state");
return response;
}
+29
View File
@@ -0,0 +1,29 @@
import Link from "next/link";
import { getTranslations } from "next-intl/server";
import { Button } from "@/components/ui/button";
import Main from "@/components/main";
export default async function OAuthErrorPage({
searchParams,
}: {
searchParams: Promise<{ reason?: string }>;
}) {
const { reason = "auth_failed" } = await searchParams;
const t = await getTranslations("OAuth");
const tc = await getTranslations("Common");
const message = t(reason as never);
return (
<Main>
<div className="flex flex-col gap-4 items-center justify-center min-h-[60vh] text-center">
<h1 className="font-semibold text-xl">{t("title")}</h1>
<p className="text-muted-foreground max-w-md">{message}</p>
<Button nativeButton={false} render={<Link href="/oauth/login" />}>{t("tryAgain")}</Button>
<Button nativeButton={false} variant="ghost" render={<Link href="/" />}>
{tc("close")}
</Button>
</div>
</Main>
);
}
+42
View File
@@ -0,0 +1,42 @@
import { NextResponse } from "next/server";
import { cookies, headers as fetchHeaders } from "next/headers";
import { generateCodeVerifier, generateCodeChallenge, generateState } from "@/lib/pkce";
const FLOW_TTL = 60 * 10;
export async function GET() {
if ((await cookies()).get("session")) {
const headers = await fetchHeaders();
const protocol = headers.get("x-forwarded-proto") ?? "http";
const host = headers.get("host");
const origin = host ? `${protocol}://${host}` : "http://localhost:3000";
return NextResponse.redirect(new URL("/", origin));
}
const verifier = generateCodeVerifier();
const challenge = generateCodeChallenge(verifier);
const state = generateState();
const authorizeUrl = new URL(process.env.KOTOSOFT_ID_AUTHORIZE_URL!);
authorizeUrl.searchParams.set("response_type", "code");
authorizeUrl.searchParams.set("client_id", process.env.CLIENT_ID!);
authorizeUrl.searchParams.set("redirect_uri", process.env.REDIRECT_URI!);
authorizeUrl.searchParams.set("scope", "profile:read");
authorizeUrl.searchParams.set("code_challenge", challenge);
authorizeUrl.searchParams.set("code_challenge_method", "S256");
authorizeUrl.searchParams.set("state", state);
const response = NextResponse.redirect(authorizeUrl);
const cookieOpts = {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax" as const,
maxAge: FLOW_TTL,
path: "/",
};
response.cookies.set("oauth_verifier", verifier, cookieOpts);
response.cookies.set("oauth_state", state, cookieOpts);
return response;
}
+36
View File
@@ -0,0 +1,36 @@
import { Suspense } from "react";
import { cookies } from "next/headers";
import Home from "@/components/home";
import { HomeSkeleton } from "@/components/homeSkeleton";
import { getUser } from "@/lib/session";
import { LANGUAGES } from "@/lib/languages";
import { parseLanguage } from "@/types/api";
import type { UiLanguage } from "@/types/language";
export default function Page() {
return (
<Suspense fallback={<HomeSkeleton />}>
<HomeLoader />
</Suspense>
);
}
function rememberedLanguage(value: string | undefined | null): UiLanguage | null {
const id = value ? parseLanguage(value) : null;
if (!id) return null;
return LANGUAGES.find((l) => l.id === id) ?? null;
}
async function HomeLoader() {
const store = await cookies();
const rememberedSourceLang = rememberedLanguage(store.get("sourceLang")?.value);
const rememberedTargetLang = rememberedLanguage(store.get("targetLang")?.value);
const user = await getUser();
return (
<Home
user={user}
rememberedSourceLang={rememberedSourceLang}
rememberedTargetLang={rememberedTargetLang}
/>
);
}
File diff suppressed because it is too large Load Diff
+25
View File
@@ -0,0 +1,25 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "base-nova",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "",
"css": "app/globals.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"iconLibrary": "lucide",
"rtl": false,
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"menuColor": "default",
"menuAccent": "subtle",
"registries": {}
}
@@ -0,0 +1,21 @@
import { memo } from "react";
import { cn } from "@/lib/utils";
interface ClickableWordProps {
word: string;
onSelect?: (word: string) => void;
}
export const ClickableWord = memo(function ClickableWord({ word, onSelect }: ClickableWordProps) {
return (
<span
className={cn(
"-mx-1 px-1 py-0.5 cursor-pointer rounded-sm transition-colors",
"hover:bg-accent hover:text-accent-foreground"
)}
onClick={() => onSelect?.(word)}
>
{word}
</span>
);
});
@@ -0,0 +1,114 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { useTranslations } from "next-intl";
import { getCollectionsByWord } from "@/lib/api";
import { resolveApiErrorMessage } from "@/lib/useApiErrorMessage";
import { CollectionResult, Fetched, Language } from "@/types/api";
import { Item, ItemActions, ItemContent } from "./ui/item";
import { Skeleton } from "./ui/skeleton";
import { CollectionsListDialog } from "./collectionsListDialog";
interface CollectionsListProps {
word: string;
lang: Language;
onResult?: (result: Fetched<CollectionResult[]>) => void;
}
type ListState =
| { status: "loading" }
| { status: "error"; error: unknown }
| { status: "done"; collections: CollectionResult[] };
export function CollectionsList({ word, lang, onResult }: CollectionsListProps) {
const [byKey, setByKey] = useState<Record<string, ListState>>({});
const key = `${lang}:${word}`;
const state = byKey[key] ?? { status: "loading" };
const onResultRef = useRef(onResult);
useEffect(() => {
onResultRef.current = onResult;
});
useEffect(() => {
let cancelled = false;
getCollectionsByWord(lang, word)
.then((data) => {
if (cancelled) return;
setByKey((prev) => ({ ...prev, [key]: { status: "done", collections: data } }));
onResultRef.current?.(
Object.assign(data, { fetched_at: new Date().toISOString() })
);
})
.catch((error) => {
if (cancelled) return;
setByKey((prev) => ({ ...prev, [key]: { status: "error", error } }));
});
return () => {
cancelled = true;
};
}, [lang, word, key]);
const t = useTranslations("CollectionsList");
const tApi = useTranslations("ApiErrors");
const errorMessage =
state.status === "error"
? resolveApiErrorMessage(
state.error,
(kind) => (kind === "not-found" ? t("notFound") : tApi(kind)),
t("notFound")
)
: null;
const applyOptimistic = (collection: CollectionResult, adding: boolean) => {
if (state.status !== "done") return () => {};
const previous = state.collections;
setByKey((prev) => ({
...prev,
[key]: {
status: "done",
collections: adding
? [...previous, collection]
: previous.filter((c) => c.id !== collection.id),
},
}));
return () =>
setByKey((prev) => ({ ...prev, [key]: { status: "done", collections: previous } }));
};
return (
<div className="flex flex-col gap-4">
{state.status === "loading" && (
<Item variant="outline" className="w-full">
<ItemContent>
<Skeleton className="w-4/5 h-4" />
<Skeleton className="w-full h-4" />
</ItemContent>
<ItemActions>
<Skeleton className="rounded-lg w-24 h-8" />
</ItemActions>
</Item>
)}
{state.status === "error" && (
<p className="text-muted-foreground">{errorMessage}</p>
)}
{state.status === "done" && (
<div className="flex flex-col md:w-1/5 gap-2">
<CollectionsListDialog
lang={lang}
word={word}
selectedCollections={state.collections}
onOptimisticToggle={applyOptimistic}
/>
</div>
)}
</div>
);
}
@@ -0,0 +1,188 @@
"use client";
import { useEffect, useState } from "react";
import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import { ChevronRightIcon, PlusIcon, XIcon } from "lucide-react";
import { Dialog, DialogContent, DialogFooter, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Skeleton } from "@/components/ui/skeleton";
import { CollectionResult, Language } from "@/types/api";
import { addWordsToCollection, deleteWordFromCollection, getCollections } from "@/lib/api";
import { resolveApiErrorMessage } from "@/lib/useApiErrorMessage";
import { Item, ItemActions, ItemContent, ItemMedia, ItemTitle } from "./ui/item";
interface CollectionsListDialogProps {
lang: Language;
word: string;
selectedCollections: CollectionResult[];
onOptimisticToggle: (collection: CollectionResult, adding: boolean) => () => void;
}
type AllCollectionsState =
| { status: "loading" }
| { status: "error"; error: unknown }
| { status: "done"; collections: CollectionResult[] };
export function CollectionsListDialog({
lang,
word,
selectedCollections,
onOptimisticToggle,
}: CollectionsListDialogProps) {
const [open, setOpen] = useState(false);
const [state, setState] = useState<AllCollectionsState>({ status: "loading" });
const [rowErrors, setRowErrors] = useState<Record<string, string>>({});
const t = useTranslations("CollectionsList");
const tc = useTranslations("Common");
const tApi = useTranslations("ApiErrors");
const handleOpenChange = (next: boolean) => {
setOpen(next);
if (next) setState({ status: "loading" });
};
useEffect(() => {
if (!open) return;
let cancelled = false;
getCollections()
.then((all) => {
if (cancelled) return;
setState({
status: "done",
collections: all.filter((c) => c.lang === lang && c.type === "user"),
});
})
.catch((error) => {
if (!cancelled) setState({ status: "error", error });
});
return () => {
cancelled = true;
};
}, [open, lang]);
const selectedIds = new Set(selectedCollections.map((c) => c.id));
const toggle = (collection: CollectionResult) => {
const alreadyIn = selectedIds.has(collection.id);
setRowErrors((prev) => ({ ...prev, [collection.id]: "" }));
const rollback = onOptimisticToggle(collection, !alreadyIn);
const request = alreadyIn
? deleteWordFromCollection(collection.id, word)
: addWordsToCollection(collection.id, [word]);
request.catch((error) => {
rollback();
setRowErrors((prev) => ({
...prev,
[collection.id]: resolveApiErrorMessage(error, (kind) => tApi(kind), t("toggleFailed")),
}));
});
};
const errorMessage =
state.status === "error"
? resolveApiErrorMessage(state.error, (kind) => tApi(kind), t("loadFailed"))
: null;
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogTrigger>
<Item variant="muted" size="sm" className="cursor-pointer">
<ItemMedia>
<PlusIcon className="size-5" />
</ItemMedia>
<ItemContent>
<ItemTitle>{t("trigger")}</ItemTitle>
</ItemContent>
<ItemActions>
<ChevronRightIcon className="size-4" />
</ItemActions>
</Item>
</DialogTrigger>
<DialogContent>
<DialogTitle>{t("dialogTitle", { word })}</DialogTitle>
{state.status === "loading" && (
<div className="flex flex-col gap-2">
<Item variant="muted">
<ItemContent className="flex flex-row items-center justify-between">
<Skeleton className="w-1/2 h-4" />
<Skeleton className="w-1/4 h-8" />
</ItemContent>
</Item>
<Item variant="muted">
<ItemContent className="flex flex-row items-center justify-between">
<Skeleton className="w-1/2 h-4" />
<Skeleton className="w-1/4 h-8" />
</ItemContent>
</Item>
<Item variant="muted">
<ItemContent className="flex flex-row items-center justify-between">
<Skeleton className="w-1/2 h-4" />
<Skeleton className="w-1/4 h-8" />
</ItemContent>
</Item>
</div>
)}
{state.status === "error" && (
<Alert variant="destructive">
<AlertDescription>{errorMessage}</AlertDescription>
</Alert>
)}
{state.status === "done" && (
<div className="flex flex-col gap-2">
{state.collections.length === 0 && (
<p className="text-muted-foreground text-sm">{t("empty")}</p>
)}
{state.collections.map((collection) => {
const checked = selectedIds.has(collection.id);
const rowError = rowErrors[collection.id];
return (
<div key={collection.id} className="flex flex-col gap-2">
<Item variant="muted">
<ItemContent>
<ItemTitle>{collection.name}</ItemTitle>
</ItemContent>
<ItemActions>
<Button
variant={checked ? "outline" : "default"}
size="sm"
onClick={() => toggle(collection)}
>
{checked ? (
<>
<XIcon className="size-4" /> {t("removeAction")}
</>
) : (
<>
<PlusIcon className="size-4" /> {t("addAction")}
</>
)}
</Button>
</ItemActions>
</Item>
{rowError && <h5 className="text-muted-foreground">{rowError}</h5>}
</div>
);
})}
</div>
)}
<DialogFooter>
<Button variant="outline" onClick={() => setOpen(false)}>
{tc("close")}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,92 @@
"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() ? (
<span key={i} className="px-1 py-0.5 rounded-sm bg-accent text-accent-foreground">
{part}
</span>
) : (
<span key={i}>{part}</span>
),
)}
</>
);
}
interface CollocationsProps {
word: string;
lang: Language;
onResult?: (result: Fetched<CollocationsResult>) => 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<CollocationsResult>(
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 (
<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?.collocations.map((collocation, 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={collocation} word={word} /></p>
</div>
</div>
))}
</div>
)}
</div>
);
}
+46
View File
@@ -0,0 +1,46 @@
"use client";
import { useEffect, useState } from "react";
import { CheckIcon, CopyIcon } from "lucide-react";
import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
const COPIED_RESET_MS = 2000;
interface CopyButtonProps {
text: string;
}
export function CopyButton({ text }: CopyButtonProps) {
const [copied, setCopied] = useState(false);
const t = useTranslations("Common");
useEffect(() => {
if (!copied) return;
const timeoutId = setTimeout(() => setCopied(false), COPIED_RESET_MS);
return () => clearTimeout(timeoutId);
}, [copied]);
const handleCopy = async () => {
try {
await navigator.clipboard.writeText(text);
setCopied(true);
} catch (err) {
console.error("Copy failed:", err);
}
};
return (
<Button
variant="outline"
size="icon"
onClick={handleCopy}
disabled={!text}
aria-label={t(copied ? "copied" : "copy")}
title={t(copied ? "copied" : "copy")}
>
{copied ? <CheckIcon /> : <CopyIcon />}
</Button>
);
}
+92
View File
@@ -0,0 +1,92 @@
"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>
);
}
+63
View File
@@ -0,0 +1,63 @@
"use client";
import { KeyIcon, ListIcon, LogOutIcon } from "lucide-react";
import Logo from "./logo";
import { ThemeToggler } from "./themeToggler";
import Link from "next/link";
import { Button } from "./ui/button";
import { LocaleSwitcher } from "./localeSwitcher";
import { logout } from "@/app/actions/logout";
import { useTranslations } from "next-intl";
import type { User } from "@/types/api";
interface HeaderProps {
user: User | null;
}
export default function Header({ user }: HeaderProps) {
const t = useTranslations("Header");
const handleLogout = async () => {
await logout();
};
return (
<div className="flex flex-row items-center justify-between">
<Logo />
<div className="flex flex-row gap-2">
{user ? (
<>
<Button
nativeButton={false}
render={<Link href="/collections" />}
variant="outline"
size="icon"
aria-label={t("collections")}
>
<ListIcon />
</Button>
<Button
variant="outline"
size="icon"
onClick={handleLogout}
aria-label={t("logout")}
>
<LogOutIcon />
</Button>
</>
) : (
<Button
nativeButton={false}
render={<Link href="/oauth/login" />}
size="icon"
aria-label={t("login")}
>
<KeyIcon />
</Button>
)}
<ThemeToggler />
<LocaleSwitcher />
</div>
</div>
);
}
@@ -0,0 +1,9 @@
"use client";
import { useUser } from "@/providers/userProvider";
import Header from "./header";
export default function HeaderWithAuth() {
const user = useUser();
return <Header user={user} />;
}
+337
View File
@@ -0,0 +1,337 @@
"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>
);
}
@@ -0,0 +1,41 @@
import { Skeleton } from "@/components/ui/skeleton";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
export function HomeSkeleton() {
return (
<div className="flex flex-col gap-8 px-6 py-8">
<div className="flex flex-row items-center justify-between">
<Skeleton className="w-24 h-8" />
<div className="flex flex-row gap-2">
<Skeleton className="size-8 rounded-lg" />
<Skeleton className="size-8 rounded-lg" />
<Skeleton className="size-8 rounded-lg" />
</div>
</div>
<div className="flex flex-col md:flex-row gap-2 w-full items-stretch">
<Card className="w-full md:w-1/2">
<CardHeader>
<Skeleton className="w-24 h-6" />
</CardHeader>
<CardContent>
<Skeleton className="w-full h-32" />
</CardContent>
</Card>
<Skeleton className="self-center size-9 rounded-lg shrink-0" />
<Card className="w-full md:w-1/2">
<CardHeader>
<Skeleton className="w-24 h-6" />
</CardHeader>
<CardContent>
<Skeleton className="w-full h-32" />
</CardContent>
</Card>
</div>
<Card className="w-full">
<CardContent>
<Skeleton className="w-1/2 h-6" />
</CardContent>
</Card>
</div>
);
}
@@ -0,0 +1,58 @@
"use client";
import Image from "next/image";
import { LANGUAGES } from "@/lib/languages";
import type { UiLanguage } from "@/types/language";
import { useTranslations } from "next-intl";
import {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
interface LanguageSelectProps {
value: UiLanguage;
onChange: (lang: UiLanguage) => void;
excludeId?: UiLanguage["id"];
}
export function LanguageSelect({ value, onChange, excludeId }: LanguageSelectProps) {
const t = useTranslations("Languages");
const options = LANGUAGES.filter((l) => l.id !== excludeId);
return (
<Select
value={value.id}
onValueChange={(id) =>
onChange(options.find((l) => l.id === id) ?? options[0])
}
>
<SelectTrigger className="w-fit border-none shadow-none px-0 dark:bg-transparent dark:hover:bg-transparent">
<SelectValue>
<div className="flex flex-row gap-2.5 items-center">
<Image src={value.flag} alt={value.autonym} width={32} height={16} className="rounded-xs" />
<h3 className="font-medium">{t(value.id)}</h3>
</div>
</SelectValue>
</SelectTrigger>
<SelectContent>
<SelectGroup>
{options.map((l) => (
<SelectItem key={l.id} value={l.id}>
<div className="flex flex-row items-center gap-2.5">
<Image src={l.flag} alt={l.autonym} width={20} height={12} className="rounded-xs" />
<div className="flex flex-col gap-0">
<p className="font-medium">{t(l.id)}</p>
<h5>{l.autonym}</h5>
</div>
</div>
</SelectItem>
))}
</SelectGroup>
</SelectContent>
</Select>
);
}
@@ -0,0 +1,45 @@
"use client";
import { useRouter } from "next/navigation";
import { useLocale, useTranslations } from "next-intl";
import { LanguagesIcon } from "lucide-react";
import { setLocale } from "@/app/actions/setLocale";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { LANGUAGE_CODES } from "@/types/api";
export function LocaleSwitcher() {
const locale = useLocale();
const t = useTranslations("Locale");
const router = useRouter();
const handleChange = async (next: string) => {
if (next === locale) return;
await setLocale(next);
router.refresh();
};
return (
<DropdownMenu>
<DropdownMenuTrigger
render={
<Button variant="outline" size="icon" aria-label={t("switch")}>
<LanguagesIcon />
</Button>
}
/>
<DropdownMenuContent align="end">
{LANGUAGE_CODES.map((code) => (
<DropdownMenuItem key={code} onClick={() => handleChange(code)}>
{t(code)}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
);
}
+15
View File
@@ -0,0 +1,15 @@
import { Merriweather } from "next/font/google";
import Link from "next/link";
const merriweather = Merriweather({
weight: "700",
subsets: ["latin"]
});
export default function Logo() {
return (
<Link href="/">
<h1 className={merriweather.className}>Fancy</h1>
</Link>
);
}
+7
View File
@@ -0,0 +1,7 @@
export default function Main({ children }: { children: React.ReactNode }) {
return (
<div className="flex flex-col gap-8 px-6 py-8">
{children}
</div>
);
}
@@ -0,0 +1,252 @@
"use client";
import { useEffect, useState, type ReactNode } from "react";
import {
ArrowDownToLineIcon,
BookOpenIcon,
ClockIcon,
CpuIcon,
GaugeIcon,
InfoIcon,
LandmarkIcon,
LanguagesIcon,
SparklesIcon,
SquareArrowRightEnterIcon,
} from "lucide-react";
import { Dialog, DialogContent, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Progress, ProgressLabel } from "@/components/ui/progress";
import { Separator } from "@/components/ui/separator";
import { getUsage } from "@/lib/api";
import { cn, formatNumber, formatTimestamp } from "@/lib/utils";
import type {
CollocationsResult,
DictionaryResult,
ExamplesResult,
Fetched,
Source,
TranslationResult,
UsageResult,
} from "@/types/api";
import { useLocale, useTranslations } from "next-intl";
interface PropertyDialogProps {
response: Fetched<TranslationResult> | null;
definition?: Fetched<DictionaryResult> | null;
examples?: Fetched<ExamplesResult> | null;
collocations?: Fetched<CollocationsResult> | null;
}
function PropertyRow({ icon, label, value }: { icon: ReactNode; label: string; value?: string | null }) {
const tc = useTranslations("Common");
return (
<div className="flex flex-row items-center gap-4">
<div className="flex flex-row items-center gap-2 text-muted-foreground">
{icon}
<p>{label}</p>
</div>
<p className="font-medium">{value || tc("dash")}</p>
</div>
);
}
function PropertySection({ icon, title, children }: { icon: ReactNode; title: string; children: ReactNode }) {
return (
<div className="flex flex-col gap-2">
<div className="flex flex-row items-center gap-2">
{icon}<p className="font-medium">{title}</p>
</div>
<div className="flex flex-col gap-1">{children}</div>
</div>
);
}
function UsageBar({ label, used, limit }: { label: string; used: number; limit: number }) {
const locale = useLocale();
const percent = limit > 0 ? Math.min(100, (used / limit) * 100) : 0;
return (
<Progress
value={percent}
className={cn("gap-1", percent >= 90 && "**:data-[slot=progress-indicator]:bg-destructive")}
>
<ProgressLabel>{label}</ProgressLabel>
<h5 className="ml-auto text-muted-foreground tabular-nums">{formatNumber(used, locale)} / {formatNumber(limit, locale)}</h5>
</Progress>
);
}
function UsageSection() {
const t = useTranslations("Properties");
const [usage, setUsage] = useState<UsageResult | null>(null);
const [failed, setFailed] = useState(false);
useEffect(() => {
let cancelled = false;
getUsage()
.then((data) => {
if (!cancelled) setUsage(data);
})
.catch((err) => {
console.error("Usage lookup failed:", err);
if (!cancelled) setFailed(true);
});
return () => {
cancelled = true;
};
}, []);
return (
<div className="flex flex-col gap-4">
<div className="flex flex-row items-center gap-2">
<GaugeIcon size={18} /><p className="font-medium">{t("usage")}</p>
</div>
{failed && <p className="text-muted-foreground">{t("usageUnavailable")}</p>}
{!failed && !usage && (
<p className="text-muted-foreground shimmer">{t("loadingUsage")}</p>
)}
{usage && (
<div className="flex flex-col gap-4">
{usage.deepl ? (
<UsageBar
label={t("deeplCharacters")}
used={usage.deepl.character_count}
limit={usage.deepl.character_limit}
/>
) : (
<p className="text-muted-foreground">{t("deeplUnavailable")}</p>
)}
<div className="flex flex-col gap-1">
<UsageBar label={t("aiTokens")} used={usage.ai.tokens} limit={usage.ai.token_limit} />
<h6 className="text-muted-foreground">
{t("requestsThisMonth", { count: usage.ai.requests })}
</h6>
</div>
</div>
)}
</div>
);
}
export function PropertyDialog({ response, definition, examples, collocations }: PropertyDialogProps) {
const t = useTranslations("Properties");
const tc = useTranslations("Common");
const locale = useLocale();
const sourceValue = (source: Source) =>
source === "provider" ? tc("provider") : tc("cache");
return (
<Dialog>
<DialogTrigger
render={
<Button variant="outline" size="icon" aria-label={t("details")}>
<InfoIcon />
</Button>
}
/>
<DialogContent className="max-h-[85vh] overflow-y-auto">
<DialogTitle>{t("title")}</DialogTitle>
<div className="flex flex-col gap-4 text-sm">
{response && (
<PropertySection icon={<LanguagesIcon size={18} />} title={t("translate")}>
<PropertyRow
icon={<SquareArrowRightEnterIcon size={18} />}
label={tc("source")}
value={sourceValue(response.source)}
/>
<PropertyRow icon={<LandmarkIcon size={18} />} label={tc("provider")} value={response.provider} />
{response.model && (
<PropertyRow icon={<CpuIcon size={18} />} label={tc("model")} value={response.model} />
)}
<PropertyRow
icon={<ClockIcon size={18} />}
label={tc("generated")}
value={formatTimestamp(response.generated_at, locale)}
/>
<PropertyRow
icon={<ArrowDownToLineIcon size={18} />}
label={tc("fetched")}
value={formatTimestamp(response.fetched_at, locale)}
/>
</PropertySection>
)}
{definition && (
<PropertySection icon={<BookOpenIcon size={18} />} title={t("definition")}>
<PropertyRow
icon={<SquareArrowRightEnterIcon size={18} />}
label={tc("source")}
value={sourceValue(definition.source)}
/>
<PropertyRow icon={<LandmarkIcon size={18} />} label={tc("provider")} value={definition.provider} />
{definition.model && (
<PropertyRow icon={<CpuIcon size={18} />} label={tc("model")} value={definition.model} />
)}
<PropertyRow
icon={<ClockIcon size={18} />}
label={tc("generated")}
value={formatTimestamp(definition.generated_at, locale)}
/>
<PropertyRow
icon={<ArrowDownToLineIcon size={18} />}
label={tc("fetched")}
value={formatTimestamp(definition.fetched_at, locale)}
/>
</PropertySection>
)}
{examples && (
<PropertySection icon={<SparklesIcon size={18} />} title={t("examples")}>
<PropertyRow
icon={<SquareArrowRightEnterIcon size={18} />}
label={tc("source")}
value={sourceValue(examples.source)}
/>
<PropertyRow icon={<LandmarkIcon size={18} />} label={tc("provider")} value={examples.provider} />
{examples.model && (
<PropertyRow icon={<CpuIcon size={18} />} label={tc("model")} value={examples.model} />
)}
<PropertyRow
icon={<ClockIcon size={18} />}
label={tc("generated")}
value={formatTimestamp(examples.generated_at, locale)}
/>
<PropertyRow
icon={<ArrowDownToLineIcon size={18} />}
label={tc("fetched")}
value={formatTimestamp(examples.fetched_at, locale)}
/>
</PropertySection>
)}
{collocations && (
<PropertySection icon={<SparklesIcon size={18} />} title={t("collocations")}>
<PropertyRow
icon={<SquareArrowRightEnterIcon size={18} />}
label={tc("source")}
value={sourceValue(collocations.source)}
/>
<PropertyRow icon={<LandmarkIcon size={18} />} label={tc("provider")} value={collocations.provider} />
{collocations.model && (
<PropertyRow icon={<CpuIcon size={18} />} label={tc("model")} value={collocations.model} />
)}
<PropertyRow
icon={<ClockIcon size={18} />}
label={tc("generated")}
value={formatTimestamp(collocations.generated_at, locale)}
/>
<PropertyRow
icon={<ArrowDownToLineIcon size={18} />}
label={tc("fetched")}
value={formatTimestamp(collocations.fetched_at, locale)}
/>
</PropertySection>
)}
<Separator />
<UsageSection />
</div>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,11 @@
"use client"
import * as React from "react"
import { ThemeProvider as NextThemesProvider } from "next-themes"
export function ThemeProvider({
children,
...props
}: React.ComponentProps<typeof NextThemesProvider>) {
return <NextThemesProvider {...props}>{children}</NextThemesProvider>
}
@@ -0,0 +1,42 @@
"use client"
import { MoonIcon, SunIcon } from "lucide-react";
import { useTheme } from "next-themes";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { useTranslations } from "next-intl";
export function ThemeToggler() {
const { setTheme } = useTheme();
const t = useTranslations("Theme");
return (
<DropdownMenu>
<DropdownMenuTrigger
render={
<Button variant="outline" size="icon" className="relative" aria-label={t("toggle")}>
<SunIcon className="h-[1.2rem] w-[1.2rem] scale-100 rotate-0 transition-all dark:scale-0 dark:-rotate-90" />
<MoonIcon className="absolute h-[1.2rem] w-[1.2rem] scale-0 rotate-90 transition-all dark:scale-100 dark:rotate-0" />
<span className="sr-only">{t("toggle")}</span>
</Button>
}
/>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => setTheme("light")}>
{t("light")}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme("dark")}>
{t("dark")}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme("system")}>
{t("system")}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)
}
@@ -0,0 +1,26 @@
import { memo, useMemo } from "react";
import { ClickableWord } from "@/components/clickableWord";
const TOKEN_PATTERN = /[\p{L}\p{M}\p{N}]+(?:['’-][\p{L}\p{M}\p{N}]+)*|[^\p{L}\p{M}\p{N}\s]|\s+/gu;
const WORD_PATTERN = /^[\p{L}\p{M}\p{N}]+(?:['’-][\p{L}\p{M}\p{N}]+)*$/u;
interface TokenizedTextProps {
text: string;
onSelect?: (word: string) => void;
}
export const TokenizedText = memo(function TokenizedText({ text, onSelect }: TokenizedTextProps) {
const tokens = useMemo(() => text.match(TOKEN_PATTERN) ?? [], [text]);
return (
<>
{tokens.map((token, i) =>
WORD_PATTERN.test(token) ? (
<ClickableWord key={i} word={token} onSelect={onSelect} />
) : (
<span key={i}>{token}</span>
)
)}
</>
);
});
@@ -0,0 +1,116 @@
"use client";
import type { ReactNode } from "react";
import { TriangleAlertIcon } from "lucide-react";
import { CopyButton } from "@/components/copyButton";
import { LanguageSelect } from "@/components/languageSelect";
import { TokenizedText } from "@/components/tokenizedText";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { Marker, MarkerContent, MarkerIcon } from "@/components/ui/marker";
import { Separator } from "@/components/ui/separator";
import { Textarea } from "@/components/ui/textarea";
import type { ApiError } from "@/lib/api";
import { cn } from "@/lib/utils";
import { useApiErrorMessage } from "@/lib/useApiErrorMessage";
import type { Language } from "@/types/api";
import type { UiLanguage } from "@/types/language";
import { useTranslations } from "next-intl";
interface TranslationCardProps {
variant: "source" | "target";
lang: UiLanguage;
onLangChange: (lang: UiLanguage) => void;
excludeLangId?: Language;
placeholder: string;
text: string;
onTextChange?: (text: string) => void;
isLoading?: boolean;
error?: ApiError | null;
onSelectWord: (word: string) => void;
footerExtra?: ReactNode;
}
export function TranslationCard({
variant,
lang,
onLangChange,
excludeLangId,
placeholder,
text,
onTextChange,
isLoading,
error,
onSelectWord,
footerExtra,
}: TranslationCardProps) {
const isSource = variant === "source";
const t = useTranslations("Home");
const apiErrorMessage = useApiErrorMessage(error?.kind);
return (
<Card className="w-full md:w-1/2 flex flex-col">
<CardHeader>
<LanguageSelect value={lang} onChange={onLangChange} excludeId={excludeLangId} />
</CardHeader>
<CardContent className="flex flex-col flex-1 justify-between gap-4">
{isSource ? (
<Textarea
placeholder={placeholder}
value={text}
onChange={(e) => onTextChange?.(e.target.value)}
className={cn(
"text-xl! resize-none flex-1 min-h-32",
"border-none p-0",
"dark:bg-transparent focus-visible:ring-0 focus-visible:ring-offset-0"
)}
/>
) : (
<h2
aria-busy={isLoading}
aria-live="polite"
className={cn(
"flex-1 min-h-32",
!text && "text-muted-foreground",
isLoading && "animate-pulse"
)}
>
{text ? (
<TokenizedText text={text} onSelect={onSelectWord} />
) : (
placeholder
)}
</h2>
)}
{!isSource && error && (
<Marker>
<MarkerIcon>
<TriangleAlertIcon />
</MarkerIcon>
<MarkerContent>{apiErrorMessage}</MarkerContent>
</Marker>
)}
{isSource && text.trim().split(/\s+/).length > 1 && (
<div className="flex flex-col gap-4">
<Separator />
<div className="flex flex-col gap-2">
<p>
<TokenizedText text={text} onSelect={onSelectWord} />
</p>
<h6 className="text-muted-foreground">{t("clickWordHint")}</h6>
</div>
</div>
)}
<div className="flex flex-row items-center justify-between">
<div className="flex flex-row items-center gap-2">
{text && <CopyButton text={text} />}
</div>
{footerExtra}
</div>
</CardContent>
</Card>
);
}
+76
View File
@@ -0,0 +1,76 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const alertVariants = cva(
"group/alert relative grid w-full gap-0.5 rounded-lg border px-2.5 py-2 text-left text-sm has-data-[slot=alert-action]:relative has-data-[slot=alert-action]:pr-18 has-[>svg]:grid-cols-[auto_1fr] has-[>svg]:gap-x-2 *:[svg]:row-span-2 *:[svg]:translate-y-0.5 *:[svg]:text-current *:[svg:not([class*='size-'])]:size-4",
{
variants: {
variant: {
default: "bg-card text-card-foreground",
destructive:
"bg-card text-destructive *:data-[slot=alert-description]:text-destructive/90 *:[svg]:text-current",
},
},
defaultVariants: {
variant: "default",
},
}
)
function Alert({
className,
variant,
...props
}: React.ComponentProps<"div"> & VariantProps<typeof alertVariants>) {
return (
<div
data-slot="alert"
role="alert"
className={cn(alertVariants({ variant }), className)}
{...props}
/>
)
}
function AlertTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-title"
className={cn(
"font-medium group-has-[>svg]/alert:col-start-2 [&_a]:underline [&_a]:underline-offset-3 [&_a]:hover:text-foreground",
className
)}
{...props}
/>
)
}
function AlertDescription({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-description"
className={cn(
"text-sm text-balance text-muted-foreground md:text-pretty [&_a]:underline [&_a]:underline-offset-3 [&_a]:hover:text-foreground [&_p:not(:last-child)]:mb-4",
className
)}
{...props}
/>
)
}
function AlertAction({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-action"
className={cn("absolute top-2 right-2", className)}
{...props}
/>
)
}
export { Alert, AlertTitle, AlertDescription, AlertAction }
+52
View File
@@ -0,0 +1,52 @@
import { mergeProps } from "@base-ui/react/merge-props"
import { useRender } from "@base-ui/react/use-render"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const badgeVariants = cva(
"group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-4xl border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground [a]:hover:bg-primary/80",
secondary:
"bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80",
destructive:
"bg-destructive/10 text-destructive focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:focus-visible:ring-destructive/40 [a]:hover:bg-destructive/20",
outline:
"border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground",
ghost:
"hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50",
link: "text-primary underline-offset-4 hover:underline",
},
},
defaultVariants: {
variant: "default",
},
}
)
function Badge({
className,
variant = "default",
render,
...props
}: useRender.ComponentProps<"span"> & VariantProps<typeof badgeVariants>) {
return useRender({
defaultTagName: "span",
props: mergeProps<"span">(
{
className: cn(badgeVariants({ variant }), className),
},
props
),
render,
state: {
slot: "badge",
variant,
},
})
}
export { Badge, badgeVariants }
+58
View File
@@ -0,0 +1,58 @@
import { Button as ButtonPrimitive } from "@base-ui/react/button"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/80",
outline:
"border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
secondary:
"bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground",
ghost:
"hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50",
destructive:
"bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default:
"h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
xs: "h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",
sm: "h-7 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",
lg: "h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
icon: "size-8",
"icon-xs":
"size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3",
"icon-sm":
"size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3.5",
"icon-lg": "size-9",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function Button({
className,
variant = "default",
size = "default",
...props
}: ButtonPrimitive.Props & VariantProps<typeof buttonVariants>) {
return (
<ButtonPrimitive
data-slot="button"
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
)
}
export { Button, buttonVariants }
+103
View File
@@ -0,0 +1,103 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Card({
className,
size = "default",
...props
}: React.ComponentProps<"div"> & { size?: "default" | "sm" }) {
return (
<div
data-slot="card"
data-size={size}
className={cn(
"group/card flex flex-col gap-(--card-spacing) overflow-hidden rounded-xl bg-card py-(--card-spacing) text-sm text-card-foreground ring-1 ring-foreground/10 [--card-spacing:--spacing(4)] has-data-[slot=card-footer]:pb-0 has-[>img:first-child]:pt-0 data-[size=sm]:[--card-spacing:--spacing(3)] data-[size=sm]:has-data-[slot=card-footer]:pb-0 *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl",
className
)}
{...props}
/>
)
}
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-header"
className={cn(
"group/card-header @container/card-header grid auto-rows-min items-start gap-1 rounded-t-xl px-(--card-spacing) has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto] [.border-b]:pb-(--card-spacing)",
className
)}
{...props}
/>
)
}
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-title"
className={cn(
"font-heading text-base leading-snug font-medium group-data-[size=sm]/card:text-sm",
className
)}
{...props}
/>
)
}
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-description"
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
)
}
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-action"
className={cn(
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
className
)}
{...props}
/>
)
}
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-content"
className={cn("px-(--card-spacing)", className)}
{...props}
/>
)
}
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-footer"
className={cn(
"flex items-center rounded-b-xl border-t bg-muted/50 p-(--card-spacing)",
className
)}
{...props}
/>
)
}
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardAction,
CardDescription,
CardContent,
}
+165
View File
@@ -0,0 +1,165 @@
"use client"
import * as React from "react"
import { Dialog as DialogPrimitive } from "@base-ui/react/dialog"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { XIcon } from "lucide-react"
import { useTranslations } from "next-intl"
function Dialog({ ...props }: DialogPrimitive.Root.Props) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
}
function DialogTrigger({ ...props }: DialogPrimitive.Trigger.Props) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
}
function DialogPortal({ ...props }: DialogPrimitive.Portal.Props) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
}
function DialogClose({ ...props }: DialogPrimitive.Close.Props) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
}
function DialogOverlay({
className,
...props
}: DialogPrimitive.Backdrop.Props) {
return (
<DialogPrimitive.Backdrop
data-slot="dialog-overlay"
className={cn(
"fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
className
)}
{...props}
/>
)
}
function DialogContent({
className,
children,
showCloseButton = true,
...props
}: DialogPrimitive.Popup.Props & {
showCloseButton?: boolean
}) {
const t = useTranslations("Common")
return (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Popup
data-slot="dialog-content"
className={cn(
"fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
className
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close
data-slot="dialog-close"
render={
<Button
variant="ghost"
className="absolute top-2 right-2"
size="icon-sm"
/>
}
>
<XIcon
/>
<span className="sr-only">{t("close")}</span>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Popup>
</DialogPortal>
)
}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-header"
className={cn("flex flex-col gap-2", className)}
{...props}
/>
)
}
function DialogFooter({
className,
showCloseButton = false,
children,
...props
}: React.ComponentProps<"div"> & {
showCloseButton?: boolean
}) {
const t = useTranslations("Common")
return (
<div
data-slot="dialog-footer"
className={cn(
"-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end",
className
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close render={<Button variant="outline" />}>
{t("close")}
</DialogPrimitive.Close>
)}
</div>
)
}
function DialogTitle({ className, ...props }: DialogPrimitive.Title.Props) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn(
"font-heading text-base leading-none font-medium",
className
)}
{...props}
/>
)
}
function DialogDescription({
className,
...props
}: DialogPrimitive.Description.Props) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn(
"text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",
className
)}
{...props}
/>
)
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
}
@@ -0,0 +1,268 @@
"use client"
import * as React from "react"
import { Menu as MenuPrimitive } from "@base-ui/react/menu"
import { cn } from "@/lib/utils"
import { ChevronRightIcon, CheckIcon } from "lucide-react"
function DropdownMenu({ ...props }: MenuPrimitive.Root.Props) {
return <MenuPrimitive.Root data-slot="dropdown-menu" {...props} />
}
function DropdownMenuPortal({ ...props }: MenuPrimitive.Portal.Props) {
return <MenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
}
function DropdownMenuTrigger({ ...props }: MenuPrimitive.Trigger.Props) {
return <MenuPrimitive.Trigger data-slot="dropdown-menu-trigger" {...props} />
}
function DropdownMenuContent({
align = "start",
alignOffset = 0,
side = "bottom",
sideOffset = 4,
className,
...props
}: MenuPrimitive.Popup.Props &
Pick<
MenuPrimitive.Positioner.Props,
"align" | "alignOffset" | "side" | "sideOffset"
>) {
return (
<MenuPrimitive.Portal>
<MenuPrimitive.Positioner
className="isolate z-50 outline-none"
align={align}
alignOffset={alignOffset}
side={side}
sideOffset={sideOffset}
>
<MenuPrimitive.Popup
data-slot="dropdown-menu-content"
className={cn("z-50 max-h-(--available-height) w-(--anchor-width) min-w-32 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 outline-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:overflow-hidden data-closed:fade-out-0 data-closed:zoom-out-95", className )}
{...props}
/>
</MenuPrimitive.Positioner>
</MenuPrimitive.Portal>
)
}
function DropdownMenuGroup({ ...props }: MenuPrimitive.Group.Props) {
return <MenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
}
function DropdownMenuLabel({
className,
inset,
...props
}: MenuPrimitive.GroupLabel.Props & {
inset?: boolean
}) {
return (
<MenuPrimitive.GroupLabel
data-slot="dropdown-menu-label"
data-inset={inset}
className={cn(
"px-1.5 py-1 text-xs font-medium text-muted-foreground data-inset:pl-7",
className
)}
{...props}
/>
)
}
function DropdownMenuItem({
className,
inset,
variant = "default",
...props
}: MenuPrimitive.Item.Props & {
inset?: boolean
variant?: "default" | "destructive"
}) {
return (
<MenuPrimitive.Item
data-slot="dropdown-menu-item"
data-inset={inset}
data-variant={variant}
className={cn(
"group/dropdown-menu-item relative flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-[variant=destructive]:*:[svg]:text-destructive",
className
)}
{...props}
/>
)
}
function DropdownMenuSub({ ...props }: MenuPrimitive.SubmenuRoot.Props) {
return <MenuPrimitive.SubmenuRoot data-slot="dropdown-menu-sub" {...props} />
}
function DropdownMenuSubTrigger({
className,
inset,
children,
...props
}: MenuPrimitive.SubmenuTrigger.Props & {
inset?: boolean
}) {
return (
<MenuPrimitive.SubmenuTrigger
data-slot="dropdown-menu-sub-trigger"
data-inset={inset}
className={cn(
"flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-popup-open:bg-accent data-popup-open:text-accent-foreground data-open:bg-accent data-open:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto" />
</MenuPrimitive.SubmenuTrigger>
)
}
function DropdownMenuSubContent({
align = "start",
alignOffset = -3,
side = "right",
sideOffset = 0,
className,
...props
}: React.ComponentProps<typeof DropdownMenuContent>) {
return (
<DropdownMenuContent
data-slot="dropdown-menu-sub-content"
className={cn("w-auto min-w-[96px] rounded-lg bg-popover p-1 text-popover-foreground shadow-lg ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className )}
align={align}
alignOffset={alignOffset}
side={side}
sideOffset={sideOffset}
{...props}
/>
)
}
function DropdownMenuCheckboxItem({
className,
children,
checked,
inset,
...props
}: MenuPrimitive.CheckboxItem.Props & {
inset?: boolean
}) {
return (
<MenuPrimitive.CheckboxItem
data-slot="dropdown-menu-checkbox-item"
data-inset={inset}
className={cn(
"relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
checked={checked}
{...props}
>
<span
className="pointer-events-none absolute right-2 flex items-center justify-center"
data-slot="dropdown-menu-checkbox-item-indicator"
>
<MenuPrimitive.CheckboxItemIndicator>
<CheckIcon
/>
</MenuPrimitive.CheckboxItemIndicator>
</span>
{children}
</MenuPrimitive.CheckboxItem>
)
}
function DropdownMenuRadioGroup({ ...props }: MenuPrimitive.RadioGroup.Props) {
return (
<MenuPrimitive.RadioGroup
data-slot="dropdown-menu-radio-group"
{...props}
/>
)
}
function DropdownMenuRadioItem({
className,
children,
inset,
...props
}: MenuPrimitive.RadioItem.Props & {
inset?: boolean
}) {
return (
<MenuPrimitive.RadioItem
data-slot="dropdown-menu-radio-item"
data-inset={inset}
className={cn(
"relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
<span
className="pointer-events-none absolute right-2 flex items-center justify-center"
data-slot="dropdown-menu-radio-item-indicator"
>
<MenuPrimitive.RadioItemIndicator>
<CheckIcon
/>
</MenuPrimitive.RadioItemIndicator>
</span>
{children}
</MenuPrimitive.RadioItem>
)
}
function DropdownMenuSeparator({
className,
...props
}: MenuPrimitive.Separator.Props) {
return (
<MenuPrimitive.Separator
data-slot="dropdown-menu-separator"
className={cn("-mx-1 my-1 h-px bg-border", className)}
{...props}
/>
)
}
function DropdownMenuShortcut({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="dropdown-menu-shortcut"
className={cn(
"ml-auto text-xs tracking-widest text-muted-foreground group-focus/dropdown-menu-item:text-accent-foreground",
className
)}
{...props}
/>
)
}
export {
DropdownMenu,
DropdownMenuPortal,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuLabel,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuSub,
DropdownMenuSubTrigger,
DropdownMenuSubContent,
}
+238
View File
@@ -0,0 +1,238 @@
"use client"
import { useMemo } from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { Label } from "@/components/ui/label"
import { Separator } from "@/components/ui/separator"
function FieldSet({ className, ...props }: React.ComponentProps<"fieldset">) {
return (
<fieldset
data-slot="field-set"
className={cn(
"flex flex-col gap-4 has-[>[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3",
className
)}
{...props}
/>
)
}
function FieldLegend({
className,
variant = "legend",
...props
}: React.ComponentProps<"legend"> & { variant?: "legend" | "label" }) {
return (
<legend
data-slot="field-legend"
data-variant={variant}
className={cn(
"mb-1.5 font-medium data-[variant=label]:text-sm data-[variant=legend]:text-base",
className
)}
{...props}
/>
)
}
function FieldGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="field-group"
className={cn(
"group/field-group @container/field-group flex w-full flex-col gap-5 data-[slot=checkbox-group]:gap-3 *:data-[slot=field-group]:gap-4",
className
)}
{...props}
/>
)
}
const fieldVariants = cva(
"group/field flex w-full gap-2 data-[invalid=true]:text-destructive",
{
variants: {
orientation: {
vertical: "flex-col *:w-full [&>.sr-only]:w-auto",
horizontal:
"flex-row items-center has-[>[data-slot=field-content]]:items-start *:data-[slot=field-label]:flex-auto has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
responsive:
"flex-col *:w-full @md/field-group:flex-row @md/field-group:items-center @md/field-group:*:w-auto @md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:*:data-[slot=field-label]:flex-auto [&>.sr-only]:w-auto @md/field-group:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
},
},
defaultVariants: {
orientation: "vertical",
},
}
)
function Field({
className,
orientation = "vertical",
...props
}: React.ComponentProps<"div"> & VariantProps<typeof fieldVariants>) {
return (
<div
role="group"
data-slot="field"
data-orientation={orientation}
className={cn(fieldVariants({ orientation }), className)}
{...props}
/>
)
}
function FieldContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="field-content"
className={cn(
"group/field-content flex flex-1 flex-col gap-0.5 leading-snug",
className
)}
{...props}
/>
)
}
function FieldLabel({
className,
...props
}: React.ComponentProps<typeof Label>) {
return (
<Label
data-slot="field-label"
className={cn(
"group/field-label peer/field-label flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50 has-data-checked:border-primary/30 has-data-checked:bg-primary/5 has-[>[data-slot=field]]:rounded-lg has-[>[data-slot=field]]:border has-[>[data-slot=field]]:not-has-[:disabled,[data-disabled]]:hover:bg-muted/50 has-[>[data-slot=field]]:has-[:focus-visible]:border-ring has-[>[data-slot=field]]:has-[:focus-visible]:ring-3 has-[>[data-slot=field]]:has-[:focus-visible]:ring-ring/50 *:data-[slot=field]:p-2.5 dark:has-data-checked:border-primary/20 dark:has-data-checked:bg-primary/10",
"has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col",
className
)}
{...props}
/>
)
}
function FieldTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="field-label"
className={cn(
"flex w-fit items-center gap-2 text-sm font-medium group-data-[disabled=true]/field:opacity-50",
className
)}
{...props}
/>
)
}
function FieldDescription({ className, ...props }: React.ComponentProps<"p">) {
return (
<p
data-slot="field-description"
className={cn(
"text-left text-sm leading-normal font-normal text-muted-foreground group-has-data-horizontal/field:text-balance [[data-variant=legend]+&]:-mt-1.5",
"last:mt-0 nth-last-2:-mt-1",
"[&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary",
className
)}
{...props}
/>
)
}
function FieldSeparator({
children,
className,
...props
}: React.ComponentProps<"div"> & {
children?: React.ReactNode
}) {
return (
<div
data-slot="field-separator"
data-content={!!children}
className={cn(
"relative -my-2 h-5 text-sm group-data-[variant=outline]/field-group:-mb-2",
className
)}
{...props}
>
<Separator className="absolute inset-0 top-1/2" />
{children && (
<span
className="relative mx-auto block w-fit bg-background px-2 text-muted-foreground"
data-slot="field-separator-content"
>
{children}
</span>
)}
</div>
)
}
function FieldError({
className,
children,
errors,
...props
}: React.ComponentProps<"div"> & {
errors?: Array<{ message?: string } | undefined>
}) {
const content = useMemo(() => {
if (children) {
return children
}
if (!errors?.length) {
return null
}
const uniqueErrors = [
...new Map(errors.map((error) => [error?.message, error])).values(),
]
if (uniqueErrors?.length === 1) {
return uniqueErrors[0]?.message
}
return (
<ul className="ml-4 flex list-disc flex-col gap-1">
{uniqueErrors.map(
(error, index) =>
error?.message && <li key={index}>{error.message}</li>
)}
</ul>
)
}, [children, errors])
if (!content) {
return null
}
return (
<div
role="alert"
data-slot="field-error"
className={cn("text-sm font-normal text-destructive", className)}
{...props}
>
{content}
</div>
)
}
export {
Field,
FieldLabel,
FieldDescription,
FieldError,
FieldGroup,
FieldLegend,
FieldSeparator,
FieldSet,
FieldContent,
FieldTitle,
}
@@ -0,0 +1,158 @@
"use client"
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
function InputGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="input-group"
role="group"
className={cn(
"group/input-group relative flex h-8 w-full min-w-0 items-center rounded-lg border border-input transition-colors outline-none in-data-[slot=combobox-content]:focus-within:border-inherit in-data-[slot=combobox-content]:focus-within:ring-0 has-disabled:bg-input/50 has-disabled:opacity-50 has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot=input-group-control]:focus-visible]:ring-3 has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50 has-[[data-slot][aria-invalid=true]]:border-destructive has-[[data-slot][aria-invalid=true]]:ring-3 has-[[data-slot][aria-invalid=true]]:ring-destructive/20 has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>textarea]:h-auto dark:bg-input/30 dark:has-disabled:bg-input/80 dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40 has-[>[data-align=block-end]]:[&>input]:pt-3 has-[>[data-align=block-start]]:[&>input]:pb-3 has-[>[data-align=inline-end]]:[&>input]:pr-1.5 has-[>[data-align=inline-start]]:[&>input]:pl-1.5",
className
)}
{...props}
/>
)
}
const inputGroupAddonVariants = cva(
"flex h-auto cursor-text items-center justify-center gap-2 py-1.5 text-sm font-medium text-muted-foreground select-none group-data-[disabled=true]/input-group:opacity-50 [&>kbd]:rounded-[calc(var(--radius)-5px)] [&>svg:not([class*='size-'])]:size-4",
{
variants: {
align: {
"inline-start":
"order-first pl-2 has-[>button]:ml-[-0.3rem] has-[>kbd]:ml-[-0.15rem]",
"inline-end":
"order-last pr-2 has-[>button]:mr-[-0.3rem] has-[>kbd]:mr-[-0.15rem]",
"block-start":
"order-first w-full justify-start px-2.5 pt-2 group-has-[>input]/input-group:pt-2 [.border-b]:pb-2",
"block-end":
"order-last w-full justify-start px-2.5 pb-2 group-has-[>input]/input-group:pb-2 [.border-t]:pt-2",
},
},
defaultVariants: {
align: "inline-start",
},
}
)
function InputGroupAddon({
className,
align = "inline-start",
...props
}: React.ComponentProps<"div"> & VariantProps<typeof inputGroupAddonVariants>) {
return (
<div
role="group"
data-slot="input-group-addon"
data-align={align}
className={cn(inputGroupAddonVariants({ align }), className)}
onClick={(e) => {
if ((e.target as HTMLElement).closest("button")) {
return
}
e.currentTarget.parentElement?.querySelector("input")?.focus()
}}
{...props}
/>
)
}
const inputGroupButtonVariants = cva(
"flex items-center gap-2 text-sm shadow-none",
{
variants: {
size: {
xs: "h-6 gap-1 rounded-[calc(var(--radius)-3px)] px-1.5 [&>svg:not([class*='size-'])]:size-3.5",
sm: "",
"icon-xs":
"size-6 rounded-[calc(var(--radius)-3px)] p-0 has-[>svg]:p-0",
"icon-sm": "size-8 p-0 has-[>svg]:p-0",
},
},
defaultVariants: {
size: "xs",
},
}
)
function InputGroupButton({
className,
type = "button",
variant = "ghost",
size = "xs",
...props
}: Omit<React.ComponentProps<typeof Button>, "size" | "type"> &
VariantProps<typeof inputGroupButtonVariants> & {
type?: "button" | "submit" | "reset"
}) {
return (
<Button
type={type}
data-size={size}
variant={variant}
className={cn(inputGroupButtonVariants({ size }), className)}
{...props}
/>
)
}
function InputGroupText({ className, ...props }: React.ComponentProps<"span">) {
return (
<span
className={cn(
"flex items-center gap-2 text-sm text-muted-foreground [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
/>
)
}
function InputGroupInput({
className,
...props
}: React.ComponentProps<"input">) {
return (
<Input
data-slot="input-group-control"
className={cn(
"flex-1 rounded-none border-0 bg-transparent shadow-none ring-0 focus-visible:ring-0 disabled:bg-transparent aria-invalid:ring-0 dark:bg-transparent dark:disabled:bg-transparent",
className
)}
{...props}
/>
)
}
function InputGroupTextarea({
className,
...props
}: React.ComponentProps<"textarea">) {
return (
<Textarea
data-slot="input-group-control"
className={cn(
"flex-1 resize-none rounded-none border-0 bg-transparent py-2 shadow-none ring-0 focus-visible:ring-0 disabled:bg-transparent aria-invalid:ring-0 dark:bg-transparent dark:disabled:bg-transparent",
className
)}
{...props}
/>
)
}
export {
InputGroup,
InputGroupAddon,
InputGroupButton,
InputGroupText,
InputGroupInput,
InputGroupTextarea,
}
+20
View File
@@ -0,0 +1,20 @@
import * as React from "react"
import { Input as InputPrimitive } from "@base-ui/react/input"
import { cn } from "@/lib/utils"
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
<InputPrimitive
type={type}
data-slot="input"
className={cn(
"h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",
className
)}
{...props}
/>
)
}
export { Input }
+201
View File
@@ -0,0 +1,201 @@
import * as React from "react"
import { mergeProps } from "@base-ui/react/merge-props"
import { useRender } from "@base-ui/react/use-render"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "cn"
import { Separator } from "@/components/ui/separator"
function ItemGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
role="list"
data-slot="item-group"
className={cn(
"group/item-group flex w-full flex-col gap-4 has-data-[size=sm]:gap-2.5 has-data-[size=xs]:gap-2",
className
)}
{...props}
/>
)
}
function ItemSeparator({
className,
...props
}: React.ComponentProps<typeof Separator>) {
return (
<Separator
data-slot="item-separator"
orientation="horizontal"
className={cn("my-2", className)}
{...props}
/>
)
}
const itemVariants = cva(
"group/item flex w-full flex-wrap items-center rounded-lg border text-sm transition-colors duration-100 outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 [a]:transition-colors [a]:hover:bg-muted",
{
variants: {
variant: {
default: "border-transparent",
outline: "border-border",
muted: "border-transparent bg-muted/50",
},
size: {
default: "gap-2.5 px-3 py-2.5",
sm: "gap-2.5 px-3 py-2.5",
xs: "gap-2 px-2.5 py-2 in-data-[slot=dropdown-menu-content]:p-0",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function Item({
className,
variant = "default",
size = "default",
render,
...props
}: useRender.ComponentProps<"div"> & VariantProps<typeof itemVariants>) {
return useRender({
defaultTagName: "div",
props: mergeProps<"div">(
{
className: cn(itemVariants({ variant, size, className })),
},
props
),
render,
state: {
slot: "item",
variant,
size,
},
})
}
const itemMediaVariants = cva(
"flex shrink-0 items-center justify-center gap-2 group-has-data-[slot=item-description]/item:translate-y-0.5 group-has-data-[slot=item-description]/item:self-start [&_svg]:pointer-events-none",
{
variants: {
variant: {
default: "bg-transparent",
icon: "[&_svg:not([class*='size-'])]:size-4",
image:
"size-10 overflow-hidden rounded-sm group-data-[size=sm]/item:size-8 group-data-[size=xs]/item:size-6 [&_img]:size-full [&_img]:object-cover",
},
},
defaultVariants: {
variant: "default",
},
}
)
function ItemMedia({
className,
variant = "default",
...props
}: React.ComponentProps<"div"> & VariantProps<typeof itemMediaVariants>) {
return (
<div
data-slot="item-media"
data-variant={variant}
className={cn(itemMediaVariants({ variant, className }))}
{...props}
/>
)
}
function ItemContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="item-content"
className={cn(
"flex flex-1 flex-col gap-1 group-data-[size=xs]/item:gap-0 [&+[data-slot=item-content]]:flex-none",
className
)}
{...props}
/>
)
}
function ItemTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="item-title"
className={cn(
"line-clamp-1 flex w-fit items-center gap-2 text-sm leading-snug font-medium underline-offset-4",
className
)}
{...props}
/>
)
}
function ItemDescription({ className, ...props }: React.ComponentProps<"p">) {
return (
<p
data-slot="item-description"
className={cn(
"line-clamp-2 text-left text-sm leading-normal font-normal text-muted-foreground group-data-[size=xs]/item:text-xs [&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary",
className
)}
{...props}
/>
)
}
function ItemActions({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="item-actions"
className={cn("flex items-center gap-2", className)}
{...props}
/>
)
}
function ItemHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="item-header"
className={cn(
"flex basis-full items-center justify-between gap-2",
className
)}
{...props}
/>
)
}
function ItemFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="item-footer"
className={cn(
"flex basis-full items-center justify-between gap-2",
className
)}
{...props}
/>
)
}
export {
Item,
ItemMedia,
ItemContent,
ItemActions,
ItemGroup,
ItemSeparator,
ItemTitle,
ItemDescription,
ItemHeader,
ItemFooter,
}
+20
View File
@@ -0,0 +1,20 @@
"use client"
import * as React from "react"
import { cn } from "@/lib/utils"
function Label({ className, ...props }: React.ComponentProps<"label">) {
return (
<label
data-slot="label"
className={cn(
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
className
)}
{...props}
/>
)
}
export { Label }
+71
View File
@@ -0,0 +1,71 @@
import * as React from "react"
import { mergeProps } from "@base-ui/react/merge-props"
import { useRender } from "@base-ui/react/use-render"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const markerVariants = cva(
"group/marker relative flex min-h-4 w-full items-center gap-2 text-left text-sm text-muted-foreground [&_svg:not([class*='size-'])]:size-4 [a]:underline [a]:underline-offset-3 [a]:hover:text-foreground",
{
variants: {
variant: {
default: "",
separator:
"before:mr-1 before:h-px before:min-w-0 before:flex-1 before:bg-border after:ml-1 after:h-px after:min-w-0 after:flex-1 after:bg-border",
border: "border-b border-border pb-2",
},
},
}
)
function Marker({
className,
variant = "default",
render,
...props
}: useRender.ComponentProps<"div"> & VariantProps<typeof markerVariants>) {
return useRender({
defaultTagName: "div",
props: mergeProps<"div">(
{
className: cn(markerVariants({ variant, className })),
},
props
),
render,
state: {
slot: "marker",
variant,
},
})
}
function MarkerIcon({ className, ...props }: React.ComponentProps<"span">) {
return (
<span
data-slot="marker-icon"
aria-hidden="true"
className={cn(
"size-4 shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
/>
)
}
function MarkerContent({ className, ...props }: React.ComponentProps<"span">) {
return (
<span
data-slot="marker-content"
className={cn(
"min-w-0 wrap-break-word group-data-[variant=separator]/marker:flex-none group-data-[variant=separator]/marker:text-center *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",
className
)}
{...props}
/>
)
}
export { Marker, MarkerIcon, MarkerContent, markerVariants }
+90
View File
@@ -0,0 +1,90 @@
"use client"
import * as React from "react"
import { Popover as PopoverPrimitive } from "@base-ui/react/popover"
import { cn } from "@/lib/utils"
function Popover({ ...props }: PopoverPrimitive.Root.Props) {
return <PopoverPrimitive.Root data-slot="popover" {...props} />
}
function PopoverTrigger({ ...props }: PopoverPrimitive.Trigger.Props) {
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
}
function PopoverContent({
className,
align = "center",
alignOffset = 0,
side = "bottom",
sideOffset = 4,
...props
}: PopoverPrimitive.Popup.Props &
Pick<
PopoverPrimitive.Positioner.Props,
"align" | "alignOffset" | "side" | "sideOffset"
>) {
return (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Positioner
align={align}
alignOffset={alignOffset}
side={side}
sideOffset={sideOffset}
className="isolate z-50"
>
<PopoverPrimitive.Popup
data-slot="popover-content"
className={cn(
"z-50 flex w-72 origin-(--transform-origin) flex-col gap-2.5 rounded-lg bg-popover p-2.5 text-sm text-popover-foreground shadow-md ring-1 ring-foreground/10 outline-hidden duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
className
)}
{...props}
/>
</PopoverPrimitive.Positioner>
</PopoverPrimitive.Portal>
)
}
function PopoverHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="popover-header"
className={cn("flex flex-col gap-0.5 text-sm", className)}
{...props}
/>
)
}
function PopoverTitle({ className, ...props }: PopoverPrimitive.Title.Props) {
return (
<PopoverPrimitive.Title
data-slot="popover-title"
className={cn("font-medium", className)}
{...props}
/>
)
}
function PopoverDescription({
className,
...props
}: PopoverPrimitive.Description.Props) {
return (
<PopoverPrimitive.Description
data-slot="popover-description"
className={cn("text-muted-foreground", className)}
{...props}
/>
)
}
export {
Popover,
PopoverContent,
PopoverDescription,
PopoverHeader,
PopoverTitle,
PopoverTrigger,
}
+83
View File
@@ -0,0 +1,83 @@
"use client"
import { Progress as ProgressPrimitive } from "@base-ui/react/progress"
import { cn } from "@/lib/utils"
function Progress({
className,
children,
value,
...props
}: ProgressPrimitive.Root.Props) {
return (
<ProgressPrimitive.Root
value={value}
data-slot="progress"
className={cn("flex flex-wrap gap-3", className)}
{...props}
>
{children}
<ProgressTrack>
<ProgressIndicator />
</ProgressTrack>
</ProgressPrimitive.Root>
)
}
function ProgressTrack({ className, ...props }: ProgressPrimitive.Track.Props) {
return (
<ProgressPrimitive.Track
className={cn(
"relative flex h-1 w-full items-center overflow-x-hidden rounded-full bg-muted",
className
)}
data-slot="progress-track"
{...props}
/>
)
}
function ProgressIndicator({
className,
...props
}: ProgressPrimitive.Indicator.Props) {
return (
<ProgressPrimitive.Indicator
data-slot="progress-indicator"
className={cn("h-full bg-primary transition-all", className)}
{...props}
/>
)
}
function ProgressLabel({ className, ...props }: ProgressPrimitive.Label.Props) {
return (
<ProgressPrimitive.Label
className={cn("text-sm font-medium", className)}
data-slot="progress-label"
{...props}
/>
)
}
function ProgressValue({ className, ...props }: ProgressPrimitive.Value.Props) {
return (
<ProgressPrimitive.Value
className={cn(
"ml-auto text-sm text-muted-foreground tabular-nums",
className
)}
data-slot="progress-value"
{...props}
/>
)
}
export {
Progress,
ProgressTrack,
ProgressIndicator,
ProgressLabel,
ProgressValue,
}
+201
View File
@@ -0,0 +1,201 @@
"use client"
import * as React from "react"
import { Select as SelectPrimitive } from "@base-ui/react/select"
import { cn } from "@/lib/utils"
import { ChevronDownIcon, CheckIcon, ChevronUpIcon } from "lucide-react"
const Select = SelectPrimitive.Root
function SelectGroup({ className, ...props }: SelectPrimitive.Group.Props) {
return (
<SelectPrimitive.Group
data-slot="select-group"
className={cn("scroll-my-1 p-1", className)}
{...props}
/>
)
}
function SelectValue({ className, ...props }: SelectPrimitive.Value.Props) {
return (
<SelectPrimitive.Value
data-slot="select-value"
className={cn("flex flex-1 text-left", className)}
{...props}
/>
)
}
function SelectTrigger({
className,
size = "default",
children,
...props
}: SelectPrimitive.Trigger.Props & {
size?: "sm" | "default"
}) {
return (
<SelectPrimitive.Trigger
data-slot="select-trigger"
data-size={size}
className={cn(
"flex w-fit items-center justify-between gap-1.5 rounded-lg border border-input bg-transparent py-2 pr-2 pl-2.5 text-sm whitespace-nowrap transition-colors outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-placeholder:text-muted-foreground data-[size=default]:h-8 data-[size=sm]:h-7 data-[size=sm]:rounded-[min(var(--radius-md),10px)] *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
{children}
<SelectPrimitive.Icon
render={
<ChevronDownIcon className="pointer-events-none size-4 text-muted-foreground" />
}
/>
</SelectPrimitive.Trigger>
)
}
function SelectContent({
className,
children,
side = "bottom",
sideOffset = 4,
align = "center",
alignOffset = 0,
alignItemWithTrigger = true,
...props
}: SelectPrimitive.Popup.Props &
Pick<
SelectPrimitive.Positioner.Props,
"align" | "alignOffset" | "side" | "sideOffset" | "alignItemWithTrigger"
>) {
return (
<SelectPrimitive.Portal>
<SelectPrimitive.Positioner
side={side}
sideOffset={sideOffset}
align={align}
alignOffset={alignOffset}
alignItemWithTrigger={alignItemWithTrigger}
className="isolate z-50"
>
<SelectPrimitive.Popup
data-slot="select-content"
data-align-trigger={alignItemWithTrigger}
className={cn("relative isolate z-50 max-h-(--available-height) w-(--anchor-width) min-w-36 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[align-trigger=true]:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className )}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.List>{children}</SelectPrimitive.List>
<SelectScrollDownButton />
</SelectPrimitive.Popup>
</SelectPrimitive.Positioner>
</SelectPrimitive.Portal>
)
}
function SelectLabel({
className,
...props
}: SelectPrimitive.GroupLabel.Props) {
return (
<SelectPrimitive.GroupLabel
data-slot="select-label"
className={cn("px-1.5 py-1 text-xs text-muted-foreground", className)}
{...props}
/>
)
}
function SelectItem({
className,
children,
...props
}: SelectPrimitive.Item.Props) {
return (
<SelectPrimitive.Item
data-slot="select-item"
className={cn(
"relative flex w-full cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
className
)}
{...props}
>
<SelectPrimitive.ItemText className="flex flex-1 shrink-0 gap-2 whitespace-nowrap">
{children}
</SelectPrimitive.ItemText>
<SelectPrimitive.ItemIndicator
render={
<span className="pointer-events-none absolute right-2 flex size-4 items-center justify-center" />
}
>
<CheckIcon className="pointer-events-none" />
</SelectPrimitive.ItemIndicator>
</SelectPrimitive.Item>
)
}
function SelectSeparator({
className,
...props
}: SelectPrimitive.Separator.Props) {
return (
<SelectPrimitive.Separator
data-slot="select-separator"
className={cn("pointer-events-none -mx-1 my-1 h-px bg-border", className)}
{...props}
/>
)
}
function SelectScrollUpButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpArrow>) {
return (
<SelectPrimitive.ScrollUpArrow
data-slot="select-scroll-up-button"
className={cn(
"top-0 z-10 flex w-full cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
<ChevronUpIcon
/>
</SelectPrimitive.ScrollUpArrow>
)
}
function SelectScrollDownButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownArrow>) {
return (
<SelectPrimitive.ScrollDownArrow
data-slot="select-scroll-down-button"
className={cn(
"bottom-0 z-10 flex w-full cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
<ChevronDownIcon
/>
</SelectPrimitive.ScrollDownArrow>
)
}
export {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectScrollDownButton,
SelectScrollUpButton,
SelectSeparator,
SelectTrigger,
SelectValue,
}
@@ -0,0 +1,25 @@
"use client"
import { Separator as SeparatorPrimitive } from "@base-ui/react/separator"
import { cn } from "@/lib/utils"
function Separator({
className,
orientation = "horizontal",
...props
}: SeparatorPrimitive.Props) {
return (
<SeparatorPrimitive
data-slot="separator"
orientation={orientation}
className={cn(
"shrink-0 bg-border data-horizontal:h-px data-horizontal:w-full data-vertical:w-px data-vertical:self-stretch",
className
)}
{...props}
/>
)
}
export { Separator }
+13
View File
@@ -0,0 +1,13 @@
import { cn } from "cn"
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="skeleton"
className={cn("animate-pulse rounded-md bg-muted", className)}
{...props}
/>
)
}
export { Skeleton }
+15
View File
@@ -0,0 +1,15 @@
"use client"
import { cn } from "@/lib/utils"
import { Loader2Icon } from "lucide-react"
import { useTranslations } from "next-intl"
function Spinner({ className, ...props }: React.ComponentProps<"svg">) {
const t = useTranslations("Common")
return (
<Loader2Icon data-slot="spinner" role="status" aria-label={t("loading")} className={cn("size-4 animate-spin", className)} {...props} />
)
}
export { Spinner }
+82
View File
@@ -0,0 +1,82 @@
"use client"
import { Tabs as TabsPrimitive } from "@base-ui/react/tabs"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
function Tabs({
className,
orientation = "horizontal",
...props
}: TabsPrimitive.Root.Props) {
return (
<TabsPrimitive.Root
data-slot="tabs"
data-orientation={orientation}
className={cn(
"group/tabs flex gap-2 data-horizontal:flex-col",
className
)}
{...props}
/>
)
}
const tabsListVariants = cva(
"group/tabs-list inline-flex w-fit items-center justify-center rounded-lg p-[3px] text-muted-foreground group-data-horizontal/tabs:h-8 group-data-vertical/tabs:h-fit group-data-vertical/tabs:flex-col data-[variant=line]:rounded-none",
{
variants: {
variant: {
default: "bg-muted",
line: "gap-1 bg-transparent",
},
},
defaultVariants: {
variant: "default",
},
}
)
function TabsList({
className,
variant = "default",
...props
}: TabsPrimitive.List.Props & VariantProps<typeof tabsListVariants>) {
return (
<TabsPrimitive.List
data-slot="tabs-list"
data-variant={variant}
className={cn(tabsListVariants({ variant }), className)}
{...props}
/>
)
}
function TabsTrigger({ className, ...props }: TabsPrimitive.Tab.Props) {
return (
<TabsPrimitive.Tab
data-slot="tabs-trigger"
className={cn(
"relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-1.5 py-0.5 text-sm font-medium whitespace-nowrap text-foreground/60 transition-all group-data-vertical/tabs:w-full group-data-vertical/tabs:justify-start hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-50 has-data-[icon=inline-end]:pr-1 has-data-[icon=inline-start]:pl-1 aria-disabled:pointer-events-none aria-disabled:opacity-50 dark:text-muted-foreground dark:hover:text-foreground group-data-[variant=default]/tabs-list:data-active:shadow-sm group-data-[variant=line]/tabs-list:data-active:shadow-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
"group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-active:bg-transparent dark:group-data-[variant=line]/tabs-list:data-active:border-transparent dark:group-data-[variant=line]/tabs-list:data-active:bg-transparent",
"data-active:bg-background data-active:text-foreground dark:data-active:border-input dark:data-active:bg-input/30 dark:data-active:text-foreground",
"after:absolute after:bg-foreground after:opacity-0 after:transition-opacity group-data-horizontal/tabs:after:inset-x-0 group-data-horizontal/tabs:after:bottom-[-5px] group-data-horizontal/tabs:after:h-0.5 group-data-vertical/tabs:after:inset-y-0 group-data-vertical/tabs:after:-right-1 group-data-vertical/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-active:after:opacity-100",
className
)}
{...props}
/>
)
}
function TabsContent({ className, ...props }: TabsPrimitive.Panel.Props) {
return (
<TabsPrimitive.Panel
data-slot="tabs-content"
className={cn("flex-1 text-sm outline-none", className)}
{...props}
/>
)
}
export { Tabs, TabsList, TabsTrigger, TabsContent, tabsListVariants }
+18
View File
@@ -0,0 +1,18 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
return (
<textarea
data-slot="textarea"
className={cn(
"flex field-sizing-content min-h-16 w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-base transition-colors outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",
className
)}
{...props}
/>
)
}
export { Textarea }
@@ -0,0 +1,206 @@
"use client";
import { useCallback, useState } from "react";
import { lookupDictionary } from "@/lib/api";
import { useResource } from "@/hooks/useResource";
import { resolveApiErrorMessage } from "@/lib/useApiErrorMessage";
import type { DictionaryResult, Entry, Fetched, Language } from "@/types/api";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { ChevronDownIcon, ChevronUpIcon } from "lucide-react";
import { Marker, MarkerContent, MarkerIcon } from "./ui/marker";
import { Spinner } from "./ui/spinner";
import { useTranslations } from "next-intl";
const INITIAL_SENSES_SHOWN = 3;
const INITIAL_SYNONYMS_SHOWN = 12;
const GENDER_BADGE_CLASSES: Record<string, string> = {
masculine: "text-white bg-sky-500 dark:bg-sky-800",
feminine: "text-white bg-rose-500 dark:bg-rose-800",
};
function EntrySection({ entry }: { entry: Entry }) {
const [sensesExpanded, setSensesExpanded] = useState(false);
const [synonymsExpanded, setSynonymsExpanded] = useState(false);
const hasMoreSenses = entry.senses.length > INITIAL_SENSES_SHOWN;
const visibleSenses = sensesExpanded
? entry.senses
: entry.senses.slice(0, INITIAL_SENSES_SHOWN);
const synonymsCount = entry.synonyms?.length ?? 0;
const hasMoreSynonyms = synonymsCount > INITIAL_SYNONYMS_SHOWN;
const visibleSynonyms = synonymsExpanded
? entry.synonyms
: entry.synonyms?.slice(0, INITIAL_SYNONYMS_SHOWN);
const tc = useTranslations("Common");
const td = useTranslations("Definition");
return (
<div className="flex flex-col gap-2">
<div className="flex flex-row items-center gap-2 mb-2">
<h4 className="font-semibold italic">{entry.partOfSpeech}</h4>
{entry.ipa && (
<h4 className="text-muted-foreground">/{entry.ipa.replace(/\//g, "")}/</h4>
)}
</div>
<div className="flex flex-col gap-4">
{visibleSenses.map((sense, 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">
{sense.tags && sense.tags.length > 0 && (
<div className="flex flex-row flex-wrap gap-1">
{sense.tags.map((tag) => (
<Badge
key={tag}
variant="secondary"
className={GENDER_BADGE_CLASSES[tag.trim().toLowerCase()]}
>
{tag}
</Badge>
))}
</div>
)}
<div className="flex flex-col">
<p>{sense.definition}</p>
{sense.examples?.[0] && (
<p className="text-muted-foreground italic">
&quot;{sense.examples[0]}&quot;
</p>
)}
</div>
</div>
</div>
))}
</div>
{hasMoreSenses && (
<Button
variant="ghost"
size="sm"
className="w-max text-muted-foreground mt-2"
onClick={() => setSensesExpanded((v) => !v)}
>
<div className="flex flex-row items-center gap-2">
{sensesExpanded ? <ChevronUpIcon /> : <ChevronDownIcon />}
<h5>
{sensesExpanded
? tc("showLess")
: tc("showMore", { count: entry.senses.length - INITIAL_SENSES_SHOWN })}
</h5>
</div>
</Button>
)}
{(entry.synonyms || entry.antonyms) && (
<div className="flex flex-col gap-4 my-4">
{entry.synonyms && entry.synonyms.length > 0 && (
<div className="flex flex-col gap-4">
<h4 className="font-semibold">{td("synonyms")}</h4>
<div className="flex flex-row flex-wrap gap-2">
{visibleSynonyms?.map((s, i) => (
<Badge variant="outline" key={i} className="h-6">
<h5>{s}</h5>
</Badge>
))}
</div>
{hasMoreSynonyms && (
<Button
variant="ghost"
size="sm"
className="w-max text-muted-foreground"
onClick={() => setSynonymsExpanded((v) => !v)}
>
<div className="flex flex-row items-center gap-2">
{synonymsExpanded ? <ChevronUpIcon /> : <ChevronDownIcon />}
<h5>
{synonymsExpanded
? tc("showLess")
: tc("showMore", { count: synonymsCount - INITIAL_SYNONYMS_SHOWN })}
</h5>
</div>
</Button>
)}
</div>
)}
{entry.antonyms && entry.antonyms.length > 0 && (
<div className="flex flex-row flex-wrap gap-4">
<h4 className="font-semibold">{td("antonyms")}</h4>
{entry.antonyms.map((s, i) => (
<Badge variant="outline" key={i} className="h-6">
<h5>{s}</h5>
</Badge>
))}
</div>
)}
</div>
)}
</div>
);
}
interface WordDefinitionProps {
word: string;
lang: Language;
onResult?: (result: Fetched<DictionaryResult>) => void;
}
export function WordDefinition({ word, lang, onResult }: WordDefinitionProps) {
const cacheKey = `dict:${lang}:${word.toLowerCase()}`;
const report = useCallback(
(data: DictionaryResult) =>
onResult?.({
...data,
fetched_at: new Date().toISOString(),
}),
[onResult]
);
const state = useResource<DictionaryResult>(
cacheKey,
() => lookupDictionary(lang, word),
report
);
const t = useTranslations("Definition");
const tApi = useTranslations("ApiErrors");
const errorMessage = resolveApiErrorMessage(
state.error,
(kind) => (kind === "not-found" ? t("notFound") : tApi(kind)),
t("notFound")
);
return (
<div className="flex flex-col gap-4">
<h2 className="font-semibold">{word}</h2>
{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" &&
state.data?.entries.map((entry, i) => (
<div key={i}>
{i > 0 && <Separator className="mb-4" />}
<EntrySection entry={entry} />
</div>
))}
</div>
);
}
+18
View File
@@ -0,0 +1,18 @@
import { defineConfig, globalIgnores } from "eslint/config";
import nextVitals from "eslint-config-next/core-web-vitals";
import nextTs from "eslint-config-next/typescript";
const eslintConfig = defineConfig([
...nextVitals,
...nextTs,
// Override default ignores of eslint-config-next.
globalIgnores([
// Default ignores of eslint-config-next:
".next/**",
"out/**",
"build/**",
"next-env.d.ts",
]),
]);
export default eslintConfig;
+16
View File
@@ -0,0 +1,16 @@
"use client";
import { useEffect, useState } from "react";
export const LOOKUP_DEBOUNCE_MS = 800;
export function useDebouncedValue<T>(value: T, delayMs: number): T {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = setTimeout(() => setDebounced(value), delayMs);
return () => clearTimeout(id);
}, [value, delayMs]);
return debounced;
}
+97
View File
@@ -0,0 +1,97 @@
"use client";
import { useEffect, useRef, useState } from "react";
export type ResourceStatus = "loading" | "done" | "error";
export interface ResourceState<T> {
status: ResourceStatus;
data?: T;
error?: unknown;
}
const cache = new Map<string, unknown>();
const inFlight = new Map<string, Promise<unknown>>();
function cachedHit<T>(key: string | null): T | undefined {
if (key != null && cache.has(key)) return cache.get(key) as T;
return undefined;
}
function dedupedFetch<T>(key: string, fetcher: () => Promise<T>): Promise<T> {
if (cache.has(key)) return Promise.resolve(cache.get(key) as T);
const running = inFlight.get(key) as Promise<T> | undefined;
if (running) return running;
const promise = fetcher()
.then((data) => {
cache.set(key, data);
return data;
})
.finally(() => {
inFlight.delete(key);
});
inFlight.set(key, promise);
return promise;
}
/**
* Loads a resource once per key, sharing the cache and in-flight requests
* across all mounts. Reports the fetched (or cached) value through `onData`
* so owners can hoist the result into their own state.
*/
export function useResource<T>(
key: string | null,
fetcher: (() => Promise<T>) | null,
onData?: (data: T) => void
): ResourceState<T> {
const fetcherRef = useRef(fetcher);
const onDataRef = useRef(onData);
useEffect(() => {
fetcherRef.current = fetcher;
onDataRef.current = onData;
});
const [state, setState] = useState<ResourceState<T>>(() => {
const hit = cachedHit<T>(key);
return hit !== undefined ? { status: "done", data: hit } : { status: "loading" };
});
const [prevKey, setPrevKey] = useState<string | null>(key);
if (key !== prevKey) {
setPrevKey(key);
const hit = cachedHit<T>(key);
setState(hit !== undefined ? { status: "done", data: hit } : { status: "loading" });
}
useEffect(() => {
if (!key || !fetcherRef.current) return;
if (cache.has(key)) {
onDataRef.current?.(cache.get(key) as T);
return;
}
let cancelled = false;
const run = fetcherRef.current;
dedupedFetch(key, run)
.then((data) => {
if (cancelled) return;
setState({ status: "done", data });
onDataRef.current?.(data);
})
.catch((err) => {
if (cancelled) return;
setState({ status: "error", error: err });
});
return () => {
cancelled = true;
};
}, [key]);
return state;
}
+90
View File
@@ -0,0 +1,90 @@
"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,
};
}
+16
View File
@@ -0,0 +1,16 @@
import {getRequestConfig} from "next-intl/server";
import { cookies } from "next/headers";
import { LANGUAGE_CODES } from "@/types/api";
export default getRequestConfig(async () => {
const store = await cookies();
const requested = store.get("locale")?.value ?? "";
const locale = LANGUAGE_CODES.includes(requested as (typeof LANGUAGE_CODES)[number])
? requested
: "en";
return {
locale,
messages: (await import(`../messages/${locale}.json`)).default
};
});
+223
View File
@@ -0,0 +1,223 @@
import type {
CollectionResult,
CollocationsResult,
DictionaryResult,
ExamplesResult,
Language,
TranslationResult,
UsageResult,
} from "@/types/api";
export type ApiErrorKind = "network" | "auth" | "quota" | "not-found" | "server";
export interface ApiError {
kind: ApiErrorKind;
}
export type ErrorWithKind = Error & ApiError;
export interface RawCollection {
id: string;
name: string;
lang: Language;
user_id: string;
words: string[];
type: "auto" | "user";
created_at: string;
updated_at: string;
}
export function apiError(kind: ApiErrorKind): ErrorWithKind {
const err = new Error(kind) as ErrorWithKind;
err.kind = kind;
return err;
}
export function isApiError(err: unknown): err is ErrorWithKind {
return (
err instanceof Error &&
"kind" in err &&
typeof (err as ErrorWithKind).kind === "string"
);
}
export function normalizeCollection(raw: RawCollection): CollectionResult {
return {
id: raw.id,
name: raw.name,
lang: raw.lang,
userId: raw.user_id,
words: raw.words,
type: raw.type,
created_at: raw.created_at,
updated_at: raw.updated_at,
};
}
export async function parseBody<T>(response: Response): Promise<T> {
const text = await response.text();
if (!text) return undefined as T;
return JSON.parse(text) as T;
}
export function errorKind(status: number): ApiErrorKind {
if (status === 401) return "auth";
if (status === 429) return "quota";
if (status === 404) return "not-found";
return "server";
}
async function request<T>(path: string, init?: RequestInit): Promise<T> {
let response: Response;
try {
response = await fetch(path, init);
} catch (err) {
if (err instanceof Error && err.name === "AbortError") throw err;
throw apiError("network");
}
if (!response.ok) throw apiError(errorKind(response.status));
return parseBody<T>(response);
}
const jsonHeaders = { "Content-Type": "application/json" };
export function translateText(
{ text, from, to }: { text: string; from: Language; to: Language },
signal?: AbortSignal
): Promise<TranslationResult> {
return request<TranslationResult>("/api/translate", {
method: "POST",
headers: jsonHeaders,
body: JSON.stringify({ text, from, to }),
signal,
});
}
export function lookupDictionary(
lang: Language,
word: string,
signal?: AbortSignal
): Promise<DictionaryResult> {
return request<DictionaryResult>(
`/api/dictionary/${lang}/${encodeURIComponent(word)}`,
{ signal }
);
}
export function getCollocations(
lang: Language,
word: string,
signal?: AbortSignal
): Promise<CollocationsResult> {
return request<CollocationsResult>(
`/api/collocations/${lang}/${encodeURIComponent(word)}`,
{ signal }
);
}
export function getExamples(
lang: Language,
word: string,
signal?: AbortSignal
): Promise<ExamplesResult> {
return request<ExamplesResult>(
`/api/examples/${lang}/${encodeURIComponent(word)}`,
{ signal }
);
}
export async function getCollections(
signal?: AbortSignal
): Promise<CollectionResult[]> {
try {
const raw = await request<RawCollection[]>("/api/collections", { signal });
return raw.map(normalizeCollection);
} catch (err) {
if (isApiError(err) && err.kind === "not-found") return [];
throw err;
}
}
export async function createCollection(
name: string,
lang: Language,
signal?: AbortSignal
): Promise<CollectionResult> {
const raw = await request<RawCollection>("/api/collections", {
signal,
method: "POST",
headers: jsonHeaders,
body: JSON.stringify({ name, lang }),
});
return normalizeCollection(raw);
}
export async function getCollectionsByWord(
lang: Language,
word: string,
signal?: AbortSignal
): Promise<CollectionResult[]> {
try {
const raw = await request<RawCollection[]>(
`/api/collections/search/${lang}/${encodeURIComponent(word)}`,
{ signal }
);
return raw.map(normalizeCollection);
} catch (err) {
if (isApiError(err) && err.kind === "not-found") return [];
throw err;
}
}
export function deleteCollection(id: string, signal?: AbortSignal) {
return request<void>(`/api/collections/${id}`, {
signal,
method: "DELETE",
});
}
export async function updateCollection(
id: string,
name: string,
signal?: AbortSignal
): Promise<CollectionResult> {
const raw = await request<RawCollection>(`/api/collections/${id}`, {
signal,
method: "PATCH",
headers: jsonHeaders,
body: JSON.stringify({ name }),
});
return normalizeCollection(raw);
}
export async function addWordsToCollection(
id: string,
words: string[],
signal?: AbortSignal
): Promise<CollectionResult> {
const raw = await request<RawCollection>(`/api/collections/${id}/words`, {
signal,
method: "POST",
headers: jsonHeaders,
body: JSON.stringify({ words }),
});
return normalizeCollection(raw);
}
export async function deleteWordFromCollection(
id: string,
word: string,
signal?: AbortSignal
): Promise<CollectionResult> {
const raw = await request<RawCollection>(
`/api/collections/${id}/words?word=${encodeURIComponent(word)}`,
{ signal, method: "DELETE" }
);
return normalizeCollection(raw);
}
export function getUsage(signal?: AbortSignal): Promise<UsageResult> {
return request<UsageResult>("/api/usage", { signal });
}
+20
View File
@@ -0,0 +1,20 @@
import { cookies } from "next/headers";
const BACKEND_URL = process.env.BACKEND_URL!;
interface BackendInit extends RequestInit {
next?: { revalidate?: number | false; tags?: string[] };
}
export async function backendFetch(
path: string,
init: BackendInit = {}
): Promise<Response> {
const { next, ...restInit } = init;
const headers = new Headers(restInit.headers);
const token = (await cookies()).get("session")?.value;
if (token) headers.set("Authorization", `Bearer ${token}`);
return fetch(`${BACKEND_URL}${path}`, { ...restInit, headers, next });
}
+66
View File
@@ -0,0 +1,66 @@
const MINUTE = 60_000;
const HOUR = 60 * MINUTE;
const DAY = 24 * HOUR;
const MONTH = 30 * DAY;
export type RelativeTimeKey =
| "now"
| "minutes"
| "hours"
| "yesterday"
| "days"
| "month"
| "months"
| "year"
| "moreThanYear";
export type RelativeTimeTranslator = (
key: RelativeTimeKey,
values?: { count?: number }
) => string;
/**
* Formats an ISO date as a localized relative time using the following
* thresholds:
*
* - < 1 minute -> "Now"
* - < 1 hour -> "X minutes ago"
* - < 24 hours -> "X hours ago"
* - 1 day -> "Yesterday"
* - < 30 days -> "X days ago"
* - 1 month -> "A month ago"
* - < 12 months -> "X months ago"
* - 12-23 months -> "A year ago"
* - >= 24 months -> "More than a year ago"
*/
export function formatDate(
dateString: string,
t: RelativeTimeTranslator,
now: Date = new Date()
): string {
const date = new Date(dateString);
if (Number.isNaN(date.getTime())) return dateString;
const diffMs = now.getTime() - date.getTime();
// Future dates (or the very same moment) are shown as "now".
if (diffMs < MINUTE) return t("now");
const minutes = Math.floor(diffMs / MINUTE);
if (minutes < 60) return t("minutes", { count: minutes });
const hours = Math.floor(diffMs / HOUR);
if (hours < 24) return t("hours", { count: hours });
const days = Math.floor(diffMs / DAY);
if (days === 1) return t("yesterday");
if (days < 30) return t("days", { count: days });
const months = Math.floor(diffMs / MONTH);
if (months === 1) return t("month");
if (months < 12) return t("months", { count: months });
const years = Math.floor(months / 12);
if (years === 1) return t("year");
return t("moreThanYear");
}
+10
View File
@@ -0,0 +1,10 @@
import type { UiLanguage } from "@/types/language";
export const LANGUAGES: readonly UiLanguage[] = [
{ id: "en", autonym: "English", flag: "/uk.svg" },
{ id: "it", autonym: "Italiano", flag: "/it.svg" },
{ id: "ru", autonym: "Русский", flag: "/ru.svg" },
];
export const DEFAULT_SOURCE_LANG = LANGUAGES[0];
export const DEFAULT_TARGET_LANG = LANGUAGES[1];
+13
View File
@@ -0,0 +1,13 @@
import { randomBytes, createHash } from "crypto";
export function generateCodeVerifier(): string {
return randomBytes(32).toString("base64url");
}
export function generateCodeChallenge(verifier: string): string {
return createHash("sha256").update(verifier).digest("base64url");
}
export function generateState(): string {
return randomBytes(16).toString("base64url");
}
+47
View File
@@ -0,0 +1,47 @@
import { backendFetch } from "./backend";
import {
apiError,
errorKind,
isApiError,
normalizeCollection,
parseBody,
type RawCollection,
} from "./api";
import type { CollectionResult, DictionaryResult, Language } from "@/types/api";
async function serverRequest<T>(path: string, init?: RequestInit): Promise<T> {
let response: Response;
try {
response = await backendFetch(path, init);
} catch {
throw apiError("network");
}
if (!response.ok) throw apiError(errorKind(response.status));
return parseBody<T>(response);
}
export async function getCollections(): Promise<CollectionResult[]> {
try {
const raw = await serverRequest<RawCollection[]>("/api/collections");
return raw.map(normalizeCollection);
} catch (err) {
if (isApiError(err) && err.kind === "not-found") return [];
throw err;
}
}
export async function getCollection(id: string): Promise<CollectionResult> {
const raw = await serverRequest<RawCollection>(`/api/collections/${encodeURIComponent(id)}`);
return normalizeCollection(raw);
}
export function lookupDictionary(
lang: Language,
word: string
): Promise<DictionaryResult> {
return serverRequest<DictionaryResult>(
`/api/dictionary/${lang}/${encodeURIComponent(word)}`
);
}
+12
View File
@@ -0,0 +1,12 @@
import type { User } from "@/types/api";
import { backendFetch } from "./backend";
export async function getUser(): Promise<User | null> {
try {
const response = await backendFetch(`/api/auth/me`);
if (!response.ok) return null;
return (await response.json()) as User;
} catch {
return null;
}
}
+19
View File
@@ -0,0 +1,19 @@
"use client";
import { useTranslations } from "next-intl";
import { isApiError, type ApiErrorKind } from "@/lib/api";
export function useApiErrorMessage(kind?: ApiErrorKind | null): string | null {
const t = useTranslations("ApiErrors");
if (!kind) return null;
return t(kind);
}
export function resolveApiErrorMessage(
err: unknown,
t: (key: ApiErrorKind) => string,
fallback: string
): string {
if (isApiError(err)) return t(err.kind);
return fallback;
}
+17
View File
@@ -0,0 +1,17 @@
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
export function formatTimestamp(iso?: string, locale?: string) {
if (!iso) return null
const date = new Date(iso)
if (Number.isNaN(date.getTime())) return null
return date.toLocaleString(locale, { dateStyle: "medium", timeStyle: "short" })
}
export function formatNumber(value: number, locale?: string) {
return value.toLocaleString(locale)
}
+164
View File
@@ -0,0 +1,164 @@
{
"Common": {
"cancel": "Cancel",
"create": "Create",
"update": "Update",
"loading": "Loading...",
"somethingWrong": "Something went wrong",
"seeAll": "See all",
"word": "word",
"words": "words",
"updated": "Updated",
"andMore": "And {count} more",
"showLess": "Show less",
"showMore": "Show {count} more",
"copy": "Copy",
"copied": "Copied",
"provider": "Provider",
"cache": "Cache",
"source": "Source",
"model": "Model",
"generated": "Generated",
"fetched": "Fetched",
"dash": "—",
"close": "Close",
"search": "Search...",
"history": "History"
},
"App": {
"title": "Fancy"
},
"Home": {
"sourcePlaceholder": "Start to write",
"translatedPlaceholder": "Translation will appear here",
"definition": "Definition",
"usageExamples": "Usage examples",
"collocations": "Collocations",
"loadingDefinition": "Loading definition...",
"generatingCollocations": "Generating collocations...",
"generatingExamples": "Generating examples...",
"clickWordHint": "Click on the word to see its definition"
},
"Theme": {
"toggle": "Toggle theme",
"light": "Light",
"dark": "Dark",
"system": "System"
},
"Locale": {
"switch": "Switch language",
"en": "English",
"it": "Italian",
"ru": "Russian"
},
"Languages": {
"en": "English",
"it": "Italian",
"ru": "Russian"
},
"Time": {
"now": "Now",
"minutes": "{count, plural, one {# minute ago} other {# minutes ago}}",
"hours": "{count, plural, one {# hour ago} other {# hours ago}}",
"yesterday": "Yesterday",
"days": "{count, plural, one {# day ago} other {# days ago}}",
"month": "A month ago",
"months": "{count, plural, one {# month ago} other {# months ago}}",
"year": "A year ago",
"moreThanYear": "More than a year ago"
},
"ApiErrors": {
"network": "Cannot reach Fancy server. Check your connection.",
"auth": "Please log in to use this feature.",
"quota": "Fancy is out of tokens for this month",
"not-found": "Nothing was found",
"server": "Request failed. Try again later."
},
"Header": {
"login": "Log in",
"logout": "Log out",
"collections": "Collections"
},
"OAuth": {
"title": "Sign-in failed",
"tryAgain": "Try again",
"auth_failed": "The sign-in could not be completed.",
"state_mismatch": "The sign-in request did not match. Please try again.",
"token_exchange_failed": "We could not verify your identity.",
"session_failed": "A session could not be created."
},
"Definition": {
"loading": "Loading definition...",
"notFound": "We do not have a definition for this word",
"synonyms": "Synonyms",
"antonyms": "Antonyms",
"otherDefinitions": "(Has {count} other {count, plural, one {definition} other {definitions}})"
},
"Collocations": {
"title": "Collocations",
"loading": "Generating collocations...",
"notFound": "No collocations found for this word",
"failed": "Generation did not succeed"
},
"Examples": {
"title": "Usage examples",
"loading": "Generating examples...",
"notFound": "No examples found for this word",
"failed": "Generation did not succeed"
},
"Properties": {
"title": "Properties",
"details": "Translation details",
"translate": "Translate",
"definition": "Definition",
"examples": "Examples",
"collocations": "Collocations",
"usage": "Usage",
"usageUnavailable": "Usage is unavailable",
"loadingUsage": "Loading usage...",
"deeplCharacters": "DeepL characters",
"deeplUnavailable": "DeepL usage is unavailable",
"aiTokens": "AI tokens",
"requestsThisMonth": "{count, plural, one {# request this month} other {# requests this month}}"
},
"Collections": {
"title": "Collections",
"create": "New collection",
"createTitle": "Create collection",
"nameLabel": "Name",
"namePlaceholder": "My collection",
"languageLabel": "Language",
"createFailed": "Failed to create collection. Please try again.",
"empty": "No collections yet. Create one!",
"noWords": "There are no words yet. Add one!",
"noSearchResults": "No words match your search"
},
"CollectionMenu": {
"title": "Properties",
"nameLabel": "Name",
"namePlaceholder": "My collection",
"ownedBy": "Owned by",
"language": "Language",
"wordCount": "Word(s)",
"lastUpdate": "Last update",
"created": "Created",
"delete": "Delete collection",
"autoTitle": "This collection is generated automatically",
"autoDescription": "It was generated and is being updated by the system. You cannot edit or delete it.",
"deleteFailed": "Failed to delete collection. Please try again.",
"updateFailed": "Failed to update collection. Please try again."
},
"CollectionsList": {
"trigger": "Add to a collection",
"dialogTitle": "Add \"{word}\" to a collection",
"empty": "You have not created any collections in this language yet.",
"addAction": "Add",
"removeAction": "Remove",
"loadFailed": "Could not load your collections",
"notFound": "Not saved in any collection yet",
"toggleFailed": "Couldn't update this collection, try again",
"showCollections": "In {count, plural, =0 {no collections} one {# collection} other {# collections}}",
"expand": "Show collections",
"collapse": "Hide collections"
}
}
+164
View File
@@ -0,0 +1,164 @@
{
"Common": {
"cancel": "Annulla",
"create": "Crea",
"update": "Aggiorna",
"loading": "Caricamento...",
"somethingWrong": "Qualcosa è andato storto",
"seeAll": "Vedi tutto",
"word": "parola",
"words": "parole",
"updated": "Aggiornato",
"andMore": "E altre {count}",
"showLess": "Mostra meno",
"showMore": "Mostra altre {count}",
"copy": "Copia",
"copied": "Copiato",
"provider": "Provider",
"cache": "Cache",
"source": "Origine",
"model": "Modello",
"generated": "Generato",
"fetched": "Recuperato",
"dash": "—",
"close": "Chiudi",
"search": "Cerca...",
"history": "Cronologia"
},
"App": {
"title": "Fancy"
},
"Home": {
"sourcePlaceholder": "Inizia a scrivere",
"translatedPlaceholder": "La traduzione apparirà qui",
"definition": "Definizione",
"usageExamples": "Esempi d'uso",
"collocations": "Collocazioni",
"loadingDefinition": "Caricamento definizione...",
"generatingCollocations": "Generazione collocazioni...",
"generatingExamples": "Generazione esempi...",
"clickWordHint": "Clicca sulla parola per vederne la definizione"
},
"Theme": {
"toggle": "Cambia tema",
"light": "Chiaro",
"dark": "Scuro",
"system": "Sistema"
},
"Locale": {
"switch": "Cambia lingua",
"en": "English",
"it": "Italiano",
"ru": "Русский"
},
"Languages": {
"en": "Inglese",
"it": "Italiano",
"ru": "Russo"
},
"Time": {
"now": "Adesso",
"minutes": "{count, plural, one {# minuto fa} other {# minuti fa}}",
"hours": "{count, plural, one {# ora fa} other {# ore fa}}",
"yesterday": "Ieri",
"days": "{count, plural, one {# giorno fa} other {# giorni fa}}",
"month": "Un mese fa",
"months": "{count, plural, one {# mese fa} other {# mesi fa}}",
"year": "Un anno fa",
"moreThanYear": "Più di un anno fa"
},
"ApiErrors": {
"network": "Impossibile raggiungere il server Fancy. Controlla la connessione.",
"auth": "Accedi per usare questa funzione.",
"quota": "Fancy ha esaurito i token per questo mese",
"not-found": "Nessun risultato trovato",
"server": "Richiesta fallita. Riprova più tardi."
},
"Header": {
"login": "Accedi",
"logout": "Esci",
"collections": "Collezioni"
},
"OAuth": {
"title": "Accesso non riuscito",
"tryAgain": "Riprova",
"auth_failed": "L'accesso non è stato completato.",
"state_mismatch": "La richiesta di accesso non corrisponde. Riprova.",
"token_exchange_failed": "Non è stato possibile verificare la tua identità.",
"session_failed": "Non è stato possibile creare una sessione."
},
"Definition": {
"loading": "Caricamento definizione...",
"notFound": "Non abbiamo una definizione per questa parola",
"synonyms": "Sinonimi",
"antonyms": "Contrari",
"otherDefinitions": "({count, plural, one {Ha # altra definizione} other {Ha # altre definizioni}})"
},
"Collocations": {
"title": "Collocazioni",
"loading": "Generazione collocazioni...",
"notFound": "Nessuna collocazione trovata per questa parola",
"failed": "Generazione non riuscita"
},
"Examples": {
"title": "Esempi d'uso",
"loading": "Generazione esempi...",
"notFound": "Nessun esempio trovato per questa parola",
"failed": "Generazione non riuscita"
},
"Properties": {
"title": "Proprietà",
"details": "Dettagli traduzione",
"translate": "Traduzione",
"definition": "Definizione",
"examples": "Esempi",
"collocations": "Collocazioni",
"usage": "Utilizzo",
"usageUnavailable": "Utilizzo non disponibile",
"loadingUsage": "Caricamento utilizzo...",
"deeplCharacters": "Caratteri DeepL",
"deeplUnavailable": "Utilizzo DeepL non disponibile",
"aiTokens": "Token AI",
"requestsThisMonth": "{count, plural, one {# richiesta questo mese} other {# richieste questo mese}}"
},
"Collections": {
"title": "Collezioni",
"create": "Nuova collezione",
"createTitle": "Crea collezione",
"nameLabel": "Nome",
"namePlaceholder": "La mia collezione",
"languageLabel": "Lingua",
"createFailed": "Impossibile creare la collezione. Riprova.",
"empty": "Nessuna collezione. Creane una!",
"noWords": "Non ci sono ancora parole. Aggiungine una!",
"noSearchResults": "Nessuna parola corrisponde alla tua ricerca"
},
"CollectionMenu": {
"title": "Proprietà",
"nameLabel": "Nome",
"namePlaceholder": "La mia collezione",
"ownedBy": "Proprietario",
"language": "Lingua",
"wordCount": "Parole",
"lastUpdate": "Ultimo aggiornamento",
"created": "Creato",
"delete": "Elimina collezione",
"autoTitle": "Questa collezione è generata automaticamente",
"autoDescription": "È generata e aggiornata dal sistema. Non puoi modificarla o eliminarla.",
"deleteFailed": "Impossibile eliminare la collezione. Riprova.",
"updateFailed": "Impossibile aggiornare la collezione. Riprova."
},
"CollectionsList": {
"trigger": "Aggiungi a una collezione",
"dialogTitle": "Aggiungi \"{word}\" a una collezione",
"empty": "Non hai ancora creato collezioni in questa lingua.",
"addAction": "Aggiungi",
"removeAction": "Rimuovi",
"loadFailed": "Impossibile caricare le tue collezioni",
"notFound": "Non ancora salvata in nessuna collezione",
"toggleFailed": "Impossibile aggiornare questa collezione, riprova",
"showCollections": "In {count, plural, =0 {nessuna collezione} one {# collezione} other {# collezioni}}",
"expand": "Mostra collezioni",
"collapse": "Nascondi collezioni"
}
}
+164
View File
@@ -0,0 +1,164 @@
{
"Common": {
"cancel": "Отмена",
"create": "Создать",
"update": "Обновить",
"loading": "Загрузка...",
"somethingWrong": "Что-то пошло не так",
"seeAll": "Смотреть все",
"word": "слово",
"words": "слов",
"updated": "Обновлено",
"andMore": "И ещё {count}",
"showLess": "Свернуть",
"showMore": "Показать ещё {count}",
"copy": "Копировать",
"copied": "Скопировано",
"provider": "Провайдер",
"cache": "Кэш",
"source": "Источник",
"model": "Модель",
"generated": "Сгенерировано",
"fetched": "Получено",
"dash": "—",
"close": "Закрыть",
"search": "Поиск...",
"history": "История"
},
"App": {
"title": "Fancy"
},
"Home": {
"sourcePlaceholder": "Начните писать",
"translatedPlaceholder": "Перевод появится здесь",
"definition": "Определение",
"usageExamples": "Примеры использования",
"collocations": "Словосочетания",
"loadingDefinition": "Загрузка определения...",
"generatingCollocations": "Генерация словосочетаний...",
"generatingExamples": "Генерация примеров...",
"clickWordHint": "Нажмите на слово, чтобы увидеть определение"
},
"Theme": {
"toggle": "Переключить тему",
"light": "Светлая",
"dark": "Тёмная",
"system": "Системная"
},
"Locale": {
"switch": "Сменить язык",
"en": "English",
"it": "Italiano",
"ru": "Русский"
},
"Languages": {
"en": "Английский",
"it": "Итальянский",
"ru": "Русский"
},
"Time": {
"now": "Сейчас",
"minutes": "{count, plural, one {# минуту назад} few {# минуты назад} many {# минут назад} other {# минут назад}}",
"hours": "{count, plural, one {# час назад} few {# часа назад} many {# часов назад} other {# часов назад}}",
"yesterday": "Вчера",
"days": "{count, plural, one {# день назад} few {# дня назад} many {# дней назад} other {# дней назад}}",
"month": "Месяц назад",
"months": "{count, plural, one {# месяц назад} few {# месяца назад} many {# месяцев назад} other {# месяцев назад}}",
"year": "Год назад",
"moreThanYear": "Больше года назад"
},
"ApiErrors": {
"network": "Не удаётся подключиться к серверу Fancy. Проверьте соединение.",
"auth": "Войдите в систему, чтобы использовать эту функцию.",
"quota": "У Fancy закончились токены на этот месяц",
"not-found": "Ничего не найдено",
"server": "Запрос не выполнен. Попробуйте позже."
},
"Header": {
"login": "Войти",
"logout": "Выйти",
"collections": "Коллекции"
},
"OAuth": {
"title": "Не удалось выполнить вход",
"tryAgain": "Попробовать снова",
"auth_failed": "Вход не был завершён.",
"state_mismatch": "Запрос на вход не совпал. Попробуйте снова.",
"token_exchange_failed": "Не удалось подтвердить вашу личность.",
"session_failed": "Не удалось создать сессию."
},
"Definition": {
"loading": "Загрузка определения...",
"notFound": "У нас нет определения для этого слова",
"synonyms": "Синонимы",
"antonyms": "Антонимы",
"otherDefinitions": "({count, plural, one {Ещё # определение} few {Ещё # определения} many {Ещё # определений} other {Ещё # определений}})"
},
"Collocations": {
"title": "Словосочетания",
"loading": "Генерация словосочетаний...",
"notFound": "Словосочетания для этого слова не найдены",
"failed": "Генерация не удалась"
},
"Examples": {
"title": "Примеры использования",
"loading": "Генерация примеров...",
"notFound": "Примеры для этого слова не найдены",
"failed": "Генерация не удалась"
},
"Properties": {
"title": "Свойства",
"details": "Детали перевода",
"translate": "Перевод",
"definition": "Определение",
"examples": "Примеры",
"collocations": "Словосочетания",
"usage": "Использование",
"usageUnavailable": "Данные об использовании недоступны",
"loadingUsage": "Загрузка данных...",
"deeplCharacters": "Символы DeepL",
"deeplUnavailable": "Данные DeepL недоступны",
"aiTokens": "Токены ИИ",
"requestsThisMonth": "{count, plural, one {# запрос в этом месяце} few {# запроса в этом месяце} many {# запросов в этом месяце} other {# запросов в этом месяце}}"
},
"Collections": {
"title": "Коллекции",
"create": "Новая коллекция",
"createTitle": "Создать коллекцию",
"nameLabel": "Название",
"namePlaceholder": "Моя коллекция",
"languageLabel": "Язык",
"createFailed": "Не удалось создать коллекцию. Попробуйте снова.",
"empty": "Коллекций пока нет. Создайте первую!",
"noWords": "Слов пока нет. Добавьте первое!",
"noSearchResults": "Ни одно слово не соответствует запросу"
},
"CollectionMenu": {
"title": "Свойства",
"nameLabel": "Название",
"namePlaceholder": "Моя коллекция",
"ownedBy": "Владелец",
"language": "Язык",
"wordCount": "Слов",
"lastUpdate": "Последнее обновление",
"created": "Создано",
"delete": "Удалить коллекцию",
"autoTitle": "Эта коллекция создана автоматически",
"autoDescription": "Она генерируется и обновляется системой. Редактирование и удаление недоступны.",
"deleteFailed": "Не удалось удалить коллекцию. Попробуйте снова.",
"updateFailed": "Не удалось обновить коллекцию. Попробуйте снова."
},
"CollectionsList": {
"trigger": "Добавить в коллекцию",
"dialogTitle": "Добавить «{word}» в коллекцию",
"empty": "Вы ещё не создали коллекции для этого языка.",
"addAction": "Добавить",
"removeAction": "Удалить",
"loadFailed": "Не удалось загрузить ваши коллекции",
"notFound": "Пока не сохранено ни в одной коллекции",
"toggleFailed": "Не удалось обновить коллекцию, попробуйте снова",
"showCollections": "{count, plural, =0 {Нет коллекций} one {В # коллекции} few {В # коллекциях} many {В # коллекциях} other {В # коллекциях}}",
"expand": "Показать коллекции",
"collapse": "Скрыть коллекции"
}
}
+16
View File
@@ -0,0 +1,16 @@
import type { NextConfig } from "next";
import createNextIntlPlugin from "next-intl/plugin";
const nextConfig: NextConfig = {
images: {
remotePatterns: [
{
protocol: "https",
hostname: "upload.wikimedia.org",
},
],
},
};
const withNextIntl = createNextIntlPlugin();
export default withNextIntl(nextConfig);
+45
View File
@@ -0,0 +1,45 @@
{
"name": "translator",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "eslint"
},
"dependencies": {
"@base-ui/react": "^1.7.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cn": "^0.2.6",
"lucide-react": "^1.33.0",
"next": "16.3.2",
"next-intl": "^4.13.7",
"next-themes": "^0.4.6",
"react": "19.2.8",
"react-dom": "19.2.8",
"shadcn": "^4.19.0",
"tailwind-merge": "^3.6.0",
"tw-animate-css": "^1.4.0"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "16.3.2",
"tailwindcss": "^4",
"typescript": "^5"
},
"packageManager": "[email protected]",
"ignoreScripts": [
"sharp",
"unrs-resolver"
],
"trustedDependencies": [
"sharp",
"unrs-resolver"
]
}
+7
View File
@@ -0,0 +1,7 @@
const config = {
plugins: {
"@tailwindcss/postcss": {},
},
};
export default config;
+16
View File
@@ -0,0 +1,16 @@
"use client";
import { createContext, useContext, type ReactNode } from "react";
import type { User } from "@/types/api";
const UserContext = createContext<User | null>(null);
export function UserProvider({ user, children }: { user: User; children: ReactNode }) {
return <UserContext.Provider value={user}>{children}</UserContext.Provider>;
}
export function useUser(): User {
const user = useContext(UserContext);
if (!user) throw new Error("useUser is called outside UserProvider");
return user;
}
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="1500" height="1000" viewBox="0 0 3 2">
<rect width="1" height="2" fill="#009246"/>
<rect width="1" height="2" x="1" fill="#fff"/>
<rect width="1" height="2" x="2" fill="#ce2b37"/>
</svg>

After

Width:  |  Height:  |  Size: 273 B

+1
View File
@@ -0,0 +1 @@
<?xml version="1.0" encoding="UTF-8"?><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 9 6" width="900" height="600"><rect fill="#fff" width="9" height="3"/><rect fill="#d52b1e" y="3" width="9" height="3"/><rect fill="#0039a6" y="2" width="9" height="2"/></svg>

After

Width:  |  Height:  |  Size: 265 B

+16
View File
@@ -0,0 +1,16 @@
<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 60 30" width="1200" height="600">
<clipPath id="s">
<path d="M0,0 v30 h60 v-30 z"/>
</clipPath>
<clipPath id="t">
<path d="M30,15 h30 v15 z v15 h-30 z h-30 v-15 z v-15 h30 z"/>
</clipPath>
<g clip-path="url(#s)">
<path d="M0,0 v30 h60 v-30 z" fill="#012169"/>
<path d="M0,0 L60,30 M60,0 L0,30" stroke="#fff" stroke-width="6"/>
<path d="M0,0 L60,30 M60,0 L0,30" clip-path="url(#t)" stroke="#C8102E" stroke-width="4"/>
<path d="M30,0 v30 M0,15 h60" stroke="#fff" stroke-width="10"/>
<path d="M30,0 v30 M0,15 h60" stroke="#C8102E" stroke-width="6"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 641 B

+34
View File
@@ -0,0 +1,34 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts"
],
"exclude": ["node_modules"]
}
+132
View File
@@ -0,0 +1,132 @@
export const LANGUAGE_CODES = ["en", "it", "ru"] as const;
export type Language = (typeof LANGUAGE_CODES)[number];
export type Source = "provider" | "cache";
export const PARTS_OF_SPEECH = [
"noun",
"verb",
"adjective",
"adverb",
"pronoun",
] as const;
export type PartOfSpeech = (typeof PARTS_OF_SPEECH)[number] | (string & {});
export function isLanguage(value: string): value is Language {
return (LANGUAGE_CODES as readonly string[]).includes(value);
}
export function parseLanguage(value: string): Language | null {
const normalized = value.trim().toLowerCase();
return isLanguage(normalized) ? normalized : null;
}
export interface Form {
word: string;
tags?: string[];
}
export interface Quote {
text: string;
reference: string;
}
export interface Sense {
definition: string;
tags?: string[];
examples?: string[];
quotes?: Quote[];
synonyms?: string[];
antonyms?: string[];
}
export interface Entry {
language: Language;
partOfSpeech: PartOfSpeech;
ipa?: string;
forms?: Form[];
senses: Sense[];
synonyms?: string[];
antonyms?: string[];
}
export interface TranslationResult {
source_text: string;
source_lang: Language;
target_lang: Language;
translations: string[];
provider: string;
model?: string;
source: Source;
generated_at?: string;
}
export interface DictionaryResult {
word: string;
entries: Entry[];
provider: string;
model?: string;
source: Source;
generated_at?: string;
}
export interface CollocationsResult {
word: string;
lang: Language;
provider: string;
model?: string;
source: Source;
collocations: string[];
generated_at?: string;
}
export interface ExamplesResult {
word: string;
lang: Language;
provider: string;
model?: string;
source: Source;
examples: string[];
generated_at?: string;
}
export interface DeepLUsage {
character_count: number;
character_limit: number;
}
export interface AIUsage {
requests: number;
tokens: number;
token_limit: number;
}
export interface UsageResult {
deepl?: DeepLUsage;
ai: AIUsage;
}
export type CollectionType = "auto" | "user";
export interface CollectionResult {
id: string;
name: string;
lang: Language;
userId: string;
words: string[];
type: CollectionType;
updated_at: string;
created_at: string;
}
export type Fetched<T> = T & { fetched_at: string };
export interface User {
id: string;
email: string;
first_name: string;
second_name: string;
created_at: string;
}
+7
View File
@@ -0,0 +1,7 @@
import type { Language } from "@/types/api";
export interface UiLanguage {
id: Language;
autonym: string;
flag: string;
}