From 4c42b5aa1d6198ef855eb18653905a9d59264092 Mon Sep 17 00:00:00 2001 From: Ivan Rezchikov Date: Sat, 11 Jul 2026 21:21:38 +0300 Subject: [PATCH] prod --- .gitignore | 6 + AGENTS.md | 5 - CLAUDE.md | 1 - README.md | 36 ---- app/[type]/[slug]/edit/page.tsx | 17 ++ app/[type]/[slug]/page.tsx | 85 ++++++++- app/account/citizenship/apply/form.tsx | 53 +++++- .../citizenship/apply/image-upload-field.tsx | 137 -------------- app/account/citizenship/apply/page.tsx | 9 + app/account/citizenship/page.tsx | 9 + app/account/citizenship/review/page.tsx | 9 + app/account/page.tsx | 9 + app/create/page.tsx | 9 + app/news/page.tsx | 3 + components/editor.tsx | 168 ++++++++++++------ lib/citizenship/actions.ts | 4 +- lib/image.ts | 18 +- lib/pages/actions.ts | 27 +++ lib/pages/repository.ts | 18 ++ next.config.ts | 6 +- 20 files changed, 369 insertions(+), 260 deletions(-) delete mode 100644 AGENTS.md delete mode 100644 CLAUDE.md delete mode 100644 README.md delete mode 100644 app/account/citizenship/apply/image-upload-field.tsx diff --git a/.gitignore b/.gitignore index 5ef6a52..6e0f87c 100644 --- a/.gitignore +++ b/.gitignore @@ -33,9 +33,15 @@ yarn-error.log* # env files (can opt-in for committing if needed) .env* +# dev notes +todo + # vercel .vercel # typescript *.tsbuildinfo next-env.d.ts + +/lib/generated/prisma +.prisma/ diff --git a/AGENTS.md b/AGENTS.md deleted file mode 100644 index 8bd0e39..0000000 --- a/AGENTS.md +++ /dev/null @@ -1,5 +0,0 @@ - -# 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. - diff --git a/CLAUDE.md b/CLAUDE.md deleted file mode 100644 index 43c994c..0000000 --- a/CLAUDE.md +++ /dev/null @@ -1 +0,0 @@ -@AGENTS.md diff --git a/README.md b/README.md deleted file mode 100644 index e215bc4..0000000 --- a/README.md +++ /dev/null @@ -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. diff --git a/app/[type]/[slug]/edit/page.tsx b/app/[type]/[slug]/edit/page.tsx index edbacfb..4907fcd 100644 --- a/app/[type]/[slug]/edit/page.tsx +++ b/app/[type]/[slug]/edit/page.tsx @@ -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 { + 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(); diff --git a/app/[type]/[slug]/page.tsx b/app/[type]/[slug]/page.tsx index 92c9755..179cf0e 100644 --- a/app/[type]/[slug]/page.tsx +++ b/app/[type]/[slug]/page.tsx @@ -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 { + 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 { + 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 (
- {b.caption u.id === page.createdBy) ?? null; @@ -196,7 +271,7 @@ export default async function Page({ params }: { params: Promise<{ type: string; It can be seen only by administrators. Make any edits to make it visible again. )} - {blocks.map((block) => ( + {resolvedBlocks.map((block) => ( ))} diff --git a/app/account/citizenship/apply/form.tsx b/app/account/citizenship/apply/form.tsx index 8c015c9..bc37402 100644 --- a/app/account/citizenship/apply/form.tsx +++ b/app/account/citizenship/apply/form.tsx @@ -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(""); const [state, formAction, isPending] = useActionState(submitCitizenshipApplication, initialFormState); const [isEuResident, setIsEuResident] = useState(null); + const [profileProcessing, setProfileProcessing] = useState(false); + const profileInputRef = useRef(null); + const signatureInputRef = useRef(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 (
@@ -287,22 +322,26 @@ export function CitizenshipApplicationForm({ firstName, secondName, sex, birthDa Images Provide your profile image and your signature for your identity document. - + + - diff --git a/app/account/citizenship/apply/image-upload-field.tsx b/app/account/citizenship/apply/image-upload-field.tsx deleted file mode 100644 index d856c1e..0000000 --- a/app/account/citizenship/apply/image-upload-field.tsx +++ /dev/null @@ -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(null); - const [previewUrl, setPreviewUrl] = useState(null); - const [fileInfo, setFileInfo] = useState<{ name: string; size: number } | null>(null); - const [clientError, setClientError] = useState(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) { - 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 ( - - {label} -
-
- {isProcessing ? ( - - ) : previewUrl ? ( - - ) : ( - - )} -
- -
- - {fileInfo && ( -
- - {fileInfo.name} ({formatFileSize(fileInfo.size)}) - - -
- )} - {description} -
-
- {displayedError && {displayedError}} -
- ); -} \ No newline at end of file diff --git a/app/account/citizenship/apply/page.tsx b/app/account/citizenship/apply/page.tsx index ac566cb..98144a8 100644 --- a/app/account/citizenship/apply/page.tsx +++ b/app/account/citizenship/apply/page.tsx @@ -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(); diff --git a/app/account/citizenship/page.tsx b/app/account/citizenship/page.tsx index 11a337d..ff63f38 100644 --- a/app/account/citizenship/page.tsx +++ b/app/account/citizenship/page.tsx @@ -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() diff --git a/app/account/citizenship/review/page.tsx b/app/account/citizenship/review/page.tsx index 78fa6c5..f2aabc7 100644 --- a/app/account/citizenship/review/page.tsx +++ b/app/account/citizenship/review/page.tsx @@ -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(); diff --git a/app/account/page.tsx b/app/account/page.tsx index 75e0c4e..98d1a38 100644 --- a/app/account/page.tsx +++ b/app/account/page.tsx @@ -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("/"); diff --git a/app/create/page.tsx b/app/create/page.tsx index 4fca172..2319b10 100644 --- a/app/create/page.tsx +++ b/app/create/page.tsx @@ -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(); diff --git a/app/news/page.tsx b/app/news/page.tsx index a6c3118..ca5db87 100644 --- a/app/news/page.tsx +++ b/app/news/page.tsx @@ -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"); diff --git a/components/editor.tsx b/components/editor.tsx index 3bc7f63..113fdff 100644 --- a/components/editor.tsx +++ b/components/editor.tsx @@ -7,7 +7,7 @@ import { Button } from "@/components/ui/button"; import { Field, FieldError, FieldGroup, FieldLabel, FieldSet } from "@/components/ui/field"; import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from "@/components/ui/input-group"; 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 { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"; import { cn } from "@/lib/utils"; @@ -15,6 +15,9 @@ import { Input } from "./ui/input"; import { Separator } from "./ui/separator"; import { Alert } from "./ui/alert"; 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 = { title: string; @@ -67,8 +70,8 @@ export default function Editor({ page, initialBlocks = [], onChange, errors }: E const [tags, setTags] = useState(meta.tags ?? []); const [tagInput, setTagInput] = useState(""); const [blocks, setBlocks] = useState(initialBlocks); - const [dragIndex, setDragIndex] = useState(null); - const [dropIndex, setDropIndex] = useState(null); + const [previewUrls, setPreviewUrls] = useState>(new Map()); + const previewCacheRef = useRef>(new Map()); useEffect(() => { onChange({ @@ -81,6 +84,37 @@ export default function Editor({ page, initialBlocks = [], onChange, errors }: E }); }, [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() { const trimmed = tagInput.trim(); if (!trimmed || tags.includes(trimmed)) return; @@ -108,6 +142,12 @@ export default function Editor({ page, initialBlocks = [], onChange, errors }: E function removeBlock(id: string) { 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"]) { @@ -121,19 +161,14 @@ export default function Editor({ page, initialBlocks = [], onChange, errors }: E setBlocks(updated.map((b, i) => ({ ...b, position: i }))); } - function handleDragStart(index: number) { - setDragIndex(index); + function moveBlockUp(index: number) { + if (index === 0) return; + moveBlock(index, index - 1); } - function handleDragOver(e: React.DragEvent, index: number) { - e.preventDefault(); - setDropIndex(index); - } - - function handleDrop(index: number) { - if (dragIndex !== null && dragIndex !== index) moveBlock(dragIndex, index); - setDragIndex(null); - setDropIndex(null); + function moveBlockDown(index: number) { + if (index === blocks.length - 1) return; + moveBlock(index, index + 1); } return ( @@ -226,27 +261,26 @@ export default function Editor({ page, initialBlocks = [], onChange, errors }: E )}
{blocks.map((block, index) => ( -
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" - )} - > +
- updateBlock(block.id, content)} /> + updateBlock(block.id, content)} + previewUrls={previewUrls} + onPreviewReady={(id, url) => { + previewCacheRef.current.set(id, url); + setPreviewUrls((prev) => new Map(prev).set(id, url)); + }} + />
-
- - +
@@ -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; onPreviewReady?: (id: string, url: string) => void }) { switch (block.type) { case "PARAGRAPH": return ( @@ -363,31 +397,12 @@ function BlockInput({ block, onChange }: { block: Block; onChange: (c: Block["co case "IMAGE": return ( -
- onChange({ type: "IMAGE", url: e.target.value })} - /> - {(block.content as any).url && ( -
- {/* eslint-disable-next-line @next/next/no-img-element */} - preview { (e.target as HTMLImageElement).style.display = "none"; }} - /> -
- )} - onChange({ type: "IMAGE", url: (block.content as any).url ?? "", caption: e.target.value })} - /> -
+ ); 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 ( + onChange({ type: "IMAGE", url: content.url, caption })} + /> + ); +} + function AutoResizeTextarea({ value, onChange, className, placeholder }: { value: string; onChange: (e: React.ChangeEvent) => void; className?: string; placeholder?: string }) { const ref = useRef(null); diff --git a/lib/citizenship/actions.ts b/lib/citizenship/actions.ts index 1806f08..ebbf8a4 100644 --- a/lib/citizenship/actions.ts +++ b/lib/citizenship/actions.ts @@ -74,11 +74,11 @@ export const submitCitizenshipApplication = formAction(citizenshipApplicationSch let signatureKey: string | undefined; try { - const profileKey = await uploadImage(profile, "citizenship/profiles", { + profileKey = await uploadImage(profile, "citizenship/profiles", { 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", }); diff --git a/lib/image.ts b/lib/image.ts index d9f34ba..8a46b08 100644 --- a/lib/image.ts +++ b/lib/image.ts @@ -8,13 +8,13 @@ const BUCKET = "uploads"; const MAX_FILE_SIZE = 5 * 1024 * 1024; 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 { +export async function uploadImage(file: File, directory: string, options: { maxWidth?: number; maxHeight?: number; fit?: "inside" | "cover" }): Promise { 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"); const input = Buffer.from(await file.arrayBuffer()); - let image = sharp(input, { + const image = sharp(input, { failOn: "error", 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"); } + const resizeOptions: Parameters[0] = { + fit: options.fit ?? "inside", + withoutEnlargement: true, + }; + if (options.maxWidth) resizeOptions.width = options.maxWidth; + if (options.maxHeight) resizeOptions.height = options.maxHeight; + const output = await image .rotate() - .resize({ - width: options.maxWidth, - height: options.maxHeight, - fit: options.fit ?? "inside", - withoutEnlargement: true, - }) + .resize(resizeOptions) .webp({ quality: 80, effort: 4 }) .toBuffer(); diff --git a/lib/pages/actions.ts b/lib/pages/actions.ts index cea6fd7..65d01e6 100644 --- a/lib/pages/actions.ts +++ b/lib/pages/actions.ts @@ -9,6 +9,8 @@ import { validatePage } from "./validation"; import { requireAdmin } from "../user/require"; import { runAction } from "../run-action"; import type { ActionResult } from "../action-result"; +import { uploadImage, removeImage, getImageUrl } from "../image"; +import { getBlocksByPageId } from "./repository"; export async function savePageAction(params: { 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 { return runAction(async () => { 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); revalidatePath(`/${type.toLowerCase()}`); }); } + +export async function uploadPageImage(file: File): Promise { + await requireAdmin(); + return uploadImage(file, "pages/images", { maxHeight: 800 }); +} + +export async function removePageImages(keys: string[]): Promise { + await requireAdmin(); + await Promise.allSettled(keys.map(removeImage)); +} + +export async function getImagePreviewUrl(key: string): Promise { + return getImageUrl(key); +} diff --git a/lib/pages/repository.ts b/lib/pages/repository.ts index 2814654..a06f3ad 100644 --- a/lib/pages/repository.ts +++ b/lib/pages/repository.ts @@ -2,6 +2,7 @@ import { getCurrentUser } from "../user"; import type { Block, Page, PageMeta, PagePublic, PageStatus, PageType } from "./types"; import { prisma } from "../prisma"; import { Prisma } from "@/lib/generated/prisma/client"; +import { removeImage } from "../image"; const publicPageSelect = { id: true, @@ -86,6 +87,19 @@ export async function updatePage( const currentPage = await prisma.page.findUnique({ where: { id }, select: { status: true } }); 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({ where: { id }, data: { @@ -114,6 +128,10 @@ export async function updatePage( : []), ]); + if (keysToRemove.length > 0) { + await Promise.allSettled(keysToRemove.map(removeImage)); + } + return page; } diff --git a/next.config.ts b/next.config.ts index 879da93..3ce0f61 100644 --- a/next.config.ts +++ b/next.config.ts @@ -1,10 +1,14 @@ 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 = { images: { remotePatterns: [ { - hostname: "**", + hostname: minioHost, + ...(minioPort ? { port: minioPort } : {}), }, ], },