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
@@ -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}
/>
);
}