feat: pages

This commit is contained in:
Ivan Rezchikov
2026-06-22 16:44:06 +03:00
parent 48656b562a
commit 64923cd1b2
20 changed files with 1038 additions and 283 deletions
+3 -2
View File
@@ -5,8 +5,9 @@ import { Button } from "@/components/ui/button";
import { ArchiveIcon } from "lucide-react"; import { ArchiveIcon } from "lucide-react";
import { Spinner } from "@/components/ui/spinner"; import { Spinner } from "@/components/ui/spinner";
import { archivePageAction } from "@/lib/pages/actions"; import { archivePageAction } from "@/lib/pages/actions";
import { PageType } from "@/lib/pages/types";
export function ArchiveButton({ pageId }: { pageId: string }) { export function ArchiveButton({ pageId, slug, type }: { pageId: string, slug: string, type: PageType }) {
const [isPending, startTransition] = useTransition(); const [isPending, startTransition] = useTransition();
return ( return (
@@ -14,7 +15,7 @@ export function ArchiveButton({ pageId }: { pageId: string }) {
variant="secondary" variant="secondary"
size="icon-sm" size="icon-sm"
disabled={isPending} disabled={isPending}
onClick={() => startTransition(() => archivePageAction(pageId))} onClick={() => startTransition(() => archivePageAction(pageId, slug, type))}
> >
{isPending ? <Spinner /> : <ArchiveIcon />} {isPending ? <Spinner /> : <ArchiveIcon />}
</Button> </Button>
+1 -2
View File
@@ -39,8 +39,7 @@ export default function EditPageClient({ page, pageType, initialBlocks = [] }: P
blocks: data.blocks, blocks: data.blocks,
meta: { location: data.location, tags: data.tags }, meta: { location: data.location, tags: data.tags },
}); });
const basePath = pageType === "NEWS" ? "news" : "pages"; router.push(`/${page?.type.toLowerCase()}/${data.slug}`);
router.push(`/${basePath}/${data.slug}`);
}); });
} }
+1
View File
@@ -16,6 +16,7 @@ export default async function EditPage({ params }: { params: Promise<{ type: str
if (!PAGE_TYPES.includes(pageType)) notFound(); if (!PAGE_TYPES.includes(pageType)) notFound();
const page = await getPageBySlug(slug); const page = await getPageBySlug(slug);
if (!page) notFound();
const blocks = page ? await getBlocksByPageId(page.id) : []; const blocks = page ? await getBlocksByPageId(page.id) : [];
return ( return (
+143 -37
View File
@@ -4,44 +4,131 @@ import { getPageBySlug, getBlocksByPageId } from "@/lib/pages/repository";
import { getCurrentUser, getUser } from "@/lib/user"; import { getCurrentUser, getUser } from "@/lib/user";
import { notFound } from "next/navigation"; import { notFound } from "next/navigation";
import { Block, PAGE_TYPES, PageMeta, PageType } from "@/lib/pages/types"; import { Block, PAGE_TYPES, PageMeta, PageType } from "@/lib/pages/types";
import { formatDate } from "@/lib/utils"; import { cn, formatDate } from "@/lib/utils";
import { ArchiveIcon, CalendarIcon, Globe2Icon, InfoIcon, PencilIcon, UserIcon } from "lucide-react"; import { CalendarIcon, DotIcon, Globe2Icon, InfoIcon, PencilIcon, UserIcon } from "lucide-react";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Separator } from "@/components/ui/separator"; import { Separator } from "@/components/ui/separator";
import Link from "next/link"; import Link from "next/link";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { archivePageAction } from "@/lib/pages/actions";
import { ArchiveButton } from "./archiveButton"; import { ArchiveButton } from "./archiveButton";
import { PinToggleButton } from "./pinToggleButton";
import { getNavLinkByPageId } from "@/lib/navlinks/repository";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import Image from "next/image";
function BlockRenderer({ block }: { block: Block }) {
const b = block.content;
function BlockRenderer({ block }: {block: Block }) {
const b = block.content
switch (b.type) { switch (b.type) {
case "PARAGRAPH": case "PARAGRAPH":
return <h4>{b.text}</h4> return (
<p className="leading-relaxed whitespace-pre-wrap">
{b.text}
</p>
);
case "HEADING": case "HEADING":
switch (b.level) { switch (b.level) {
case 1: case 1:
return <h1>{b.text}</h1> return <h1>{b.text}</h1>;
case 2: case 2:
return <h2>{b.text}</h2> return <h2>{b.text}</h2>;
case 3: case 3:
return <h3>{b.text}</h3> return <h3>{b.text}</h3>;
default:
return <h2>{b.text}</h2>;
} }
case "QUOTE": case "QUOTE":
return <div className="flex flex-col gap-2 border-l-2 border-muted-foreground pl-4"> return (
<p>{b.text}</p> <div className="flex flex-col gap-2 border-l-2 border-muted-foreground pl-4">
<h5 className="text-sm text-muted-foreground">{b.author}</h5> <p className="italic">{b.text}</p>
</div> {b.author && (
<h5 className="text-sm text-muted-foreground">
— {b.author}
</h5>
)}
</div>
);
case "CALLOUT": case "CALLOUT":
return <Alert> return (
<InfoIcon /> <Alert className="w-max">
<AlertTitle>{b.title}</AlertTitle> <InfoIcon />
<AlertDescription>{b.text}</AlertDescription> <AlertTitle>{b.title}</AlertTitle>
</Alert> <AlertDescription>{b.text}</AlertDescription>
</Alert>
);
case "IMAGE":
return (
<figure className="flex flex-col gap-2">
<Image
src={b.url}
alt={b.caption || "Image"}
width={1200}
height={800}
className="rounded-md border max-w-200 h-auto object-contain"
/>
{b.caption && (
<figcaption className="text-sm text-muted-foreground">
{b.caption}
</figcaption>
)}
</figure>
);
case "LIST":
return b.style === "ORDERED" ? (
<div className="flex flex-col gap-2">
{b.items.map((item: string, index: number) => (
<p className="flex flex-row gap-1 items-center" key={index}><span className="text-muted-foreground">{index+1}.</span> {item}</p>
))}
</div>
) : (
<div className="flex flex-col gap-2">
{b.items.map((item: string, index: number) => (
<p className="flex flex-row gap-1 items-center" key={index}><DotIcon className="text-muted-foreground" /> {item}</p>
))}
</div>
);
case "TABLE":
return (
<div className="overflow-x-auto">
<Table>
<TableHeader>
<TableRow>
{b.headers.map((header: string, index: number) => (
<TableHead key={index}>{header}</TableHead>
))}
</TableRow>
</TableHeader>
<TableBody>
{b.rows.map((row: string[], rowIndex: number) => (
<TableRow key={rowIndex}>
{row.map((cell: string, cellIndex: number) => (
<TableCell key={cellIndex}>{cell}</TableCell>
))}
</TableRow>
))}
</TableBody>
</Table>
</div>
);
case "DIVIDER": case "DIVIDER":
return <Separator /> return <Separator />;
case "LINK":
return <Link href={b.href} target="_blank">
<Button variant="secondary" className="w-max">{b.label}</Button>
</Link>
default: default:
return return null;
} }
} }
@@ -56,36 +143,55 @@ export default async function Page({ params }: { params: Promise<{ type: string;
const page = await getPageBySlug(slug); const page = await getPageBySlug(slug);
if (!page || (!user?.isAdmin && page.status == "ARCHIVED")) notFound(); if (!page || (!user?.isAdmin && page.status == "ARCHIVED")) notFound();
const navlink = await getNavLinkByPageId(page.id);
const blocks = page ? await getBlocksByPageId(page.id) : []; const blocks = page ? await getBlocksByPageId(page.id) : [];
const createdBy = await getUser(page?.createdBy); const createdBy = await getUser(page?.createdBy);
const updatedBy = await getUser(page?.updatedBy); const updatedBy = await getUser(page?.updatedBy);
const isNews = page.type === "NEWS";
const isArchived = page.status === "ARCHIVED";
const wasUpdated = formatDate(page.publishedAt) !== formatDate(page.updatedAt);
const location = (page.meta as PageMeta)?.location;
const wasUpdatedByOther = page.updatedBy && page.createdBy !== page.updatedBy;
const meta = {
publishedAt: isNews ? formatDate(page.publishedAt) : null,
updatedAt: (wasUpdated || !isNews) ? formatDate(page.updatedAt) : null,
location: location ?? null,
author: user?.isAdmin ? `${createdBy?.firstName} ${createdBy?.secondName}` : null,
updatedBy: user?.isAdmin && wasUpdatedByOther ? `${updatedBy?.firstName} ${updatedBy?.secondName}` : null,
};
return ( return (
<> <>
<Header /> <Header />
<div className="flex flex-col p-16 gap-16"> <div className="flex flex-col p-16 gap-12">
<div className="flex flex-col gap-4 items-center justify-center"> <div className={cn("flex flex-col gap-4 justify-center", isNews && "items-center")}>
<div className="flex flex-row items-center gap-6"> <div className="flex flex-row items-center gap-6">
<h1 className="underline underline-offset-8 decoration-2 text-center">{page?.title}</h1> <h1 className="underline underline-offset-8 decoration-2">{page?.title}</h1>
<div className="flex flex-row gap-2 items-center"> {user?.isAdmin && (
<Link href={`/news/${page.slug}/edit`}> <div className="flex flex-row gap-2 items-center">
<Button variant="secondary" size="icon-sm"><PencilIcon /></Button> <Link href={`/${page.type.toLowerCase()}/${page.slug}/edit`}>
</Link> <Button variant="secondary" size="icon-sm"><PencilIcon /></Button>
{page.status != "ARCHIVED" && <ArchiveButton pageId={page.id} />} </Link>
</div> {!isArchived && <ArchiveButton pageId={page.id} slug={page.slug} type={page.type} />}
{!isArchived && <PinToggleButton label={page.title} pageId={page.id} isPinned={!!navlink} />}
</div>
)}
</div> </div>
<div className="flex flex-row gap-6 items-center"> <div className="flex flex-row gap-6 items-center">
<p className="flex gap-1.5 items-center"><CalendarIcon size={16} />{formatDate(page?.publishedAt)}</p> {meta.publishedAt && <p className="flex gap-1.5 items-center"><CalendarIcon size={16} />{meta.publishedAt}</p>}
{formatDate(page?.publishedAt) !== formatDate(page?.updatedAt) && <p className="flex gap-2 items-center"><CalendarIcon size={16} />Updated on {formatDate(page?.updatedAt)}</p>} {meta.updatedAt && <p className="flex gap-1.5 items-center"><CalendarIcon size={16} />Updated on {meta.updatedAt}</p>}
{(page?.meta as PageMeta)?.location && <p className="flex gap-1.5 items-center"><Globe2Icon size={16} />{(page?.meta as PageMeta)?.location}</p>} {meta.location && <p className="flex gap-1.5 items-center"><Globe2Icon size={16} />{meta.location}</p>}
{user?.isAdmin && <p className="flex gap-1.5 items-center"><UserIcon size={16} />{`${createdBy?.firstName} ${createdBy?.secondName}`}</p>} {meta.author && <p className="flex gap-1.5 items-center"><UserIcon size={16} />{meta.author}</p>}
{user?.isAdmin && page.updatedBy && page.createdBy !== page.updatedBy && <p className="flex gap-2 items-center"><CalendarIcon size={18} />Last update by {updatedBy?.firstName} ${updatedBy?.secondName}</p>} {meta.updatedBy && <p className="flex gap-1.5 items-center"><UserIcon size={16} />Last update by {meta.updatedBy}</p>}
</div> </div>
</div> </div>
<div className="flex flex-col gap-8"> <div className="flex flex-col gap-6">
{page.status == "ARCHIVED" && ( {isArchived && (
<Alert> <Alert className="w-max">
<InfoIcon /> <InfoIcon />
<AlertTitle>This page is archived</AlertTitle> <AlertTitle>This page is archived</AlertTitle>
<AlertDescription>It can be seen only by admins. Make any edits to make it visible again.</AlertDescription> <AlertDescription>It can be seen only by admins. Make any edits to make it visible again.</AlertDescription>
+23
View File
@@ -0,0 +1,23 @@
"use client";
import { useTransition } from "react";
import { Button } from "@/components/ui/button";
import { PinIcon, PinOffIcon } from "lucide-react";
import { Spinner } from "@/components/ui/spinner";
import { pinPageAction, unpinPageAction } from "@/lib/navlinks/actions";
export function PinToggleButton({ label, pageId, isPinned }: { label: string; pageId: string; isPinned: boolean }) {
const [isPending, startTransition] = useTransition();
const handleClick = () => {
startTransition(() =>
isPinned ? unpinPageAction(pageId) : pinPageAction(pageId)
);
};
return (
<Button variant={isPinned ? "secondary" : "secondary"} size="icon-sm" disabled={isPending} onClick={handleClick}>
{isPending ? <Spinner /> : isPinned ? <PinOffIcon /> : <PinIcon />}
</Button>
);
}
+5 -1
View File
@@ -10,7 +10,11 @@ import Link from "next/link";
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");
const drafts = await getPages("NEWS", "DRAFT");
const newsDrafts = await getPages("NEWS", "DRAFT");
const pageDrafts = await getPages("PAGE", "DRAFT");
const drafts = [...newsDrafts, ...pageDrafts];
return ( return (
<> <>
+8 -7
View File
@@ -1,11 +1,8 @@
import Footer from "@/components/footer"; import Footer from "@/components/footer";
import Header from "@/components/header"; import Header from "@/components/header";
import { NewsCard } from "@/components/newsCard"; import { NewsCard } from "@/components/newsCard";
import { Badge } from "@/components/ui/badge"
import { getPages } from "@/lib/pages/repository"; import { getPages } from "@/lib/pages/repository";
import { PageMeta } from "@/lib/pages/types"; import { ArrowRightIcon } from "lucide-react";
import { formatDate } from "@/lib/utils";
import { ArrowRightIcon, CalendarIcon, Globe2Icon } from "lucide-react";
import Link from "next/link"; import Link from "next/link";
export default async function Home() { export default async function Home() {
@@ -17,13 +14,17 @@ export default async function Home() {
<div className="flex flex-col p-16 gap-16"> <div className="flex flex-col p-16 gap-16">
<h1>Welcome to the <span className="underline underline-offset-8 decoration-2">European Federation</span>!</h1> <h1>Welcome to the <span className="underline underline-offset-8 decoration-2">European Federation</span>!</h1>
<div className="grid grid-cols-[2fr_1fr_1fr_1fr] gap-8"> <div className="grid grid-cols-[2fr_1fr_1fr_1fr] gap-8">
<Link href="/page/citizenship">
<div className="flex items-end h-64 p-4 rounded-lg bg-[#00a2e8] text-white"> <div className="flex items-end h-64 p-4 rounded-lg bg-[#00a2e8] text-white">
<h1 className="flex flex-row items-center gap-2 hover:gap-4 hover:underline underline-offset-8 decoration-2 duration-200 cursor-pointer">Become a citizen<ArrowRightIcon size={30} /></h1> <h1 className="flex flex-row items-center gap-2 hover:gap-4 hover:underline underline-offset-8 decoration-2 duration-200 cursor-pointer">Become a citizen<ArrowRightIcon size={30} /></h1>
</div> </div>
</Link>
<div className="grid grid-rows-2 gap-8"> <div className="grid grid-rows-2 gap-8">
<div className="flex items-end h-28 p-2.5 rounded-lg bg-muted"> <Link href="/page/president">
<h2 className="flex flex-row items-center gap-2 hover:gap-4 hover:underline underline-offset-8 decoration-2 duration-200 cursor-pointer">Learn more about the President</h2> <div className="flex items-end h-28 p-2.5 rounded-lg bg-muted">
</div> <h2 className="flex flex-row items-center gap-2 hover:gap-4 hover:underline underline-offset-8 decoration-2 duration-200 cursor-pointer">Learn more about the President</h2>
</div>
</Link>
<div className="flex items-end h-28 p-2.5 rounded-lg bg-muted"> <div className="flex items-end h-28 p-2.5 rounded-lg bg-muted">
<h2 className="flex flex-row items-center gap-2 hover:gap-4 hover:underline underline-offset-8 decoration-2 duration-200 cursor-pointer">Acknowledge with the Federal Government</h2> <h2 className="flex flex-row items-center gap-2 hover:gap-4 hover:underline underline-offset-8 decoration-2 duration-200 cursor-pointer">Acknowledge with the Federal Government</h2>
</div> </div>
-2
View File
@@ -17,8 +17,6 @@ import { Spinner } from "@/components/ui/spinner";
type Draft = { id: string; title: string; slug: string; updatedAt: Date }; type Draft = { id: string; title: string; slug: string; updatedAt: Date };
export default function DraftsDialog({ drafts }: { drafts: Draft[]}) { export default function DraftsDialog({ drafts }: { drafts: Draft[]}) {
const [isDeletingId, setIsDeletingId] = useState(""); const [isDeletingId, setIsDeletingId] = useState("");
+464 -210
View File
@@ -1,23 +1,19 @@
"use client"; "use client";
import { useState, useEffect } from "react"; import { useState, useEffect, useRef } from "react";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { import { Field, FieldGroup, FieldLabel, FieldSet } from "@/components/ui/field";
Field, import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from "@/components/ui/input-group";
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 { Block, BlockType, Page, PageMeta, PageType } from "@/lib/pages/types";
import { Globe2, Plus, Trash2, X } from "lucide-react"; import { Globe2Icon, PlusIcon, Trash2Icon, XIcon, GripVerticalIcon, ChevronDownIcon, 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 { cn } from "@/lib/utils";
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";
export type EditorData = { export type EditorData = {
title: string; title: string;
@@ -35,20 +31,42 @@ type EditorProps = {
onChange: (data: EditorData) => void; onChange: (data: EditorData) => void;
}; };
export default function Editor({ const BLOCK_ICONS: Record<BlockType, React.ReactNode> = {
page, PARAGRAPH: <AlignLeftIcon size={14} />,
initialBlocks = [], HEADING: <TypeIcon size={14} />,
onChange, IMAGE: <ImageIcon size={14} />,
}: EditorProps) { QUOTE: <QuoteIcon size={14} />,
CALLOUT: <AlertCircleIcon size={14} />,
DIVIDER: <MinusIcon size={14} />,
LIST: <ListIcon size={14} />,
TABLE: <TableIcon size={14} />,
LINK: <LinkIcon size={14} />
};
const BLOCK_LABELS: Record<BlockType, string> = {
PARAGRAPH: "Text",
HEADING: "Heading",
IMAGE: "Image",
QUOTE: "Quote",
CALLOUT: "Callout",
DIVIDER: "Divider",
LIST: "List",
TABLE: "Table",
LINK: "Link"
};
export default function Editor({ page, initialBlocks = [], onChange }: EditorProps) {
const meta = (page?.meta as PageMeta) ?? {}; const meta = (page?.meta as PageMeta) ?? {};
const [title, setTitle] = useState(page?.title ?? ""); const [title, setTitle] = useState(page?.title ?? "");
const [type, setType] = useState(page?.type ?? "NEWS"); const [type, setType] = useState<PageType>(page?.type ?? "NEWS");
const [slug, setSlug] = useState(page?.slug ?? ""); const [slug, setSlug] = useState(page?.slug ?? "");
const [location, setLocation] = useState(meta.location ?? ""); const [location, setLocation] = useState(meta.location ?? "");
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 [dropIndex, setDropIndex] = useState<number | null>(null);
useEffect(() => { useEffect(() => {
onChange({ onChange({
@@ -72,16 +90,16 @@ export default function Editor({
setTags(tags.filter((t) => t !== tag)); setTags(tags.filter((t) => t !== tag));
} }
function addBlock(type: BlockType) { function addBlock(blockType: BlockType) {
setBlocks([ setBlocks([
...blocks, ...blocks,
{ {
id: crypto.randomUUID(), id: crypto.randomUUID(),
pageId: page?.id ?? "", pageId: page?.id ?? "",
parentId: null, parentId: null,
type, type: blockType,
position: blocks.length, position: blocks.length,
content: getDefaultContent(type), content: getDefaultContent(blockType),
}, },
]); ]);
} }
@@ -94,10 +112,32 @@ export default function Editor({
setBlocks(blocks.map((b) => (b.id === id ? { ...b, content } : b))); setBlocks(blocks.map((b) => (b.id === id ? { ...b, content } : b)));
} }
function moveBlock(from: number, to: number) {
const updated = [...blocks];
const [moved] = updated.splice(from, 1);
updated.splice(to, 0, moved);
setBlocks(updated.map((b, i) => ({ ...b, position: i })));
}
function handleDragStart(index: number) {
setDragIndex(index);
}
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);
}
return ( return (
<div className="flex flex-col gap-10"> <div className="flex flex-col gap-10">
<FieldSet> <FieldSet>
<h2 className="underline underline-offset-8 decoration-2 mb-4">Meta</h2> <h2 className="underline underline-offset-8 decoration-2 mb-6">Meta</h2>
<FieldGroup> <FieldGroup>
<Field> <Field>
<FieldLabel htmlFor="title">Title</FieldLabel> <FieldLabel htmlFor="title">Title</FieldLabel>
@@ -105,21 +145,17 @@ export default function Editor({
<InputGroupInput <InputGroupInput
id="title" id="title"
value={title} value={title}
placeholder="Enter page title"
onChange={(e) => { onChange={(e) => {
setTitle(e.target.value); setTitle(e.target.value);
if (!page) { if (!page) setSlug(e.target.value.toLowerCase().replace(/\s+/g, "-"));
setSlug(
e.target.value.toLowerCase().replace(/\s+/g, "-")
);
}
}} }}
placeholder="Enter page title"
/> />
</InputGroup> </InputGroup>
</Field> </Field>
<Field> <Field>
<FieldLabel htmlFor="type">Page type</FieldLabel> <FieldLabel htmlFor="type">Page type</FieldLabel>
<Select defaultValue={type} onValueChange={(e) => setType(e)} disabled={true}> <Select defaultValue={type} onValueChange={(e) => setType(e as PageType)}>
<SelectTrigger> <SelectTrigger>
<SelectValue placeholder="Type" /> <SelectValue placeholder="Type" />
</SelectTrigger> </SelectTrigger>
@@ -134,122 +170,105 @@ export default function Editor({
<Field> <Field>
<FieldLabel htmlFor="slug">Slug</FieldLabel> <FieldLabel htmlFor="slug">Slug</FieldLabel>
<InputGroup> <InputGroup>
<InputGroupInput <InputGroupInput id="slug" value={slug} placeholder="page-slug" onChange={(e) => setSlug(e.target.value)} />
id="slug"
value={slug}
onChange={(e) => setSlug(e.target.value)}
placeholder="page-slug"
disabled={true}
/>
</InputGroup> </InputGroup>
</Field> </Field>
<Field> {type === "NEWS" && (
<FieldLabel htmlFor="location">Location</FieldLabel> <Field>
<InputGroup> <FieldLabel htmlFor="location">Location</FieldLabel>
<InputGroupAddon align="inline-start"> <InputGroup>
<Globe2 size={14} className="text-muted-foreground" /> <InputGroupAddon align="inline-start">
</InputGroupAddon> <Globe2Icon size={14} className="text-muted-foreground" />
<InputGroupInput </InputGroupAddon>
id="location" <InputGroupInput id="location" value={location} placeholder="Liberty City, European Federation" onChange={(e) => setLocation(e.target.value)} />
value={location} </InputGroup>
onChange={(e) => setLocation(e.target.value)} </Field>
placeholder="Liberty City, European Federation" )}
/> {type === "NEWS" && (
</InputGroup> <Field>
</Field> <FieldLabel htmlFor="tags">Tags</FieldLabel>
<Field> <InputGroup>
<FieldLabel htmlFor="tags">Tags</FieldLabel> <InputGroupInput
<InputGroup> id="tags"
<InputGroupInput value={tagInput}
id="tags" placeholder="Add a tag and press Enter"
value={tagInput} onChange={(e) => setTagInput(e.target.value)}
onChange={(e) => setTagInput(e.target.value)} onKeyDown={(e) => e.key === "Enter" && addTag()}
onKeyDown={(e) => e.key === "Enter" && addTag()} />
placeholder="Add a tag and press Enter" <InputGroupAddon align="inline-end">
/> <InputGroupButton onClick={addTag}>Add</InputGroupButton>
<InputGroupAddon align="inline-end"> </InputGroupAddon>
<InputGroupButton onClick={addTag}>Add</InputGroupButton> </InputGroup>
</InputGroupAddon> {tags.length > 0 && (
</InputGroup> <div className="flex flex-row gap-2 flex-wrap mt-3">
{tags.length > 0 && ( {tags.map((tag) => (
<div className="flex flex-row gap-2 flex-wrap mt-3"> <Badge key={tag} variant="secondary" className="flex gap-1 items-center cursor-pointer" onClick={() => removeTag(tag)}>
{tags.map((tag) => ( {tag}
<Badge <XIcon size={11} />
key={tag} </Badge>
variant="secondary" ))}
className="flex gap-1 items-center cursor-pointer" </div>
onClick={() => removeTag(tag)} )}
> </Field>
{tag} )}
<X size={11} />
</Badge>
))}
</div>
)}
</Field>
</FieldGroup> </FieldGroup>
</FieldSet> </FieldSet>
<FieldSet> <div className="flex flex-col gap-1">
<h2 className="underline underline-offset-8 decoration-2 mb-4">Content</h2> <h2 className="underline underline-offset-8 decoration-2 mb-6">Content</h2>
<div className="flex flex-col gap-3"> {blocks.length === 0 && (
{blocks.length === 0 && ( <p className="text-sm text-muted-foreground">No blocks yet. Add one below.</p>
<p className="text-sm text-muted-foreground"> )}
No blocks yet. Add one below. <div className="flex flex-col gap-6">
</p> {blocks.map((block, index) => (
)} <div
{blocks.map((block) => (
<BlockEditor
key={block.id} key={block.id}
block={block} draggable
onChange={(content) => updateBlock(block.id, content)} onDragStart={() => handleDragStart(index)}
onRemove={() => removeBlock(block.id)} onDragOver={(e) => handleDragOver(e, index)}
/> onDrop={() => handleDrop(index)}
))} onDragEnd={() => { setDragIndex(null); setDropIndex(null); }}
</div> className={cn(
<div className="flex flex-row gap-2 flex-wrap mt-6"> "group relative flex flex-row gap-4 items-start py-1 transition-opacity",
{( dragIndex === index && "opacity-30",
[ dropIndex === index && dragIndex !== index && "border-t-2 border-primary"
"PARAGRAPH", )}
"HEADING",
"IMAGE",
"QUOTE",
"CALLOUT",
"DIVIDER",
"LIST",
"TABLE",
] as BlockType[]
).map((t) => (
<Button
key={t}
variant="outline"
size="sm"
onClick={() => addBlock(t)}
> >
<Plus size={12} /> <div className="flex-1 min-w-0">
{t.charAt(0) + t.slice(1).toLowerCase()} <BlockInput block={block} onChange={(content) => updateBlock(block.id, content)} />
</Button> </div>
<div className="flex flex-col gap-2 items-center opacity-0 group-hover:opacity-100 transition-opacity shrink-0">
<Button variant="ghost" className="cursor-grab active:cursor-grabbing" size="icon-sm" >
<GripVerticalIcon />
</Button>
<Button variant="ghost" onClick={() => removeBlock(block.id)} size="icon-sm" >
<Trash2Icon />
</Button>
</div>
</div>
))} ))}
</div> </div>
</FieldSet>
</div>
);
}
function BlockEditor({ block, onChange, onRemove }: { block: Block; onChange: (content: Block["content"]) => void; onRemove: () => void }) { <div className="mt-4">
return ( <DropdownMenu>
<div className="flex flex-row gap-3 items-start group"> <DropdownMenuTrigger asChild>
<div className="flex-1 rounded-md border bg-background p-4"> <Button variant="outline" size="sm" className="gap-1.5 text-muted-foreground">
<BlockInput block={block} onChange={onChange} /> <PlusIcon size={14} />
<p>Add block</p>
<ChevronDownIcon size={12} />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-44">
{(["PARAGRAPH", "HEADING", "IMAGE", "QUOTE", "CALLOUT", "DIVIDER", "LIST", "TABLE", "LINK"] as BlockType[]).map((t) => (
<DropdownMenuItem key={t} onClick={() => addBlock(t)} className="gap-2">
<p className="text-muted-foreground">{BLOCK_ICONS[t]}</p>
<p>{BLOCK_LABELS[t]}</p>
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
</div>
</div> </div>
<Button
variant="ghost"
size="icon"
onClick={onRemove}
className="opacity-0 group-hover:opacity-100 transition-opacity mt-1 shrink-0"
>
<Trash2 size={14} />
</Button>
</div> </div>
); );
} }
@@ -258,111 +277,346 @@ function BlockInput({ block, onChange }: { block: Block; onChange: (c: Block["co
switch (block.type) { switch (block.type) {
case "PARAGRAPH": case "PARAGRAPH":
return ( return (
<textarea <AutoResizeTextarea
className="w-full bg-transparent resize-none outline-none text-sm leading-relaxed" className="w-full bg-transparent resize-none outline-none leading-relaxed placeholder:text-muted-foreground"
rows={3}
placeholder="Start writing..." placeholder="Start writing..."
value={(block.content as any).text ?? ""} value={(block.content as any).text ?? ""}
onChange={(e) => onChange={(e) => onChange({ type: "PARAGRAPH", text: e.target.value })}
onChange({ type: "PARAGRAPH", text: e.target.value })
}
/> />
); );
case "HEADING": case "HEADING":
return ( return (
<input <div className="flex items-center gap-2">
className="w-full bg-transparent outline-none text-lg tracking-tight" <input
placeholder="Heading" className="flex-1 bg-transparent outline-none tracking-tight placeholder:text-muted-foreground"
value={(block.content as any).text ?? ""} placeholder="Heading"
onChange={(e) => value={(block.content as any).text ?? ""}
onChange({ type: "HEADING", text: e.target.value, level: 2 }) onChange={(e) => onChange({ type: "HEADING", text: e.target.value, level: (block.content as any).level ?? 2 })}
} />
/> <Select
value={String((block.content as any).level ?? 2)}
onValueChange={(v) => onChange({ type: "HEADING", text: (block.content as any).text ?? "", level: Number(v) as 1 | 2 | 3 })}
>
<SelectTrigger className="w-16 h-7 opacity-0 group-hover:opacity-100 transition-opacity">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="1">H1</SelectItem>
<SelectItem value="2">H2</SelectItem>
<SelectItem value="3">H3</SelectItem>
</SelectContent>
</Select>
</div>
); );
case "QUOTE": case "QUOTE":
return ( return (
<div className="flex flex-col gap-2 border-l-2 pl-4"> <div className="flex flex-col gap-2 border-l-2 border-muted-foreground pl-4">
<textarea <AutoResizeTextarea
className="w-full bg-transparent resize-none outline-none text-sm italic leading-relaxed" className="w-full bg-transparent resize-none outline-none leading-relaxed placeholder:text-muted-foreground"
rows={2}
placeholder="Quote text..." placeholder="Quote text..."
value={(block.content as any).text ?? ""} value={(block.content as any).text ?? ""}
onChange={(e) => onChange={(e) => onChange({ type: "QUOTE", text: e.target.value, author: (block.content as any).author })}
onChange({
type: "QUOTE",
text: e.target.value,
author: (block.content as any).author,
})
}
/> />
<input <input
className="w-full bg-transparent outline-none text-xs text-muted-foreground" className="w-full bg-transparent outline-none text-sm text-muted-foreground placeholder:text-muted-foreground/60"
placeholder="Author" placeholder="— Author"
value={(block.content as any).author ?? ""} value={(block.content as any).author ?? ""}
onChange={(e) => onChange={(e) => onChange({ type: "QUOTE", text: (block.content as any).text, author: e.target.value })}
onChange({
type: "QUOTE",
text: (block.content as any).text,
author: e.target.value,
})
}
/> />
</div> </div>
); );
case "DIVIDER":
return <hr className="border-border" />;
case "CALLOUT": case "CALLOUT":
return ( return (
<div className="flex flex-row gap-3 items-start rounded-md bg-muted p-3"> <Alert>
<span className="text-base leading-none mt-0.5">⚠️</span> <InfoIcon />
<textarea <input
className="w-full bg-transparent resize-none outline-none text-sm leading-relaxed" className="w-full bg-transparent outline-none text-sm font-medium placeholder:text-muted-foreground"
rows={2} placeholder="Callout title"
value={(block.content as any).title ?? ""}
onChange={(e) => onChange({ type: "CALLOUT", title: e.target.value, text: (block.content as any).text ?? "" })}
/>
<AutoResizeTextarea
className="w-full bg-transparent resize-none outline-none text-sm leading-relaxed text-muted-foreground placeholder:text-muted-foreground/60"
placeholder="Callout text..." placeholder="Callout text..."
value={(block.content as any).text ?? ""} value={(block.content as any).text ?? ""}
onChange={(e) => onChange={(e) => onChange({ type: "CALLOUT", title: (block.content as any).title ?? "", text: e.target.value })}
onChange({ type: "CALLOUT", text: e.target.value }) />
} </Alert>
);
case "IMAGE":
return (
<div className="flex flex-col gap-4">
<input
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"
placeholder="https://example.com/image.jpg"
value={(block.content as any).url ?? ""}
onChange={(e) => onChange({ type: "IMAGE", url: e.target.value })}
/>
{(block.content as any).url && (
<div className="w-max relative 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="max-h-64 w-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> </div>
); );
case "IMAGE":
case "DIVIDER":
return <Separator />;
case "LIST":
return <ListEditor content={block.content as any} onChange={(c) => onChange(c)} />;
case "TABLE":
return <TableEditor content={block.content as any} onChange={(c) => onChange(c)} />;
case "LINK":
return ( return (
<input <div className="flex flex-row gap-2.5">
className="w-full bg-transparent outline-none text-sm text-muted-foreground" <LinkIcon size={16} />
placeholder="https://example.com/image.jpg" <div className="flex flex-col gap-2">
value={(block.content as any).url ?? ""} <input
onChange={(e) => onChange({ type: "IMAGE", url: e.target.value })} className="w-full bg-transparent outline-none text-sm"
/> placeholder="Link label"
value={(block.content as any).label ?? ""}
onChange={(e) =>
onChange({
type: "LINK",
label: e.target.value,
href: (block.content as any).href ?? "",
})
}
/>
<input
className="w-full bg-transparent outline-none text-sm text-muted-foreground"
placeholder="URL"
value={(block.content as any).href ?? ""}
onChange={(e) =>
onChange({
type: "LINK",
label: (block.content as any).label ?? "",
href: e.target.value,
})
}
/>
</div>
</div>
); );
default: default:
return ( return <p className="text-muted-foreground text-sm py-1.5">{block.type} — editor coming soon</p>;
<p className="text-muted-foreground text-sm">
{block.type} — editor coming soon
</p>
);
} }
} }
function ListEditor({ content, onChange }: { content: { type: "LIST"; style: "BULLET" | "ORDERED"; items: string[] }; onChange: (c: any) => void }) {
const items = content.items ?? [""];
function updateItem(index: number, value: string) {
const updated = [...items];
updated[index] = value;
onChange({ ...content, items: updated });
}
function addItem() {
onChange({ ...content, items: [...items, ""] });
}
function removeItem(index: number) {
const updated = items.filter((_, i) => i !== index);
onChange({ ...content, items: updated.length ? updated : [""] });
}
function handleKeyDown(e: React.KeyboardEvent, index: number) {
if (e.key === "Enter") {
e.preventDefault();
const updated = [...items];
updated.splice(index + 1, 0, "");
onChange({ ...content, items: updated });
setTimeout(() => {
const inputs = document.querySelectorAll(`[data-list-item]`);
(inputs[index + 1] as HTMLInputElement)?.focus();
}, 0);
}
if (e.key === "Backspace" && items[index] === "" && items.length > 1) {
e.preventDefault();
removeItem(index);
}
}
return (
<div className="flex flex-col gap-2">
<div className="flex items-center gap-2 mb-2">
<Select value={content.style} onValueChange={(v) => onChange({ ...content, style: v })}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="BULLET"><ListIcon />Bullet</SelectItem>
<SelectItem value="ORDERED"><ListOrderedIcon /> Ordered</SelectItem>
</SelectContent>
</Select>
</div>
<div className="flex flex-col gap-1">
{items.map((item, index) => (
<div key={index} className="flex items-center gap-2">
<span className="text-muted-foreground w-4 shrink-0 text-right">
{content.style === "ORDERED" ? `${index + 1}.` : <DotIcon />}
</span>
<input
data-list-item
className="w-64 bg-transparent outline-none py-0.5 placeholder:text-muted-foreground"
placeholder="List item"
value={item}
onChange={(e) => updateItem(index, e.target.value)}
onKeyDown={(e) => handleKeyDown(e, index)}
/>
{items.length > 1 && (
<Button variant="ghost" onClick={() => removeItem(index)} size="icon-sm" >
<XIcon />
</Button>
)}
</div>
))}
</div>
<Button className="w-max mt-2 text-muted-foreground" variant="outline" onClick={addItem} size="sm">
<PlusIcon />
Add item
</Button>
</div>
);
}
function TableEditor({ content, onChange }: { content: { type: "TABLE"; headers: string[]; rows: string[][] }; onChange: (c: any) => void }) {
const headers = content.headers ?? ["Column 1"];
const rows = content.rows ?? [];
function updateHeader(index: number, value: string) {
const updated = [...headers];
updated[index] = value;
onChange({ ...content, headers: updated });
}
function addColumn() {
onChange({ ...content, headers: headers.concat(""), rows: rows.map((row) => [...row, ""]) });
}
function removeColumn(colIndex: number) {
if (headers.length <= 1) return;
onChange({
...content,
headers: headers.filter((_, i) => i !== colIndex),
rows: rows.map((row) => row.filter((_, i) => i !== colIndex)),
});
}
function addRow() {
onChange({ ...content, rows: [...rows, headers.map(() => "")] });
}
function removeRow(rowIndex: number) {
onChange({ ...content, rows: rows.filter((_, i) => i !== rowIndex) });
}
function updateCell(rowIndex: number, colIndex: number, value: string) {
onChange({
...content,
rows: rows.map((row, ri) => ri === rowIndex ? row.map((cell, ci) => (ci === colIndex ? value : cell)) : row),
});
}
return (
<div className="flex flex-col gap-2 py-1 overflow-x-auto">
<Table>
<TableHeader>
<TableRow>
{headers.map((header, ci) => (
<TableHead key={ci}>
<div className="flex flex-row items-center">
<input
className="flex-1 bg-transparent outline-none placeholder:text-muted-foreground min-w-0"
placeholder={`Column ${ci + 1}`}
value={header}
onChange={(e) => updateHeader(ci, e.target.value)}
/>
{headers.length > 1 && (
<Button variant="ghost" onClick={() => removeColumn(ci)} size="icon-sm" >
<XIcon />
</Button>
)}
</div>
</TableHead>
))}
<TableHead>
<Button variant="ghost" onClick={addColumn} size="icon-sm" >
<PlusIcon />
</Button>
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{rows.map((row, ri) => (
<TableRow key={ri}>
{row.map((cell, ci) => (
<TableCell key={ci}>
<input className="w-full bg-transparent outline-none placeholder:text-muted-foreground min-w-0" placeholder="Value" value={cell} onChange={(e) => updateCell(ri, ci, e.target.value)} />
</TableCell>
))}
<TableCell>
<Button variant="ghost" onClick={() => removeRow(ri)} size="icon-sm" >
<XIcon />
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
<Button className="w-max mt-2 text-muted-foreground" variant="outline" onClick={addRow} size="sm">
<PlusIcon />
Add row
</Button>
</div>
);
}
function AutoResizeTextarea({ value, onChange, className, placeholder }: { value: string; onChange: (e: React.ChangeEvent<HTMLTextAreaElement>) => void; className?: string; placeholder?: string }) {
const ref = useRef<HTMLTextAreaElement>(null);
useEffect(() => {
if (ref.current) {
ref.current.style.height = "auto";
ref.current.style.height = `${ref.current.scrollHeight}px`;
}
}, [value]);
return <textarea ref={ref} rows={1} className={cn("overflow-hidden", className)} placeholder={placeholder} value={value} onChange={onChange} />;
}
function getDefaultContent(type: BlockType): Block["content"] { function getDefaultContent(type: BlockType): Block["content"] {
switch (type) { switch (type) {
case "PARAGRAPH": case "PARAGRAPH": return { type: "PARAGRAPH", text: "" };
return { type: "PARAGRAPH", text: "" }; case "HEADING": return { type: "HEADING", text: "", level: 2 };
case "HEADING": case "QUOTE": return { type: "QUOTE", text: "" };
return { type: "HEADING", text: "", level: 2 }; case "CALLOUT": return { type: "CALLOUT", title: "", text: "" };
case "QUOTE": case "DIVIDER": return { type: "DIVIDER" };
return { type: "QUOTE", text: "" }; case "LIST": return { type: "LIST", style: "BULLET", items: [""] };
case "CALLOUT": case "TABLE": return { type: "TABLE", headers: ["", ""], rows: [["", ""]] };
return { type: "CALLOUT", text: "" }; case "IMAGE": return { type: "IMAGE", url: "", caption: "" };
case "DIVIDER": default: return { type: "PARAGRAPH", text: "" };
return { type: "DIVIDER" };
case "LIST":
return { type: "LIST", style: "BULLET", items: [] };
case "TABLE":
return { type: "TABLE", headers: [], rows: [] };
case "IMAGE":
return { type: "IMAGE", url: "" };
default:
return { type: "PARAGRAPH", text: "" };
} }
} }
+5 -5
View File
@@ -18,15 +18,15 @@ export default function Footer() {
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<Link href="/" className="text-black/60 cursor-pointer hover:underline underline-offset-8 decoration-2">Main</Link> <Link href="/" className="text-black/60 cursor-pointer hover:underline underline-offset-8 decoration-2">Main</Link>
<Link href="/news" className="text-black/60 cursor-pointer hover:underline underline-offset-8 decoration-2">News</Link> <Link href="/news" className="text-black/60 cursor-pointer hover:underline underline-offset-8 decoration-2">News</Link>
<Link href="/congress" className="text-black/60 cursor-pointer hover:underline underline-offset-8 decoration-2">The Congress</Link> <Link href="/page/congress" className="text-black/60 cursor-pointer hover:underline underline-offset-8 decoration-2">The Congress</Link>
</div> </div>
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<Link href="/president" className="text-black/60 cursor-pointer hover:underline underline-offset-8 decoration-2">President</Link> <Link href="/page/president" className="text-black/60 cursor-pointer hover:underline underline-offset-8 decoration-2">President</Link>
<Link href="/vice-president" className="text-black/60 cursor-pointer hover:underline underline-offset-8 decoration-2">Vice-President</Link> <Link href="/page/vice-president" className="text-black/60 cursor-pointer hover:underline underline-offset-8 decoration-2">Vice President</Link>
<Link href="/government" className="text-black/60 cursor-pointer hover:underline underline-offset-8 decoration-2">Federal Government</Link> <Link href="/page/government" className="text-black/60 cursor-pointer hover:underline underline-offset-8 decoration-2">Federal Government</Link>
</div> </div>
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<Link href="/regions" className="text-black/60 cursor-pointer hover:underline underline-offset-8 decoration-2">Regions</Link> <Link href="/page/regions" className="text-black/60 cursor-pointer hover:underline underline-offset-8 decoration-2">Regions</Link>
</div> </div>
</div> </div>
<p>© 2026 European Federation. All rights reserved.</p> <p>© 2026 European Federation. All rights reserved.</p>
+10 -2
View File
@@ -4,14 +4,15 @@ import login from "@/app/actions/login";
import { getCurrentUser } from "@/lib/user"; import { getCurrentUser } from "@/lib/user";
import logout from "@/app/actions/logout"; import logout from "@/app/actions/logout";
import Link from "next/link"; import Link from "next/link";
import { getNavLinks } from "@/lib/navlinks/repository";
export default async function Header() { export default async function Header() {
const user = await getCurrentUser(); const user = await getCurrentUser();
const links = await getNavLinks();
return ( return (
<header className="relative flex items-center justify-between w-full h-16 px-8 bg-gray-100"> <header className="relative flex items-center justify-between w-full h-16 px-8 bg-gray-100">
<div /> <Link href="/" className="flex items-center gap-4">
<Link href="/" className="absolute left-1/2 -translate-x-1/2 flex items-center gap-4">
<Image <Image
src="/emblem.png" src="/emblem.png"
width={28} width={28}
@@ -20,6 +21,13 @@ export default async function Header() {
/> />
<h3>European Federation</h3> <h3>European Federation</h3>
</Link> </Link>
<div className="absolute left-1/2 -translate-x-1/2 flex items-center gap-6">
{
links.map((link) => (
<Link className="hover:underline underline-offset-8 decoration-2 duration-200" key={link.id} href={link.href || `/${link.page.type.toLowerCase()}/${link.page.slug}`}><h3>{link.label ?? link.page?.title}</h3></Link>
))
}
</div>
{ {
user ? ( user ? (
<form action={logout}> <form action={logout}>
+267
View File
@@ -0,0 +1,267 @@
"use client"
import * as React from "react"
import { CheckIcon, ChevronRightIcon } from "lucide-react"
import { DropdownMenu as DropdownMenuPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
function DropdownMenu({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />
}
function DropdownMenuPortal({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
return (
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
)
}
function DropdownMenuTrigger({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
return (
<DropdownMenuPrimitive.Trigger
data-slot="dropdown-menu-trigger"
{...props}
/>
)
}
function DropdownMenuContent({
className,
align = "start",
sideOffset = 4,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
return (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
data-slot="dropdown-menu-content"
sideOffset={sideOffset}
align={align}
className={cn("z-50 max-h-(--radix-dropdown-menu-content-available-height) w-(--radix-dropdown-menu-trigger-width) min-w-32 origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:overflow-hidden data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className )}
{...props}
/>
</DropdownMenuPrimitive.Portal>
)
}
function DropdownMenuGroup({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
return (
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
)
}
function DropdownMenuItem({
className,
inset,
variant = "default",
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean
variant?: "default" | "destructive"
}) {
return (
<DropdownMenuPrimitive.Item
data-slot="dropdown-menu-item"
data-inset={inset}
data-variant={variant}
className={cn(
"group/dropdown-menu-item relative flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-[variant=destructive]:*:[svg]:text-destructive",
className
)}
{...props}
/>
)
}
function DropdownMenuCheckboxItem({
className,
children,
checked,
inset,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem> & {
inset?: boolean
}) {
return (
<DropdownMenuPrimitive.CheckboxItem
data-slot="dropdown-menu-checkbox-item"
data-inset={inset}
className={cn(
"relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
checked={checked}
{...props}
>
<span
className="pointer-events-none absolute right-2 flex items-center justify-center"
data-slot="dropdown-menu-checkbox-item-indicator"
>
<DropdownMenuPrimitive.ItemIndicator>
<CheckIcon />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
)
}
function DropdownMenuRadioGroup({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
return (
<DropdownMenuPrimitive.RadioGroup
data-slot="dropdown-menu-radio-group"
{...props}
/>
)
}
function DropdownMenuRadioItem({
className,
children,
inset,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem> & {
inset?: boolean
}) {
return (
<DropdownMenuPrimitive.RadioItem
data-slot="dropdown-menu-radio-item"
data-inset={inset}
className={cn(
"relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
<span
className="pointer-events-none absolute right-2 flex items-center justify-center"
data-slot="dropdown-menu-radio-item-indicator"
>
<DropdownMenuPrimitive.ItemIndicator>
<CheckIcon />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
)
}
function DropdownMenuLabel({
className,
inset,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean
}) {
return (
<DropdownMenuPrimitive.Label
data-slot="dropdown-menu-label"
data-inset={inset}
className={cn(
"px-1.5 py-1 text-xs font-medium text-muted-foreground data-inset:pl-7",
className
)}
{...props}
/>
)
}
function DropdownMenuSeparator({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
return (
<DropdownMenuPrimitive.Separator
data-slot="dropdown-menu-separator"
className={cn("-mx-1 my-1 h-px bg-border", className)}
{...props}
/>
)
}
function DropdownMenuShortcut({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="dropdown-menu-shortcut"
className={cn(
"ml-auto text-xs tracking-widest text-muted-foreground group-focus/dropdown-menu-item:text-accent-foreground",
className
)}
{...props}
/>
)
}
function DropdownMenuSub({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />
}
function DropdownMenuSubTrigger({
className,
inset,
children,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean
}) {
return (
<DropdownMenuPrimitive.SubTrigger
data-slot="dropdown-menu-sub-trigger"
data-inset={inset}
className={cn(
"flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-open:bg-accent data-open:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
{children}
<ChevronRightIcon className="cn-rtl-flip ml-auto" />
</DropdownMenuPrimitive.SubTrigger>
)
}
function DropdownMenuSubContent({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
return (
<DropdownMenuPrimitive.SubContent
data-slot="dropdown-menu-sub-content"
className={cn("z-50 min-w-[96px] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-lg bg-popover p-1 text-popover-foreground shadow-lg ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className )}
{...props}
/>
)
}
export {
DropdownMenu,
DropdownMenuPortal,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuLabel,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuSub,
DropdownMenuSubTrigger,
DropdownMenuSubContent,
}
+19
View File
@@ -0,0 +1,19 @@
"use server";
import { revalidatePath } from "next/cache";
import { addNavLink, deleteNavLinkByPageId } from "./repository";
import { prisma } from "../prisma";
export async function pinPageAction(pageId: string) {
const page = await prisma.page.findUnique({ where: { id: pageId } });
if (!page) throw new Error(`Page not found: ${pageId}`);
await addNavLink({ pageId });
revalidatePath("/", "layout");
}
export async function unpinPageAction(pageId: string) {
await deleteNavLinkByPageId(pageId);
revalidatePath("/", "layout");
}
+46
View File
@@ -0,0 +1,46 @@
import { prisma } from "../prisma";
export async function getNavLinks() {
return await prisma.navLink.findMany({
orderBy: { order: "asc" },
include: {
page: true
}
});
}
export async function getNavLinkByPageId(pageId: string) {
return await prisma.navLink.findFirst({ where: { pageId }});
}
export async function addNavLink(link: { pageId?: string; href?: string; label?: string }) {
const last = await prisma.navLink.findFirst({
orderBy: { order: "desc" },
});
return await prisma.navLink.create({
data: {
...link,
order: last ? last.order + 1 : 0,
},
});
}
export async function reorderNavLinks(orderedIds: string[]) {
await prisma.$transaction(
orderedIds.map((id, index) =>
prisma.navLink.update({
where: { id },
data: { order: index },
})
)
);
}
export async function deleteNavLink(id: string) {
await prisma.navLink.delete({ where: { id } });
}
export async function deleteNavLinkByPageId(pageId: string) {
await prisma.navLink.deleteMany({ where: { pageId } });
}
+7
View File
@@ -0,0 +1,7 @@
export type NavLink = {
id: string;
label: string | null;
order: number;
pageId: string | null;
href: string | null;
}
+9 -11
View File
@@ -4,6 +4,7 @@ import { redirect } from "next/navigation";
import { Block, PageMeta, PageStatus, PageType } from "./types"; import { Block, PageMeta, PageStatus, PageType } from "./types";
import { archivePage, createPage, deletePage, updatePage } from "./repository"; import { archivePage, createPage, deletePage, updatePage } from "./repository";
import { revalidatePath } from "next/cache"; import { revalidatePath } from "next/cache";
import { deleteNavLinkByPageId } from "../navlinks/repository";
export async function savePageAction(params: { export async function savePageAction(params: {
id: string | null, id: string | null,
@@ -14,29 +15,26 @@ export async function savePageAction(params: {
blocks: Block[], blocks: Block[],
meta?: PageMeta meta?: PageMeta
}) { }) {
const basePath = params.type === "NEWS" ? "news" : "pages";
if (params.id) { if (params.id) {
await updatePage(params.id, params.title, params.type, params.status, params.blocks, params.meta); await updatePage(params.id, params.title, params.type, params.status, params.blocks, params.meta);
revalidatePath(`/${basePath}/${params.slug}`); revalidatePath(`/${params.type.toLowerCase()}/${params.slug}`);
revalidatePath(`/${basePath}`); revalidatePath(`/${params.type.toLowerCase()}`);
} else { } else {
const page = await createPage(params.slug, params.title, params.type, params.status, params.blocks, params.meta); const page = await createPage(params.slug, params.title, params.type, params.status, params.blocks, params.meta);
revalidatePath(`/${basePath}`); revalidatePath(`/${params.type.toLowerCase()}`);
redirect(`/${basePath}/${page.slug}/edit`); redirect(`/${params.type.toLowerCase()}/${page.slug}`);
} }
} }
export async function archivePageAction(id: string, slug: string, type: PageType) { export async function archivePageAction(id: string, slug: string, type: PageType) {
await archivePage(id); await archivePage(id);
const basePath = type === "NEWS" ? "news" : "pages"; await deleteNavLinkByPageId(id);
revalidatePath(`/${basePath}/${slug}`); revalidatePath(`/${type.toLowerCase()}/${slug}`);
revalidatePath(`/${basePath}`); revalidatePath(`/${type.toLowerCase()}`);
redirect(`/${basePath}`);
} }
export async function deletePageAction(id: string, type: PageType) { export async function deletePageAction(id: string, type: PageType) {
await deletePage(id); await deletePage(id);
const basePath = type === "NEWS" ? "news" : "pages"; revalidatePath(`/${type.toLowerCase()}`);
revalidatePath(`/${basePath}`);
} }
+7 -2
View File
@@ -17,12 +17,13 @@ export type Page = {
status: PageStatus; status: PageStatus;
meta: PageMeta; meta: PageMeta;
createdAt: Date; createdAt: Date;
updatedAt: Date; updatedAt: Date | null;
publishedAt: Date | null; publishedAt: Date | null;
createdBy: string; createdBy: string;
updatedBy: string | null;
} }
export const BLOCK_TYPES = ["PARAGRAPH", "HEADING", "QUOTE", "DIVIDER", "CALLOUT"] as const; export const BLOCK_TYPES = ["PARAGRAPH", "HEADING", "QUOTE", "DIVIDER", "CALLOUT", "IMAGE", "LIST", "TABLE", "LINK"] as const;
export type BlockType = typeof BLOCK_TYPES[number]; export type BlockType = typeof BLOCK_TYPES[number];
export type BlockContent = export type BlockContent =
@@ -31,6 +32,10 @@ export type BlockContent =
| { type: "QUOTE"; text: string; author?: string } | { type: "QUOTE"; text: string; author?: string }
| { type: "DIVIDER" } | { type: "DIVIDER" }
| { type: "CALLOUT"; title: string; text: string } | { type: "CALLOUT"; title: string; text: string }
| { type: "IMAGE"; url: string; caption?: string }
| { type: "LIST"; style: "BULLET" | "ORDERED"; items: string[] }
| { type: "TABLE"; headers: string[]; rows: string[][] }
| { type: "LINK"; label: string; href: string }
export type Block = { export type Block = {
id: string; id: string;
+1 -1
View File
@@ -7,7 +7,7 @@ export async function getCurrentUser() {
return findUserById(userId); return findUserById(userId);
} }
export async function getUser(id: string) { export async function getUser(id: string | null) {
if (!id) return null; if (!id) return null;
return findUserById(id); return findUserById(id);
} }
+8 -1
View File
@@ -1,7 +1,14 @@
import type { NextConfig } from "next"; import type { NextConfig } from "next";
const nextConfig: NextConfig = { const nextConfig: NextConfig = {
/* config options here */ images: {
remotePatterns: [
{
protocol: "https",
hostname: "**",
},
],
},
}; };
export default nextConfig; export default nextConfig;
+11
View File
@@ -61,6 +61,7 @@ model Page {
editor User? @relation("PageEditor", fields: [updatedBy], references: [id]) editor User? @relation("PageEditor", fields: [updatedBy], references: [id])
blocks Block[] blocks Block[]
navLinks NavLink[]
} }
model Block { model Block {
@@ -78,3 +79,13 @@ model Block {
@@index([pageId, position]) @@index([pageId, position])
} }
model NavLink {
id String @id @default(uuid())
label String?
order Int
pageId String?
page Page? @relation(fields: [pageId], references: [id], onDelete: SetNull)
href String?
}