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
+6
View File
@@ -33,9 +33,15 @@ yarn-error.log*
# env files (can opt-in for committing if needed) # env files (can opt-in for committing if needed)
.env* .env*
# dev notes
todo
# vercel # vercel
.vercel .vercel
# typescript # typescript
*.tsbuildinfo *.tsbuildinfo
next-env.d.ts next-env.d.ts
/lib/generated/prisma
.prisma/
-5
View File
@@ -1,5 +0,0 @@
<!-- 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/` before writing any code. Heed deprecation notices.
<!-- END:nextjs-agent-rules -->
-1
View File
@@ -1 +0,0 @@
@AGENTS.md
-36
View File
@@ -1,36 +0,0 @@
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.
+17
View File
@@ -3,6 +3,23 @@ import { getCurrentUser } from "@/lib/user";
import { redirect, notFound } from "next/navigation"; import { redirect, notFound } from "next/navigation";
import { PAGE_TYPES, PageType } from "@/lib/pages/types"; import { PAGE_TYPES, PageType } from "@/lib/pages/types";
import EditPageClient from "./client"; 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 }> }) { export default async function EditPage({ params }: { params: Promise<{ type: string; slug: string }> }) {
const user = await getCurrentUser(); 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 { getPageBySlug, getBlocksByPageId } from "@/lib/pages/repository";
import { getCurrentUser, getUsers } from "@/lib/user"; import { getCurrentUser, getUsers } from "@/lib/user";
import { notFound } from "next/navigation"; import { notFound } from "next/navigation";
@@ -14,7 +12,83 @@ import { ArchiveButton } from "./archive-button";
import { PinToggleButton } from "./pin-toggle-button"; import { PinToggleButton } from "./pin-toggle-button";
import { getNavLinkByPageId } from "@/lib/navlinks/repository"; import { getNavLinkByPageId } from "@/lib/navlinks/repository";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; 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 }) { function BlockRenderer({ block }: { block: Block }) {
const b = block.content; const b = block.content;
@@ -63,7 +137,7 @@ function BlockRenderer({ block }: { block: Block }) {
case "IMAGE": case "IMAGE":
return ( return (
<figure className="flex flex-col gap-2"> <figure className="flex flex-col gap-2">
<Image <img
src={b.url} src={b.url}
alt={b.caption || "Image"} alt={b.caption || "Image"}
width={1200} width={1200}
@@ -146,6 +220,7 @@ export default async function Page({ params }: { params: Promise<{ type: string;
const navlink = await getNavLinkByPageId(page.id); const navlink = await getNavLinkByPageId(page.id);
const blocks = page ? await getBlocksByPageId(page.id) : []; const blocks = page ? await getBlocksByPageId(page.id) : [];
const resolvedBlocks = await resolveBlockImageUrls(blocks);
const users = await getUsers(page.createdBy, page.updatedBy); const users = await getUsers(page.createdBy, page.updatedBy);
const createdBy = users.find((u) => u.id === page.createdBy) ?? null; 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> <AlertDescription>It can be seen only by administrators. Make any edits to make it visible again.</AlertDescription>
</Alert> </Alert>
)} )}
{blocks.map((block) => ( {resolvedBlocks.map((block) => (
<BlockRenderer key={block.id} block={block} /> <BlockRenderer key={block.id} block={block} />
))} ))}
</div> </div>
+46 -7
View File
@@ -1,6 +1,6 @@
"use client"; "use client";
import { useActionState, useEffect, useState } from "react"; import { useActionState, useEffect, useRef, useState } from "react";
import { toast } from "sonner"; import { toast } from "sonner";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { import {
@@ -29,7 +29,8 @@ import { submitCitizenshipApplication } from "@/lib/citizenship/actions";
import { initialFormState } from "@/lib/form-action"; import { initialFormState } from "@/lib/form-action";
import { EYE_COLORS } from "@/lib/citizenship/types"; import { EYE_COLORS } from "@/lib/citizenship/types";
import { Spinner } from "@/components/ui/spinner"; 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 = { type Props = {
firstName: string; firstName: string;
@@ -50,6 +51,9 @@ export function CitizenshipApplicationForm({ firstName, secondName, sex, birthDa
const [appType, setAppType] = useState<AppType | "">(""); const [appType, setAppType] = useState<AppType | "">("");
const [state, formAction, isPending] = useActionState(submitCitizenshipApplication, initialFormState); const [state, formAction, isPending] = useActionState(submitCitizenshipApplication, initialFormState);
const [isEuResident, setIsEuResident] = useState<boolean | null>(null); const [isEuResident, setIsEuResident] = useState<boolean | null>(null);
const [profileProcessing, setProfileProcessing] = useState(false);
const profileInputRef = useRef<HTMLInputElement>(null);
const signatureInputRef = useRef<HTMLInputElement>(null);
useEffect(() => { useEffect(() => {
if (state.error) { if (state.error) {
@@ -59,6 +63,37 @@ export function CitizenshipApplicationForm({ firstName, secondName, sex, birthDa
const errors = state.fieldErrors ?? {}; 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 ( return (
<form action={formAction}> <form action={formAction}>
<FieldGroup> <FieldGroup>
@@ -287,22 +322,26 @@ export function CitizenshipApplicationForm({ firstName, secondName, sex, birthDa
<FieldLegend>Images</FieldLegend> <FieldLegend>Images</FieldLegend>
<FieldDescription>Provide your profile image and your signature for your identity document.</FieldDescription> <FieldDescription>Provide your profile image and your signature for your identity document.</FieldDescription>
<FieldGroup> <FieldGroup>
<ImageUploadField <input ref={profileInputRef} type="hidden" name="profile" />
<input ref={signatureInputRef} type="hidden" name="signature" />
<ImageUploader
id="profile" id="profile"
name="profile"
label="Profile" label="Profile"
description="Select a profile image to upload. The image should be taken on a neutral background." description="Select a profile image to upload. The image should be taken on a neutral background."
error={errors.profile?.[0]} error={errors.profile?.[0]}
previewClassName="aspect-4/5" previewClassName="aspect-4/5"
removeBg onFileSelect={handleProfileSelect}
onRemove={handleProfileRemove}
isUploading={profileProcessing}
/> />
<ImageUploadField <ImageUploader
id="signature" id="signature"
name="signature"
label="Signature" label="Signature"
description="Select a signature to upload." description="Select a signature to upload."
error={errors.signature?.[0]} error={errors.signature?.[0]}
previewClassName="aspect-5/2" previewClassName="aspect-5/2"
onFileSelect={handleSignatureSelect}
onRemove={handleSignatureRemove}
/> />
</FieldGroup> </FieldGroup>
</FieldSet> </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 { prisma } from "@/lib/prisma";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { InfoIcon } from "lucide-react"; 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() { export default async function CitizenshipApplication() {
const user = await getCurrentUser(); const user = await getCurrentUser();
+9
View File
@@ -6,6 +6,15 @@ import Link from "next/link";
import { getPendingApplicationsCount, getActiveCitizenship } from "@/lib/citizenship/repository"; import { getPendingApplicationsCount, getActiveCitizenship } from "@/lib/citizenship/repository";
import { HasCitizenship } from "./has-citizenship"; import { HasCitizenship } from "./has-citizenship";
import { NoCitizenship } from "./no-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() { export default async function Citizenship() {
const user = await getCurrentUser() const user = await getCurrentUser()
+9
View File
@@ -4,6 +4,15 @@ import { redirect } from "next/navigation";
import { AccountMenu } from "../../account-menu"; import { AccountMenu } from "../../account-menu";
import { getPendingApplications } from "@/lib/citizenship/repository"; import { getPendingApplications } from "@/lib/citizenship/repository";
import { getImageUrl } from "@/lib/image"; 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() { export default async function ReviewPage() {
const user = await getCurrentUser(); const user = await getCurrentUser();
+9
View File
@@ -6,6 +6,7 @@ import { DeleteDialog } from "./delete-dialog";
import { LogoutButton } from "./logout-button"; import { LogoutButton } from "./logout-button";
import { UpdateButton } from "./update-button"; import { UpdateButton } from "./update-button";
import { AccountMenu } from "./account-menu"; import { AccountMenu } from "./account-menu";
import { Metadata } from "next";
function ProfileField({ label, value }: { label: string; value: string }) { function ProfileField({ label, value }: { label: string; value: string }) {
return ( 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() { export default async function Account() {
const user = await getCurrentUser(); const user = await getCurrentUser();
if (!user) redirect("/"); if (!user) redirect("/");
+9
View File
@@ -1,6 +1,15 @@
import { getCurrentUser } from "@/lib/user"; import { getCurrentUser } from "@/lib/user";
import { redirect } from "next/navigation"; import { redirect } from "next/navigation";
import CreatePageClient from "./client"; 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() { export default async function CreatePage() {
const user = await getCurrentUser(); const user = await getCurrentUser();
+3
View File
@@ -3,8 +3,11 @@ import { NewsCard } from "@/components/news-card";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { getPages } from "@/lib/pages/repository"; import { getPages } from "@/lib/pages/repository";
import { getCurrentUser } from "@/lib/user"; import { getCurrentUser } from "@/lib/user";
import { Metadata } from "next";
import Link from "next/link"; import Link from "next/link";
export const metadata: Metadata = { title: "News" };
export default async function News() { export default async function News() {
const user = await getCurrentUser(); const user = await getCurrentUser();
const news = await getPages("NEWS", "PUBLISHED"); const news = await getPages("NEWS", "PUBLISHED");
+108 -56
View File
@@ -7,7 +7,7 @@ import { Button } from "@/components/ui/button";
import { Field, FieldError, FieldGroup, FieldLabel, FieldSet } from "@/components/ui/field"; import { Field, FieldError, FieldGroup, FieldLabel, FieldSet } from "@/components/ui/field";
import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from "@/components/ui/input-group"; import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from "@/components/ui/input-group";
import { Block, BlockType, Page, PageMeta, PageType } from "@/lib/pages/types"; import { Block, BlockType, Page, PageMeta, PageType } from "@/lib/pages/types";
import { Globe2Icon, PlusIcon, Trash2Icon, XIcon, GripVerticalIcon, ChevronDownIcon, ImageIcon, QuoteIcon, AlertCircleIcon, MinusIcon, ListIcon, TableIcon, TypeIcon, AlignLeftIcon, InfoIcon, DotIcon, ListOrderedIcon, LinkIcon } from "lucide-react"; import { Globe2Icon, PlusIcon, Trash2Icon, XIcon, ChevronDownIcon, ChevronUpIcon, ImageIcon, QuoteIcon, AlertCircleIcon, MinusIcon, ListIcon, TableIcon, TypeIcon, AlignLeftIcon, InfoIcon, DotIcon, ListOrderedIcon, LinkIcon } from "lucide-react";
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "./ui/select"; import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
@@ -15,6 +15,9 @@ import { Input } from "./ui/input";
import { Separator } from "./ui/separator"; import { Separator } from "./ui/separator";
import { Alert } from "./ui/alert"; import { Alert } from "./ui/alert";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { uploadPageImage, getImagePreviewUrl } from "@/lib/pages/actions";
import { ImageUploader } from "@/components/image-uploader";
import { Spinner } from "@/components/ui/spinner";
export type EditorData = { export type EditorData = {
title: string; title: string;
@@ -67,8 +70,8 @@ export default function Editor({ page, initialBlocks = [], onChange, errors }: E
const [tags, setTags] = useState<string[]>(meta.tags ?? []); const [tags, setTags] = useState<string[]>(meta.tags ?? []);
const [tagInput, setTagInput] = useState(""); const [tagInput, setTagInput] = useState("");
const [blocks, setBlocks] = useState<Block[]>(initialBlocks); const [blocks, setBlocks] = useState<Block[]>(initialBlocks);
const [dragIndex, setDragIndex] = useState<number | null>(null); const [previewUrls, setPreviewUrls] = useState<Map<string, string>>(new Map());
const [dropIndex, setDropIndex] = useState<number | null>(null); const previewCacheRef = useRef<Map<string, string>>(new Map());
useEffect(() => { useEffect(() => {
onChange({ onChange({
@@ -81,6 +84,37 @@ export default function Editor({ page, initialBlocks = [], onChange, errors }: E
}); });
}, [title, slug, location, tags, blocks]); }, [title, slug, location, tags, blocks]);
useEffect(() => {
const imageBlocks = blocks.filter(
(b) => b.type === "IMAGE" && !!(b.content as { type: string; url?: string }).url
);
const unresolved = imageBlocks.filter((b) => !previewCacheRef.current.has(b.id));
if (unresolved.length === 0) return;
let cancelled = false;
Promise.all(
unresolved.map(async (b) => {
try {
const url = await getImagePreviewUrl((b.content as { type: string; url: string }).url);
return { id: b.id, url };
} catch {
return null;
}
})
).then((results) => {
if (cancelled) return;
const newEntries = results.filter((r): r is { id: string; url: string } => r !== null);
if (newEntries.length === 0) return;
const next = new Map(previewCacheRef.current);
for (const { id, url } of newEntries) next.set(id, url);
previewCacheRef.current = next;
setPreviewUrls(new Map(next));
});
return () => { cancelled = true; };
}, [blocks]);
function addTag() { function addTag() {
const trimmed = tagInput.trim(); const trimmed = tagInput.trim();
if (!trimmed || tags.includes(trimmed)) return; if (!trimmed || tags.includes(trimmed)) return;
@@ -108,6 +142,12 @@ export default function Editor({ page, initialBlocks = [], onChange, errors }: E
function removeBlock(id: string) { function removeBlock(id: string) {
setBlocks(blocks.filter((b) => b.id !== id)); setBlocks(blocks.filter((b) => b.id !== id));
previewCacheRef.current.delete(id);
setPreviewUrls((prev) => {
const next = new Map(prev);
next.delete(id);
return next;
});
} }
function updateBlock(id: string, content: Block["content"]) { function updateBlock(id: string, content: Block["content"]) {
@@ -121,19 +161,14 @@ export default function Editor({ page, initialBlocks = [], onChange, errors }: E
setBlocks(updated.map((b, i) => ({ ...b, position: i }))); setBlocks(updated.map((b, i) => ({ ...b, position: i })));
} }
function handleDragStart(index: number) { function moveBlockUp(index: number) {
setDragIndex(index); if (index === 0) return;
moveBlock(index, index - 1);
} }
function handleDragOver(e: React.DragEvent, index: number) { function moveBlockDown(index: number) {
e.preventDefault(); if (index === blocks.length - 1) return;
setDropIndex(index); moveBlock(index, index + 1);
}
function handleDrop(index: number) {
if (dragIndex !== null && dragIndex !== index) moveBlock(dragIndex, index);
setDragIndex(null);
setDropIndex(null);
} }
return ( return (
@@ -226,25 +261,24 @@ export default function Editor({ page, initialBlocks = [], onChange, errors }: E
)} )}
<div className="flex flex-col gap-4 md:gap-6"> <div className="flex flex-col gap-4 md:gap-6">
{blocks.map((block, index) => ( {blocks.map((block, index) => (
<div <div key={block.id} className="group relative flex flex-row gap-2 md:gap-4 items-start py-1">
key={block.id}
draggable
onDragStart={() => handleDragStart(index)}
onDragOver={(e) => handleDragOver(e, index)}
onDrop={() => handleDrop(index)}
onDragEnd={() => { setDragIndex(null); setDropIndex(null); }}
className={cn(
"group relative flex flex-row gap-2 md:gap-4 items-start py-1 transition-opacity",
dragIndex === index && "opacity-30",
dropIndex === index && dragIndex !== index && "border-t-2 border-primary"
)}
>
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">
<BlockInput block={block} onChange={(content) => updateBlock(block.id, content)} /> <BlockInput
block={block}
onChange={(content) => updateBlock(block.id, content)}
previewUrls={previewUrls}
onPreviewReady={(id, url) => {
previewCacheRef.current.set(id, url);
setPreviewUrls((prev) => new Map(prev).set(id, url));
}}
/>
</div> </div>
<div className="flex flex-col gap-2 items-center opacity-0 group-hover:opacity-100 transition-opacity shrink-0"> <div className="flex flex-col gap-1 items-center opacity-0 group-hover:opacity-100 transition-opacity shrink-0">
<Button variant="ghost" className="cursor-grab active:cursor-grabbing" size="icon-sm" > <Button variant="ghost" onClick={() => moveBlockUp(index)} disabled={index === 0} size="icon-sm">
<GripVerticalIcon /> <ChevronUpIcon />
</Button>
<Button variant="ghost" onClick={() => moveBlockDown(index)} disabled={index === blocks.length - 1} size="icon-sm">
<ChevronDownIcon />
</Button> </Button>
<Button variant="ghost" onClick={() => removeBlock(block.id)} size="icon-sm"> <Button variant="ghost" onClick={() => removeBlock(block.id)} size="icon-sm">
<Trash2Icon /> <Trash2Icon />
@@ -278,7 +312,7 @@ export default function Editor({ page, initialBlocks = [], onChange, errors }: E
); );
} }
function BlockInput({ block, onChange }: { block: Block; onChange: (c: Block["content"]) => void }) { function BlockInput({ block, onChange, previewUrls, onPreviewReady }: { block: Block; onChange: (c: Block["content"]) => void; previewUrls?: Map<string, string>; onPreviewReady?: (id: string, url: string) => void }) {
switch (block.type) { switch (block.type) {
case "PARAGRAPH": case "PARAGRAPH":
return ( return (
@@ -363,31 +397,12 @@ function BlockInput({ block, onChange }: { block: Block; onChange: (c: Block["co
case "IMAGE": case "IMAGE":
return ( return (
<div className="flex flex-col gap-4"> <ImageBlock
<input block={block}
className="w-full bg-transparent outline-none text-muted-foreground placeholder:text-muted-foreground py-1.5 border-b border-dashed border-muted-foreground/30 focus:border-muted-foreground/60 transition-colors" previewUrl={previewUrls?.get(block.id)}
placeholder="https://example.com/image.jpg" onChange={onChange}
value={(block.content as any).url ?? ""} onPreviewReady={onPreviewReady!}
onChange={(e) => onChange({ type: "IMAGE", url: e.target.value })}
/> />
{(block.content as any).url && (
<div className="relative max-w-150 rounded-md overflow-hidden border bg-muted/30">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={(block.content as any).url}
alt="preview"
className="block max-w-full h-auto object-contain"
onError={(e) => { (e.target as HTMLImageElement).style.display = "none"; }}
/>
</div>
)}
<Input
className="max-w-64"
placeholder="Caption (optional)"
value={(block.content as any).caption ?? ""}
onChange={(e) => onChange({ type: "IMAGE", url: (block.content as any).url ?? "", caption: e.target.value })}
/>
</div>
); );
case "DIVIDER": case "DIVIDER":
@@ -608,6 +623,43 @@ function TableEditor({ content, onChange }: { content: { type: "TABLE"; headers:
); );
} }
function ImageBlock({ block, previewUrl, onChange, onPreviewReady }: { block: Block; previewUrl?: string; onChange: (c: Block["content"]) => void; onPreviewReady: (id: string, url: string) => void }) {
const content = block.content as { type: "IMAGE"; url: string; caption?: string };
const [isUploading, setIsUploading] = useState(false);
async function handleFileSelect(file: File) {
setIsUploading(true);
try {
const key = await uploadPageImage(file);
const url = await getImagePreviewUrl(key);
onPreviewReady(block.id, url);
onChange({ type: "IMAGE", url: key, caption: content.caption ?? "" });
} catch (e) {
console.error("Failed to upload image:", e);
} finally {
setIsUploading(false);
}
}
function handleRemove() {
onChange({ type: "IMAGE", url: "", caption: content.caption ?? "" });
}
return (
<ImageUploader
id={`image-${block.id}`}
label=""
variant="editor"
value={previewUrl}
onFileSelect={handleFileSelect}
onRemove={handleRemove}
isUploading={isUploading}
caption={content.caption}
onCaptionChange={(caption) => onChange({ type: "IMAGE", url: content.url, caption })}
/>
);
}
function AutoResizeTextarea({ value, onChange, className, placeholder }: { value: string; onChange: (e: React.ChangeEvent<HTMLTextAreaElement>) => void; className?: string; placeholder?: string }) { function AutoResizeTextarea({ value, onChange, className, placeholder }: { value: string; onChange: (e: React.ChangeEvent<HTMLTextAreaElement>) => void; className?: string; placeholder?: string }) {
const ref = useRef<HTMLTextAreaElement>(null); const ref = useRef<HTMLTextAreaElement>(null);
+2 -2
View File
@@ -74,11 +74,11 @@ export const submitCitizenshipApplication = formAction(citizenshipApplicationSch
let signatureKey: string | undefined; let signatureKey: string | undefined;
try { try {
const profileKey = await uploadImage(profile, "citizenship/profiles", { profileKey = await uploadImage(profile, "citizenship/profiles", {
maxWidth: 800, maxHeight: 1000, fit: "cover", maxWidth: 800, maxHeight: 1000, fit: "cover",
}); });
const signatureKey = await uploadImage(signature, "citizenship/signatures", { signatureKey = await uploadImage(signature, "citizenship/signatures", {
maxWidth: 1000, maxHeight: 400, fit: "inside", maxWidth: 1000, maxHeight: 400, fit: "inside",
}); });
+10 -8
View File
@@ -8,13 +8,13 @@ const BUCKET = "uploads";
const MAX_FILE_SIZE = 5 * 1024 * 1024; const MAX_FILE_SIZE = 5 * 1024 * 1024;
const ALLOWED_INPUT_FORMATS = new Set(["jpeg", "png", "webp"]); const ALLOWED_INPUT_FORMATS = new Set(["jpeg", "png", "webp"]);
export async function uploadImage(file: File, directory: string, options: { maxWidth: number; maxHeight: number; fit?: "inside" | "cover"; removeBg?: boolean }): Promise<string> { export async function uploadImage(file: File, directory: string, options: { maxWidth?: number; maxHeight?: number; fit?: "inside" | "cover" }): Promise<string> {
if (file.size === 0) throw new AppError("A file is required"); if (file.size === 0) throw new AppError("A file is required");
if (file.size > MAX_FILE_SIZE) throw new AppError("Image must be smaller than 5MB"); if (file.size > MAX_FILE_SIZE) throw new AppError("Image must be smaller than 5MB");
const input = Buffer.from(await file.arrayBuffer()); const input = Buffer.from(await file.arrayBuffer());
let image = sharp(input, { const image = sharp(input, {
failOn: "error", failOn: "error",
limitInputPixels: 30_000_000, limitInputPixels: 30_000_000,
}); });
@@ -28,14 +28,16 @@ export async function uploadImage(file: File, directory: string, options: { maxW
throw new AppError("Image is too small"); throw new AppError("Image is too small");
} }
const output = await image const resizeOptions: Parameters<typeof image.resize>[0] = {
.rotate()
.resize({
width: options.maxWidth,
height: options.maxHeight,
fit: options.fit ?? "inside", fit: options.fit ?? "inside",
withoutEnlargement: true, withoutEnlargement: true,
}) };
if (options.maxWidth) resizeOptions.width = options.maxWidth;
if (options.maxHeight) resizeOptions.height = options.maxHeight;
const output = await image
.rotate()
.resize(resizeOptions)
.webp({ quality: 80, effort: 4 }) .webp({ quality: 80, effort: 4 })
.toBuffer(); .toBuffer();
+27
View File
@@ -9,6 +9,8 @@ import { validatePage } from "./validation";
import { requireAdmin } from "../user/require"; import { requireAdmin } from "../user/require";
import { runAction } from "../run-action"; import { runAction } from "../run-action";
import type { ActionResult } from "../action-result"; import type { ActionResult } from "../action-result";
import { uploadImage, removeImage, getImageUrl } from "../image";
import { getBlocksByPageId } from "./repository";
export async function savePageAction(params: { export async function savePageAction(params: {
id: string | null, id: string | null,
@@ -52,7 +54,32 @@ export async function archivePageAction(id: string, slug: string, type: PageType
export async function deletePageAction(id: string, type: PageType): Promise<ActionResult> { export async function deletePageAction(id: string, type: PageType): Promise<ActionResult> {
return runAction(async () => { return runAction(async () => {
await requireAdmin(); await requireAdmin();
const blocks = await getBlocksByPageId(id);
const imageKeys = blocks
.filter((b) => b.type === "IMAGE")
.map((b) => (b.content as { type: "IMAGE"; url: string }).url)
.filter(Boolean);
if (imageKeys.length) {
await Promise.allSettled(imageKeys.map(removeImage));
}
await deletePage(id); await deletePage(id);
revalidatePath(`/${type.toLowerCase()}`); revalidatePath(`/${type.toLowerCase()}`);
}); });
} }
export async function uploadPageImage(file: File): Promise<string> {
await requireAdmin();
return uploadImage(file, "pages/images", { maxHeight: 800 });
}
export async function removePageImages(keys: string[]): Promise<void> {
await requireAdmin();
await Promise.allSettled(keys.map(removeImage));
}
export async function getImagePreviewUrl(key: string): Promise<string> {
return getImageUrl(key);
}
+18
View File
@@ -2,6 +2,7 @@ import { getCurrentUser } from "../user";
import type { Block, Page, PageMeta, PagePublic, PageStatus, PageType } from "./types"; import type { Block, Page, PageMeta, PagePublic, PageStatus, PageType } from "./types";
import { prisma } from "../prisma"; import { prisma } from "../prisma";
import { Prisma } from "@/lib/generated/prisma/client"; import { Prisma } from "@/lib/generated/prisma/client";
import { removeImage } from "../image";
const publicPageSelect = { const publicPageSelect = {
id: true, id: true,
@@ -86,6 +87,19 @@ export async function updatePage(
const currentPage = await prisma.page.findUnique({ where: { id }, select: { status: true } }); const currentPage = await prisma.page.findUnique({ where: { id }, select: { status: true } });
const isNewlyPublished = status === "PUBLISHED" && currentPage?.status !== "PUBLISHED"; const isNewlyPublished = status === "PUBLISHED" && currentPage?.status !== "PUBLISHED";
const oldImageBlocks = await prisma.block.findMany({
where: { pageId: id, type: "IMAGE" },
select: { content: true },
});
const oldImageKeys = oldImageBlocks
.map((b) => (b.content as { type: "IMAGE"; url: string }).url)
.filter(Boolean);
const newImageKeys = blocks
.filter((b) => b.type === "IMAGE")
.map((b) => (b.content as { type: "IMAGE"; url: string }).url)
.filter(Boolean);
const keysToRemove = oldImageKeys.filter((k) => !newImageKeys.includes(k));
const page = await prisma.page.update({ const page = await prisma.page.update({
where: { id }, where: { id },
data: { data: {
@@ -114,6 +128,10 @@ export async function updatePage(
: []), : []),
]); ]);
if (keysToRemove.length > 0) {
await Promise.allSettled(keysToRemove.map(removeImage));
}
return page; return page;
} }
+5 -1
View File
@@ -1,10 +1,14 @@
import type { NextConfig } from "next"; import type { NextConfig } from "next";
const minioHost = process.env.MINIO_PUBLIC_URL ? new URL(process.env.MINIO_PUBLIC_URL).hostname : "localhost";
const minioPort = process.env.MINIO_PUBLIC_URL ? new URL(process.env.MINIO_PUBLIC_URL).port : undefined;
const nextConfig: NextConfig = { const nextConfig: NextConfig = {
images: { images: {
remotePatterns: [ remotePatterns: [
{ {
hostname: "**", hostname: minioHost,
...(minioPort ? { port: minioPort } : {}),
}, },
], ],
}, },