[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>textarea]:h-auto dark:bg-input/30 dark:has-disabled:bg-input/80 dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40 has-[>[data-align=block-end]]:[&>input]:pt-3 has-[>[data-align=block-start]]:[&>input]:pb-3 has-[>[data-align=inline-end]]:[&>input]:pr-1.5 has-[>[data-align=inline-start]]:[&>input]:pl-1.5",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+const inputGroupAddonVariants = cva(
+ "flex h-auto cursor-text items-center justify-center gap-2 py-1.5 text-sm font-medium text-muted-foreground select-none group-data-[disabled=true]/input-group:opacity-50 [&>kbd]:rounded-[calc(var(--radius)-5px)] [&>svg:not([class*='size-'])]:size-4",
+ {
+ variants: {
+ align: {
+ "inline-start":
+ "order-first pl-2 has-[>button]:ml-[-0.3rem] has-[>kbd]:ml-[-0.15rem]",
+ "inline-end":
+ "order-last pr-2 has-[>button]:mr-[-0.3rem] has-[>kbd]:mr-[-0.15rem]",
+ "block-start":
+ "order-first w-full justify-start px-2.5 pt-2 group-has-[>input]/input-group:pt-2 [.border-b]:pb-2",
+ "block-end":
+ "order-last w-full justify-start px-2.5 pb-2 group-has-[>input]/input-group:pb-2 [.border-t]:pt-2",
+ },
+ },
+ defaultVariants: {
+ align: "inline-start",
+ },
+ }
+)
+
+function InputGroupAddon({
+ className,
+ align = "inline-start",
+ ...props
+}: React.ComponentProps<"div"> & VariantProps
) {
+ return (
+ {
+ if ((e.target as HTMLElement).closest("button")) {
+ return
+ }
+ e.currentTarget.parentElement?.querySelector("input")?.focus()
+ }}
+ {...props}
+ />
+ )
+}
+
+const inputGroupButtonVariants = cva(
+ "flex items-center gap-2 text-sm shadow-none",
+ {
+ variants: {
+ size: {
+ xs: "h-6 gap-1 rounded-[calc(var(--radius)-3px)] px-1.5 [&>svg:not([class*='size-'])]:size-3.5",
+ sm: "",
+ "icon-xs":
+ "size-6 rounded-[calc(var(--radius)-3px)] p-0 has-[>svg]:p-0",
+ "icon-sm": "size-8 p-0 has-[>svg]:p-0",
+ },
+ },
+ defaultVariants: {
+ size: "xs",
+ },
+ }
+)
+
+function InputGroupButton({
+ className,
+ type = "button",
+ variant = "ghost",
+ size = "xs",
+ ...props
+}: Omit, "size"> &
+ VariantProps) {
+ return (
+
+ )
+}
+
+function InputGroupText({ className, ...props }: React.ComponentProps<"span">) {
+ return (
+
+ )
+}
+
+function InputGroupInput({
+ className,
+ ...props
+}: React.ComponentProps<"input">) {
+ return (
+
+ )
+}
+
+function InputGroupTextarea({
+ className,
+ ...props
+}: React.ComponentProps<"textarea">) {
+ return (
+
+ )
+}
+
+export {
+ InputGroup,
+ InputGroupAddon,
+ InputGroupButton,
+ InputGroupText,
+ InputGroupInput,
+ InputGroupTextarea,
+}
diff --git a/components/ui/input.tsx b/components/ui/input.tsx
new file mode 100644
index 0000000..d763cd9
--- /dev/null
+++ b/components/ui/input.tsx
@@ -0,0 +1,19 @@
+import * as React from "react"
+
+import { cn } from "@/lib/utils"
+
+function Input({ className, type, ...props }: React.ComponentProps<"input">) {
+ return (
+
+ )
+}
+
+export { Input }
diff --git a/components/ui/label.tsx b/components/ui/label.tsx
new file mode 100644
index 0000000..1ac80f7
--- /dev/null
+++ b/components/ui/label.tsx
@@ -0,0 +1,24 @@
+"use client"
+
+import * as React from "react"
+import { Label as LabelPrimitive } from "radix-ui"
+
+import { cn } from "@/lib/utils"
+
+function Label({
+ className,
+ ...props
+}: React.ComponentProps) {
+ return (
+
+ )
+}
+
+export { Label }
diff --git a/components/ui/separator.tsx b/components/ui/separator.tsx
new file mode 100644
index 0000000..d457090
--- /dev/null
+++ b/components/ui/separator.tsx
@@ -0,0 +1,28 @@
+"use client"
+
+import * as React from "react"
+import { Separator as SeparatorPrimitive } from "radix-ui"
+
+import { cn } from "@/lib/utils"
+
+function Separator({
+ className,
+ orientation = "horizontal",
+ decorative = true,
+ ...props
+}: React.ComponentProps) {
+ return (
+
+ )
+}
+
+export { Separator }
diff --git a/components/ui/spinner.tsx b/components/ui/spinner.tsx
new file mode 100644
index 0000000..222eb1b
--- /dev/null
+++ b/components/ui/spinner.tsx
@@ -0,0 +1,17 @@
+import { Loader2Icon } from "lucide-react"
+
+import { cn } from "@/lib/utils"
+
+function Spinner({ className, ...props }: React.ComponentProps<"svg">) {
+ return (
+
+ )
+}
+
+export { Spinner }
diff --git a/components/ui/textarea.tsx b/components/ui/textarea.tsx
new file mode 100644
index 0000000..04d27f7
--- /dev/null
+++ b/components/ui/textarea.tsx
@@ -0,0 +1,18 @@
+import * as React from "react"
+
+import { cn } from "@/lib/utils"
+
+function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
+ return (
+
+ )
+}
+
+export { Textarea }
diff --git a/lib/pages/actions.ts b/lib/pages/actions.ts
new file mode 100644
index 0000000..d1a0fb6
--- /dev/null
+++ b/lib/pages/actions.ts
@@ -0,0 +1,31 @@
+"use server";
+
+import { redirect } from "next/navigation";
+import { Block, PageMeta, PageStatus, PageType } from "./types";
+import { createPage, deletePage, updatePage } from "./repository";
+import { revalidatePath } from "next/cache";
+
+export async function savePageAction(params: {
+ id: string | null,
+ slug: string,
+ title: string,
+ type: PageType,
+ status: PageStatus,
+ blocks: Block[],
+ meta?: PageMeta
+}) {
+ if (params.id) {
+ await updatePage(params.id, params.title, params.status, params.blocks, params.meta);
+ revalidatePath(`/${params.slug}`);
+ revalidatePath("/news");
+ } else {
+ const page = await createPage(params.slug, params.title, params.type, params.status, params.blocks, params.meta);
+ revalidatePath("/news");
+ redirect(`/news/${page.slug}/edit`);
+ }
+}
+
+export async function deletePageAction(id: string) {
+ await deletePage(id);
+ revalidatePath("/news");
+}
\ No newline at end of file
diff --git a/lib/pages/repository.ts b/lib/pages/repository.ts
new file mode 100644
index 0000000..50df5e4
--- /dev/null
+++ b/lib/pages/repository.ts
@@ -0,0 +1,152 @@
+import { getCurrentUser } from "../user";
+import { Block, PageMeta, PageStatus, PageType } from "./types";
+import { prisma } from "../prisma";
+
+export async function getPages(type: PageType, status: PageStatus, limit?: number) {
+ return await prisma.page.findMany({ where: { type, status }, take: limit, orderBy: { publishedAt: "desc" }, });
+}
+
+export async function getPageById(id: string) {
+ return await prisma.page.findUnique({ where: { id: id } });
+}
+
+export async function getPageBySlug(slug: string) {
+ return await prisma.page.findUnique({ where: { slug } });
+}
+
+export async function createPage(slug: string, title: string, type: PageType, status: PageStatus, blocks: Block[], meta?: PageMeta) {
+ const user = await getCurrentUser();
+ if (!user) {
+ throw new Error("Failed to fetch user");
+ }
+
+ if (!user.isAdmin) {
+ throw new Error("Access denied")
+ }
+
+ const existingPage = await prisma.page.findUnique({ where: { slug } });
+ if (existingPage) {
+ throw new Error("Page already exists");
+ }
+
+ const page = await prisma.page.create({
+ data: {
+ slug,
+ title,
+ type,
+ status,
+ meta: meta ?? {},
+ publishedAt: status === "PUBLISHED" ? new Date() : null,
+ createdBy: user.id,
+ },
+ });
+
+ if (blocks.length > 0) {
+ await prisma.block.createMany({
+ data: blocks.map((block) => ({
+ pageId: page.id,
+ parentId: block.parentId,
+ type: block.type,
+ position: block.position,
+ content: block.content,
+ })),
+ });
+ }
+
+ if (status === "PUBLISHED") {
+ await prisma.pageVersion.create({
+ data: {
+ pageId: page.id,
+ title: page.title,
+ blocks: blocks,
+ createdBy: user.id,
+ }
+ });
+ }
+
+ return page;
+}
+
+export async function restoreVersion(pageId: string, versionId: string) {
+ const version = await prisma.pageVersion.findUnique({
+ where: { id: versionId }
+ });
+
+ await prisma.$transaction([
+ prisma.block.deleteMany({ where: { pageId } }),
+ prisma.block.createMany({
+ data: (version?.blocks as Block[]).map(block => ({
+ ...block,
+ pageId,
+ id: crypto.randomUUID(),
+ }))
+ }),
+ prisma.page.update({
+ where: { id: pageId },
+ data: { updatedAt: new Date() }
+ })
+ ]);
+}
+
+export async function updatePage(
+ id: string,
+ title: string,
+ status: PageStatus,
+ blocks: Block[],
+ meta?: PageMeta
+) {
+ const user = await getCurrentUser();
+ if (!user?.isAdmin) throw new Error("Access denied");
+
+ const page = await prisma.page.update({
+ where: { id },
+ data: {
+ title,
+ status,
+ meta: meta ?? {},
+ publishedAt: status === "PUBLISHED" ? new Date() : undefined,
+ updatedAt: new Date(),
+ },
+ });
+
+ await prisma.$transaction([
+ prisma.block.deleteMany({ where: { pageId: id } }),
+ ...(blocks.length > 0
+ ? [prisma.block.createMany({
+ data: blocks.map((b) => ({
+ pageId: id,
+ parentId: b.parentId,
+ type: b.type,
+ position: b.position,
+ content: b.content as any,
+ })),
+ })]
+ : []),
+ ]);
+
+ if (status === "PUBLISHED") {
+ await prisma.pageVersion.create({
+ data: {
+ pageId: id,
+ title: page.title,
+ blocks: blocks as any,
+ createdBy: user.id,
+ },
+ });
+ }
+
+ return page;
+}
+
+export async function deletePage(id: string) {
+ const user = await getCurrentUser();
+ if (!user?.isAdmin) throw new Error("Access denied");
+ await prisma.page.delete({ where: { id } });
+}
+
+export async function getBlocksByPageId(pageId: string) {
+ return prisma.block.findMany({
+ where: { pageId },
+ orderBy: { position: "asc" },
+ });
+}
\ No newline at end of file
diff --git a/lib/pages/types.ts b/lib/pages/types.ts
new file mode 100644
index 0000000..b41cca3
--- /dev/null
+++ b/lib/pages/types.ts
@@ -0,0 +1,56 @@
+export const PAGE_TYPES = ["NEWS"] as const;
+export type PageType = typeof PAGE_TYPES[number];
+
+export const PAGE_STATUSES = ["DRAFT", "PUBLISHED", "ARCHIVED"] as const;
+export type PageStatus = typeof PAGE_STATUSES[number];
+
+export type PageMeta = {
+ tags?: string[];
+ location?: string;
+}
+
+export type Page = {
+ id: string;
+ slug: string;
+ title: string;
+ type: PageType;
+ status: PageStatus;
+ meta: PageMeta;
+ createdAt: Date;
+ updatedAt: Date;
+ publishedAt: Date | null;
+ createdBy: string;
+}
+
+export const BLOCK_TYPES = ["PARAGRAPH", "HEADING", "IMAGE", "FILE", "QUOTE", "DIVIDER", "TABLE", "CALLOUT", "LIST", "LINK"] as const;
+export type BlockType = typeof BLOCK_TYPES[number];
+
+export type BlockContent =
+ | { type: "PARAGRAPH"; text: string }
+ | { type: "HEADING"; text: string; level: 1 | 2 | 3 }
+ | { type: "IMAGE"; url: string; caption?: string }
+ | { type: "FILE"; url: string; name: string }
+ | { type: "QUOTE"; text: string; author?: string }
+ | { type: "DIVIDER" }
+ | { type: "TABLE"; headers: string[]; rows: string[][] }
+ | { type: "CALLOUT"; text: string; icon?: string; color?: string }
+ | { type: "LIST"; style: "BULLET" | "NUMBERED"; items: string[] }
+ | { type: "LINK"; text?: string; url: string };
+
+export type Block = {
+ id: string;
+ pageId: string;
+ parentId: string | null;
+ type: BlockType;
+ position: number;
+ content: BlockContent;
+}
+
+export type PageVersion = {
+ id: string;
+ pageId: string;
+ title: string;
+ blocks: Block[];
+ createdAt: Date;
+ createdBy: string;
+};
\ No newline at end of file
diff --git a/lib/user/types.ts b/lib/user/types.ts
index 4da2b3c..be7f0de 100644
--- a/lib/user/types.ts
+++ b/lib/user/types.ts
@@ -5,4 +5,5 @@ export type UserData = {
secondName: string;
sex: string;
birthDate: string;
+ isAdmin: boolean;
}
\ No newline at end of file
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index a2cef45..edb2e43 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -13,13 +13,73 @@ datasource db {
}
model User {
- id String @id @default(uuid())
- kotosoftId String @unique
- email String @unique
- firstName String
- secondName String
- sex String
- birthDate DateTime
-
- createdAt DateTime @default(now())
+ id String @id @default(uuid())
+ kotosoftId String @unique
+ email String @unique
+ firstName String
+ secondName String
+ sex String
+ birthDate DateTime
+ createdAt DateTime @default(now())
+ isAdmin Boolean @default(false)
+
+ pages Page[]
+ versions PageVersion[]
+}
+
+enum PageStatus {
+ DRAFT
+ PUBLISHED
+ ARCHIVED
+}
+
+enum PageType {
+ NEWS
+}
+
+model Page {
+ id String @id @default(uuid())
+ slug String @unique
+ title String
+ type PageType
+ status PageStatus @default(DRAFT)
+ meta Json @default("{}")
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ publishedAt DateTime?
+
+ createdBy String
+ author User @relation(fields: [createdBy], references: [id])
+
+ blocks Block[]
+ versions PageVersion[]
+}
+
+model Block {
+ id String @id @default(uuid())
+ pageId String
+ page Page @relation(fields: [pageId], references: [id], onDelete: Cascade)
+
+ parentId String?
+ parent Block? @relation("BlockChildren", fields: [parentId], references: [id])
+ children Block[] @relation("BlockChildren")
+
+ type String
+ position Float
+ content Json
+
+ @@index([pageId, position])
+}
+
+model PageVersion {
+ id String @id @default(uuid())
+ pageId String
+ page Page @relation(fields: [pageId], references: [id], onDelete: Cascade)
+
+ title String
+ blocks Json
+
+ createdAt DateTime @default(now())
+ createdBy String
+ author User @relation(fields: [createdBy], references: [id])
}
\ No newline at end of file
diff --git a/todo b/todo
new file mode 100644
index 0000000..3793b7f
--- /dev/null
+++ b/todo
@@ -0,0 +1,42 @@
+Я разрабатываю сайт государства "European Federation" на Next.js (App Router) + Prisma + Postgres + Tailwind + Shadcn UI.
+
+Это CMS с универсальными "страницами" (тип: NEWS, LAW, DEPARTMENT, FAQ, STATIC).
+Каждая страница состоит из блоков (PARAGRAPH, HEADING, IMAGE, QUOTE, CALLOUT, DIVIDER, LIST, TABLE).
+
+Схема БД (Prisma):
+- User { id, kotosoftId, email, firstName, secondName, sex, birthDate, isAdmin }
+- Page { id, slug, title, type, status (DRAFT/PUBLISHED/ARCHIVED), meta (Json), publishedAt, createdAt, updatedAt, createdBy }
+- Block { id, pageId, parentId, type, position (Float), content (Json) }
+- PageVersion { id, pageId, title, blocks (Json snapshot), createdAt, createdBy }
+
+TypeScript типы:
+- PageType = "NEWS" | "LAW" | "DEPARTMENT" | "FAQ" | "STATIC"
+- PageStatus = "DRAFT" | "PUBLISHED" | "ARCHIVED"
+- BlockContent = discriminated union по type
+- PageMeta = { description?, ogImage?, location?, tags?, coverUrl?, lawNumber?, signedAt? }
+
+Архитектура:
+- /[slug] — публичная страница (SSR), время редактирования видно всем
+- /[slug]/edit — редактор (только isAdmin), Server Actions для save/publish
+- /pages — список черновиков в Dialog (только isAdmin)
+- /news, /laws и т.д. — списки по типу
+
+Стилистика (важно соблюдать):
+- p-16 gap-16 на страницах
+- Заголовки: h1/h2 с underline underline-offset-8 decoration-2
+- Hover-анимации: hover:underline или hover:gap-4 duration-200
+- Shadcn компоненты: Field/FieldGroup/FieldSet для форм, InputGroup для инпутов с иконками
+- Без лишних Card/Panel — минималистично
+
+Текущие баги:
+1. Блоки не сохраняются в DRAFT — нужно убрать условие if (status === "PUBLISHED") вокруг createMany
+2. Теги показывают индексы — .map((i, tag) => tag) перепутано, надо .map((tag) => tag)
+3. Даты — .toString() надо заменить на toLocaleDateString("en-GB", {...})
+
+Текущие задачи:
+1. UI везде говорит "news" — нужно сделать type-aware (заголовки, маршруты, тексты)
+2. Дореализовать блоки LIST, TABLE, IMAGE в Editor (сейчас "coming soon")
+3. UI истории версий в редакторе — список версий, кнопка "restore"
+4. On-demand ISR через revalidatePath при публикации (уже частично есть)
+
+Цель: чистый, человеческий, безопасный код без бойлерплейта.
\ No newline at end of file