This commit is contained in:
Ivan Rezchikov
2026-07-11 21:21:38 +03:00
parent 18161f4604
commit 4c42b5aa1d
20 changed files with 369 additions and 260 deletions
+17
View File
@@ -3,6 +3,23 @@ import { getCurrentUser } from "@/lib/user";
import { redirect, notFound } from "next/navigation";
import { PAGE_TYPES, PageType } from "@/lib/pages/types";
import EditPageClient from "./client";
import { Metadata } from "next";
export async function generateMetadata({ params }: { params: Promise<{ type: string; slug: string }>}): Promise<Metadata> {
const { type, slug } = await params;
const pageType = type.toUpperCase() as PageType;
const page = await getPageBySlug(slug, pageType);
return {
title: page ? `Edit «${page.title}» page` : "Edit page",
robots: {
index: false,
follow: false,
},
};
}
export default async function EditPage({ params }: { params: Promise<{ type: string; slug: string }> }) {
const user = await getCurrentUser();
+80 -5
View File
@@ -1,5 +1,3 @@
import Header from "@/components/header";
import Footer from "@/components/footer";
import { getPageBySlug, getBlocksByPageId } from "@/lib/pages/repository";
import { getCurrentUser, getUsers } from "@/lib/user";
import { notFound } from "next/navigation";
@@ -14,7 +12,83 @@ import { ArchiveButton } from "./archive-button";
import { PinToggleButton } from "./pin-toggle-button";
import { getNavLinkByPageId } from "@/lib/navlinks/repository";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import Image from "next/image";
import { Metadata } from "next";
import { getImageUrl } from "@/lib/image";
function makeDescription(text?: string, maxLength = 160) {
if (!text) return undefined;
const normalized = text.replace(/\s+/g, " ").trim();
if (normalized.length <= maxLength) {
return normalized;
}
const cut = normalized.lastIndexOf(" ", maxLength);
return (cut > 0 ? normalized.slice(0, cut) : normalized.slice(0, maxLength)) + "…";
}
async function resolveBlockImageUrls(blocks: Block[]): Promise<Block[]> {
return Promise.all(
blocks.map(async (block) => {
if (block.type !== "IMAGE") return block;
const content = block.content as { type: "IMAGE"; url: string; caption?: string };
if (!content.url) return block;
try {
const presignedUrl = await getImageUrl(content.url);
return { ...block, content: { ...content, url: presignedUrl } };
} catch {
return block;
}
})
);
}
export async function generateMetadata({ params }: { params: Promise<{ type: string; slug: string }>}): Promise<Metadata> {
const { type, slug } = await params;
const pageType = type.toUpperCase() as PageType;
if (!PAGE_TYPES.includes(pageType)) {
return {};
}
const page = await getPageBySlug(slug, pageType);
if (!page) {
return {};
}
const blocks = await getBlocksByPageId(page.id);
const resolvedBlocksForMeta = await resolveBlockImageUrls(blocks);
const firstParagraph = resolvedBlocksForMeta.find(
(b): b is Block & { content: { type: "PARAGRAPH"; text: string } } =>
b.content.type === "PARAGRAPH"
)?.content.text;
const firstImage = resolvedBlocksForMeta.find(
(b): b is Block & { content: { type: "IMAGE"; url: string } } =>
b.content.type === "IMAGE"
)?.content.url;
const description = makeDescription(firstParagraph);
return {
title: page.title,
description,
openGraph: {
title: page.title,
description,
images: firstImage ? [{ url: firstImage }] : undefined,
},
twitter: {
card: firstImage ? "summary_large_image" : "summary",
title: page.title,
description,
images: firstImage ? [firstImage] : undefined,
},
};
}
function BlockRenderer({ block }: { block: Block }) {
const b = block.content;
@@ -63,7 +137,7 @@ function BlockRenderer({ block }: { block: Block }) {
case "IMAGE":
return (
<figure className="flex flex-col gap-2">
<Image
<img
src={b.url}
alt={b.caption || "Image"}
width={1200}
@@ -146,6 +220,7 @@ export default async function Page({ params }: { params: Promise<{ type: string;
const navlink = await getNavLinkByPageId(page.id);
const blocks = page ? await getBlocksByPageId(page.id) : [];
const resolvedBlocks = await resolveBlockImageUrls(blocks);
const users = await getUsers(page.createdBy, page.updatedBy);
const createdBy = users.find((u) => u.id === page.createdBy) ?? null;
@@ -196,7 +271,7 @@ export default async function Page({ params }: { params: Promise<{ type: string;
<AlertDescription>It can be seen only by administrators. Make any edits to make it visible again.</AlertDescription>
</Alert>
)}
{blocks.map((block) => (
{resolvedBlocks.map((block) => (
<BlockRenderer key={block.id} block={block} />
))}
</div>
+46 -7
View File
@@ -1,6 +1,6 @@
"use client";
import { useActionState, useEffect, useState } from "react";
import { useActionState, useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
@@ -29,7 +29,8 @@ import { submitCitizenshipApplication } from "@/lib/citizenship/actions";
import { initialFormState } from "@/lib/form-action";
import { EYE_COLORS } from "@/lib/citizenship/types";
import { Spinner } from "@/components/ui/spinner";
import { ImageUploadField } from "./image-upload-field";
import { ImageUploader } from "@/components/image-uploader";
import { removeBackground } from "@imgly/background-removal";
type Props = {
firstName: string;
@@ -50,6 +51,9 @@ export function CitizenshipApplicationForm({ firstName, secondName, sex, birthDa
const [appType, setAppType] = useState<AppType | "">("");
const [state, formAction, isPending] = useActionState(submitCitizenshipApplication, initialFormState);
const [isEuResident, setIsEuResident] = useState<boolean | null>(null);
const [profileProcessing, setProfileProcessing] = useState(false);
const profileInputRef = useRef<HTMLInputElement>(null);
const signatureInputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
if (state.error) {
@@ -59,6 +63,37 @@ export function CitizenshipApplicationForm({ firstName, secondName, sex, birthDa
const errors = state.fieldErrors ?? {};
async function handleProfileSelect(file: File) {
setProfileProcessing(true);
try {
const resultBlob = await removeBackground(file);
const processedFile = new File([resultBlob], file.name, { type: "image/png" });
const dt = new DataTransfer();
dt.items.add(processedFile);
if (profileInputRef.current) profileInputRef.current.files = dt.files;
} catch {
const dt = new DataTransfer();
dt.items.add(file);
if (profileInputRef.current) profileInputRef.current.files = dt.files;
} finally {
setProfileProcessing(false);
}
}
function handleSignatureSelect(file: File) {
const dt = new DataTransfer();
dt.items.add(file);
if (signatureInputRef.current) signatureInputRef.current.files = dt.files;
}
function handleProfileRemove() {
if (profileInputRef.current) profileInputRef.current.value = "";
}
function handleSignatureRemove() {
if (signatureInputRef.current) signatureInputRef.current.value = "";
}
return (
<form action={formAction}>
<FieldGroup>
@@ -287,22 +322,26 @@ export function CitizenshipApplicationForm({ firstName, secondName, sex, birthDa
<FieldLegend>Images</FieldLegend>
<FieldDescription>Provide your profile image and your signature for your identity document.</FieldDescription>
<FieldGroup>
<ImageUploadField
<input ref={profileInputRef} type="hidden" name="profile" />
<input ref={signatureInputRef} type="hidden" name="signature" />
<ImageUploader
id="profile"
name="profile"
label="Profile"
description="Select a profile image to upload. The image should be taken on a neutral background."
error={errors.profile?.[0]}
previewClassName="aspect-4/5"
removeBg
onFileSelect={handleProfileSelect}
onRemove={handleProfileRemove}
isUploading={profileProcessing}
/>
<ImageUploadField
<ImageUploader
id="signature"
name="signature"
label="Signature"
description="Select a signature to upload."
error={errors.signature?.[0]}
previewClassName="aspect-5/2"
onFileSelect={handleSignatureSelect}
onRemove={handleSignatureRemove}
/>
</FieldGroup>
</FieldSet>
@@ -1,137 +0,0 @@
"use client";
import { useRef, useState } from "react";
import { Field, FieldDescription, FieldError, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { XIcon, ImageIcon } from "lucide-react";
import { cn } from "@/lib/utils";
import { removeBackground } from "@imgly/background-removal";
import { Spinner } from "@/components/ui/spinner";
type Props = {
id: string;
name: string;
label: string;
description: string;
error?: string;
previewClassName?: string;
removeBg?: boolean;
};
const MAX_SIZE = 5 * 1024 * 1024;
const ACCEPTED_TYPES = ["image/jpeg", "image/png", "image/webp"];
function formatFileSize(bytes: number): string {
return bytes < 1024 * 1024 ? `${Math.round(bytes / 1024)} KB` : `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
export function ImageUploadField({ id, name, label, description, error, previewClassName, removeBg }: Props) {
const inputRef = useRef<HTMLInputElement>(null);
const [previewUrl, setPreviewUrl] = useState<string | null>(null);
const [fileInfo, setFileInfo] = useState<{ name: string; size: number } | null>(null);
const [clientError, setClientError] = useState<string | null>(null);
const [isProcessing, setIsProcessing] = useState(false);
function reset() {
if (previewUrl) URL.revokeObjectURL(previewUrl);
setPreviewUrl(null);
setFileInfo(null);
if (inputRef.current) inputRef.current.value = "";
}
async function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
const file = e.target.files?.[0];
if (!file) { reset(); setClientError(null); return; }
if (!ACCEPTED_TYPES.includes(file.type)) {
setClientError("Only JPEG, PNG, or WEBP images are allowed.");
reset();
return;
}
if (file.size > MAX_SIZE) {
setClientError("Image must be smaller than 5MB.");
reset();
return;
}
setClientError(null);
if (!removeBg) {
if (previewUrl) URL.revokeObjectURL(previewUrl);
setPreviewUrl(URL.createObjectURL(file));
setFileInfo({ name: file.name, size: file.size });
return;
}
setIsProcessing(true);
try {
const resultBlob = await removeBackground(file);
const processedFile = new File([resultBlob], file.name, { type: "image/png" });
const dt = new DataTransfer();
dt.items.add(processedFile);
if (inputRef.current) inputRef.current.files = dt.files;
if (previewUrl) URL.revokeObjectURL(previewUrl);
setPreviewUrl(URL.createObjectURL(processedFile));
setFileInfo({ name: processedFile.name, size: processedFile.size });
} catch {
if (previewUrl) URL.revokeObjectURL(previewUrl);
setPreviewUrl(URL.createObjectURL(file));
setFileInfo({ name: file.name, size: file.size });
} finally {
setIsProcessing(false);
}
}
const displayedError = clientError ?? error;
return (
<Field data-invalid={!!displayedError}>
<FieldLabel htmlFor={id}>{label}</FieldLabel>
<div className="flex flex-col md:flex-row items-start gap-4">
<div
className={cn(
"w-28 rounded-md border border-dashed border-foreground/15 bg-muted flex items-center justify-center overflow-hidden shrink-0",
previewClassName ?? "aspect-4/5"
)}
>
{isProcessing ? (
<Spinner className="text-muted-foreground" />
) : previewUrl ? (
<img src={previewUrl} alt="" className="w-full h-full object-cover" />
) : (
<ImageIcon className="text-muted-foreground" size={24} />
)}
</div>
<div className="flex flex-col gap-1 flex-1 min-w-0">
<Input
ref={inputRef}
id={id}
name={name}
type="file"
accept="image/jpeg,image/png,image/webp"
aria-invalid={!!displayedError}
onChange={handleChange}
disabled={isProcessing}
required={!fileInfo}
/>
{fileInfo && (
<div className="flex items-center gap-2 text-sm text-muted-foreground w-full min-w-0">
<span className="flex-1 min-w-0 truncate">
{fileInfo.name} ({formatFileSize(fileInfo.size)})
</span>
<Button type="button" variant="ghost" size="icon" className="h-6 w-6" onClick={reset} disabled={isProcessing}>
<XIcon size={14} />
</Button>
</div>
)}
<FieldDescription className="mt-1">{description}</FieldDescription>
</div>
</div>
{displayedError && <FieldError>{displayedError}</FieldError>}
</Field>
);
}
+9
View File
@@ -6,6 +6,15 @@ import { getApplicationEligibility } from "@/lib/citizenship/repository";
import { prisma } from "@/lib/prisma";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { InfoIcon } from "lucide-react";
import { Metadata } from "next";
export const metadata: Metadata = {
title: "Citizenship application",
robots: {
index: false,
follow: false,
},
};
export default async function CitizenshipApplication() {
const user = await getCurrentUser();
+9
View File
@@ -6,6 +6,15 @@ import Link from "next/link";
import { getPendingApplicationsCount, getActiveCitizenship } from "@/lib/citizenship/repository";
import { HasCitizenship } from "./has-citizenship";
import { NoCitizenship } from "./no-citizenship";
import { Metadata } from "next";
export const metadata: Metadata = {
title: "Citizenship",
robots: {
index: false,
follow: false,
},
};
export default async function Citizenship() {
const user = await getCurrentUser()
+9
View File
@@ -4,6 +4,15 @@ import { redirect } from "next/navigation";
import { AccountMenu } from "../../account-menu";
import { getPendingApplications } from "@/lib/citizenship/repository";
import { getImageUrl } from "@/lib/image";
import { Metadata } from "next";
export const metadata: Metadata = {
title: "Review citizenship applications",
robots: {
index: false,
follow: false,
},
};
export default async function ReviewPage() {
const user = await getCurrentUser();
+9
View File
@@ -6,6 +6,7 @@ import { DeleteDialog } from "./delete-dialog";
import { LogoutButton } from "./logout-button";
import { UpdateButton } from "./update-button";
import { AccountMenu } from "./account-menu";
import { Metadata } from "next";
function ProfileField({ label, value }: { label: string; value: string }) {
return (
@@ -16,6 +17,14 @@ function ProfileField({ label, value }: { label: string; value: string }) {
);
}
export const metadata: Metadata = {
title: "Profile",
robots: {
index: false,
follow: false,
},
};
export default async function Account() {
const user = await getCurrentUser();
if (!user) redirect("/");
+9
View File
@@ -1,6 +1,15 @@
import { getCurrentUser } from "@/lib/user";
import { redirect } from "next/navigation";
import CreatePageClient from "./client";
import { Metadata } from "next";
export const metadata: Metadata = {
title: "Create page",
robots: {
index: false,
follow: false,
},
};
export default async function CreatePage() {
const user = await getCurrentUser();
+3
View File
@@ -3,8 +3,11 @@ import { NewsCard } from "@/components/news-card";
import { Button } from "@/components/ui/button";
import { getPages } from "@/lib/pages/repository";
import { getCurrentUser } from "@/lib/user";
import { Metadata } from "next";
import Link from "next/link";
export const metadata: Metadata = { title: "News" };
export default async function News() {
const user = await getCurrentUser();
const news = await getPages("NEWS", "PUBLISHED");