create category dialog

This commit is contained in:
shrt 2025-03-08 12:48:18 +01:00
parent dd3c321350
commit 66aadfd04d
19 changed files with 535 additions and 25 deletions

View File

@ -1,3 +1,6 @@
https://docs.google.com/document/d/1z1sCHzXE0cN2vAPtI4rkddCkIfzXs2ihKtYowZ9JjBw/edit?usp=sharing
# Create T3 App # Create T3 App
This is a [T3 Stack](https://create.t3.gg/) project bootstrapped with `create-t3-app`. This is a [T3 Stack](https://create.t3.gg/) project bootstrapped with `create-t3-app`.

12
docs/start.md Normal file
View File

@ -0,0 +1,12 @@
# Docs
### How things are
##### Images
Stored in public subfolder "/uploads"
### How things cahnge if ...
##### Images
Cloudeflare R2 with custom domain

View File

@ -0,0 +1,17 @@
import { Article } from "@/server/db/schema";
import Link from "next/link";
import React from "react";
function ArticleCard({
title,
slug,
createdAt,
}: Pick<Article, "title" | "slug" | "createdAt">) {
return (
<Link href={`/artikel/${slug}`}>
<div className="rounded-md border p-4">{title}</div>
</Link>
);
}
export default ArticleCard;

View File

@ -47,7 +47,7 @@ function CreateArticleDialog() {
return ( return (
<Dialog open={open} onOpenChange={setOpen}> <Dialog open={open} onOpenChange={setOpen}>
<Button asChild> <Button asChild>
<DialogTrigger>Artikel Erstellen</DialogTrigger> <DialogTrigger className="w-full">Artikel Erstellen</DialogTrigger>
</Button> </Button>
<DialogContent> <DialogContent>
<DialogHeader> <DialogHeader>

View File

@ -0,0 +1,17 @@
import { Category } from "@/server/db/schema";
import Link from "next/link";
import React from "react";
function CategoryCard({
name,
slug,
createdAt,
}: Pick<Category, "name" | "slug" | "createdAt">) {
return (
<Link href={`/kategorie/${slug}`}>
<div className="rounded-md border p-4">{name}</div>
</Link>
);
}
export default CategoryCard;

View File

@ -0,0 +1,81 @@
"use client";
import React from "react";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { Button } from "@/components/ui/button";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { categorySchema } from "@/lib/validation/zod/category";
import { createCategory } from "@/server/actions/category";
const formSchema = categorySchema.pick({
name: true,
});
function CreateCategoryDialog() {
const [open, setOpen] = React.useState<boolean>(false);
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
name: "",
},
});
// 2. Define a submit handler.
async function onSubmit(values: z.infer<typeof formSchema>) {
setOpen(false);
await createCategory(values);
}
return (
<Dialog open={open} onOpenChange={setOpen}>
<Button asChild>
<DialogTrigger className="w-full">Kategorie Erstellen</DialogTrigger>
</Button>
<DialogContent>
<DialogHeader>
<DialogTitle>Neue Kategorie Erstellen</DialogTitle>
<DialogDescription></DialogDescription>
</DialogHeader>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel>Name</FormLabel>
<FormControl>
<Input placeholder="Kategorie Name" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit">Artikel Erstellen</Button>
</form>
</Form>
</DialogContent>
</Dialog>
);
}
export default CreateCategoryDialog;

View File

@ -0,0 +1,45 @@
import React from "react";
import { api } from "@/trpc/server";
import { Card, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
const StatCard = ({
title,
value,
children,
}: {
title: string;
value: string;
children?: React.ReactNode;
}) => {
return (
<Card className="w-full max-w-64">
<CardHeader className="">
<span className="text-4xl font-bold leading-5">{value}</span>
<CardTitle className="text-2xl">{title}</CardTitle>
</CardHeader>
{children && <CardFooter className="pb-2">{children}</CardFooter>}
</Card>
);
};
async function GlobalStats() {
const articleCount = await api.article.getCount();
const authorCount = await api.author.getCount();
const categoryCount = await api.category.getCount();
return (
<div className="flex w-full gap-4">
<StatCard title="Artikel" value={String(articleCount)}>
{/* <Button
variant={"link"}
className="ml-auto px-1 py-px text-muted-foreground"
>
Alle Artikel
</Button> */}
</StatCard>
<StatCard title="Kategorien" value={String(categoryCount)} />
<StatCard title="Autoren" value={String(authorCount)} />
</div>
);
}
export default GlobalStats;

View File

@ -1,8 +1,61 @@
import BreadNavigator from "@/components/bread-navigator";
import { Button } from "@/components/ui/button";
import { hasPermission, Role } from "@/lib/validation/permissions";
import { auth } from "@/server/auth";
import { api } from "@/trpc/server";
import { Edit } from "lucide-react";
import { notFound } from "next/navigation";
import React from "react"; import React from "react";
import ArticleCard from "../../_components/article/article-card";
async function Page({ params }: { params: Promise<{ name: string }> }) { async function Page({ params }: { params: Promise<{ name: string }> }) {
const { name } = await params; const { name } = await params;
return <div>Kategorie {name}</div>; const category = await api.category.get({ slug: name });
if (!category) return notFound();
const articles = await api.article.getAll({ categoryId: category.id });
const session = await auth();
const isEditor = session?.user
? hasPermission(session.user.role, Role.EDITOR)
: false;
return (
<>
<div className="flex items-center justify-between">
<BreadNavigator
links={[
{ label: "Kategorie", href: "/kategorie" },
{
label: name,
href: `/kategorie/${name}`,
},
]}
/>
{isEditor && (
<Button>
<Edit className="size-4" />
<span>Bearbeiten</span>
</Button>
)}
</div>
<h1 className="text-3xl font-bold capitalize">{name}</h1>
<p className="text-muted-foreground">keine Beschreibung</p>
<h3 className="text-2xl font-bold">Artikel</h3>
{articles.length ? (
<menu>
{articles.map((article) => (
<li key={article.slug}>
<ArticleCard {...article} />
</li>
))}
</menu>
) : (
<p className="text-muted-foreground">
Noch keine Artikel in dieser Kategorie.
</p>
)}
</>
);
} }
export default Page; export default Page;

View File

@ -9,7 +9,7 @@ function Layout({ children }: { children: React.ReactNode }) {
<AppSidebar /> <AppSidebar />
<div className="w-full"> <div className="w-full">
<Navbar /> <Navbar />
<main className="p-4">{children}</main> <main className="space-y-4 p-4">{children}</main>
</div> </div>
</SidebarProvider> </SidebarProvider>
); );

View File

@ -1,21 +1,43 @@
import { auth } from "@/server/auth"; import { auth } from "@/server/auth";
import { api } from "@/trpc/server"; import { api } from "@/trpc/server";
import Link from "next/link"; import Link from "next/link";
import GlobalStats from "./_components/global-stats";
import ArticleCard from "./_components/article/article-card";
import CategoryCard from "./_components/category/category-card";
export default async function Home() { export default async function Home() {
const session = await auth(); const session = await auth();
const articles = await api.article.getAllPreviews(); const articles = await api.article.getAllPreviews();
const categories = await api.category.getAll();
return ( return (
<div className=""> <>
<h1 className="text-4xl font-bold">Anti Rechts Wiki</h1> <div className="w-full space-y-1">
<h2 className="text-2xl font-medium">Kategorien</h2>
<menu className="grid grid-cols-1 gap-2 lg:grid-cols-2 xl:grid-cols-3">
{categories.map((category) => (
<li key={category.slug}>
<CategoryCard {...category} />
</li>
))}
</menu>
</div>
{/* <h1 className="text-4xl font-bold">Anti Rechts Wiki</h1> */}
<div className="flex h-64 w-full items-center justify-center rounded-md bg-muted">
<span>Artikel Suche</span>
</div>
<menu> {/* <GlobalStats /> */}
{articles.map((article) => (
<li key={article.slug}> <div className="w-full space-y-1">
<Link href={`/artikel/${article.slug}`}>{article.title}</Link> <h2 className="text-2xl font-medium">Artikel</h2>
</li> <menu className="grid grid-cols-1 gap-2 lg:grid-cols-2">
))} {articles.map((article) => (
</menu> <li key={article.slug}>
</div> <ArticleCard {...article} />
</li>
))}
</menu>
</div>
</>
); );
} }

View File

@ -0,0 +1,42 @@
import React from "react";
import {
Breadcrumb,
BreadcrumbItem,
BreadcrumbLink,
BreadcrumbList,
BreadcrumbPage,
BreadcrumbSeparator,
} from "@/components/ui/breadcrumb";
function BreadNavigator({
links,
}: {
links: { label: string; href: string }[];
}) {
return (
<Breadcrumb>
<BreadcrumbList>
{links.map(({ label, href }, idx) => {
if (idx < links.length - 1)
return (
<React.Fragment key={href}>
<BreadcrumbItem>
<BreadcrumbLink className="capitalize" href={href}>
{label}
</BreadcrumbLink>
</BreadcrumbItem>
<BreadcrumbSeparator />
</React.Fragment>
);
return (
<BreadcrumbItem className="capitalize" key={href}>
<BreadcrumbPage>{label}</BreadcrumbPage>
</BreadcrumbItem>
);
})}
</BreadcrumbList>
</Breadcrumb>
);
}
export default BreadNavigator;

View File

@ -11,6 +11,7 @@ import {
PopoverTrigger, PopoverTrigger,
} from "@/components/ui/popover"; } from "@/components/ui/popover";
import CreateArticleDialog from "@/app/(PAGES)/_components/article/create-article-dialog"; import CreateArticleDialog from "@/app/(PAGES)/_components/article/create-article-dialog";
import CreateCategoryDialog from "@/app/(PAGES)/_components/category/create-category-dialog";
async function Navbar() { async function Navbar() {
const session = await auth(); const session = await auth();
@ -25,11 +26,6 @@ async function Navbar() {
<Input className="w-full max-w-xs" placeholder="Suche..." /> <Input className="w-full max-w-xs" placeholder="Suche..." />
<div className="flex items-center gap-4"> <div className="flex items-center gap-4">
{isAdmin && (
<Button asChild>
<Link href={"/admin"}>Admin Dashboard</Link>
</Button>
)}
{isEditor && ( {isEditor && (
<Popover> <Popover>
<PopoverTrigger asChild> <PopoverTrigger asChild>
@ -42,12 +38,15 @@ async function Navbar() {
// side="left" // side="left"
> >
<CreateArticleDialog /> <CreateArticleDialog />
<Button className="w-full" asChild> <CreateCategoryDialog />
<Link href={"/kategorie/neu"}>Kategorie erstellen</Link>
</Button>
</PopoverContent> </PopoverContent>
</Popover> </Popover>
)} )}
{isAdmin && (
<Button asChild>
<Link href={"/admin"}>Admin Dashboard</Link>
</Button>
)}
{session ? ( {session ? (
<Avatar <Avatar
className="size-8" className="size-8"

View File

@ -0,0 +1,115 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { ChevronRight, MoreHorizontal } from "lucide-react"
import { cn } from "@/lib/utils"
const Breadcrumb = React.forwardRef<
HTMLElement,
React.ComponentPropsWithoutRef<"nav"> & {
separator?: React.ReactNode
}
>(({ ...props }, ref) => <nav ref={ref} aria-label="breadcrumb" {...props} />)
Breadcrumb.displayName = "Breadcrumb"
const BreadcrumbList = React.forwardRef<
HTMLOListElement,
React.ComponentPropsWithoutRef<"ol">
>(({ className, ...props }, ref) => (
<ol
ref={ref}
className={cn(
"flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",
className
)}
{...props}
/>
))
BreadcrumbList.displayName = "BreadcrumbList"
const BreadcrumbItem = React.forwardRef<
HTMLLIElement,
React.ComponentPropsWithoutRef<"li">
>(({ className, ...props }, ref) => (
<li
ref={ref}
className={cn("inline-flex items-center gap-1.5", className)}
{...props}
/>
))
BreadcrumbItem.displayName = "BreadcrumbItem"
const BreadcrumbLink = React.forwardRef<
HTMLAnchorElement,
React.ComponentPropsWithoutRef<"a"> & {
asChild?: boolean
}
>(({ asChild, className, ...props }, ref) => {
const Comp = asChild ? Slot : "a"
return (
<Comp
ref={ref}
className={cn("transition-colors hover:text-foreground", className)}
{...props}
/>
)
})
BreadcrumbLink.displayName = "BreadcrumbLink"
const BreadcrumbPage = React.forwardRef<
HTMLSpanElement,
React.ComponentPropsWithoutRef<"span">
>(({ className, ...props }, ref) => (
<span
ref={ref}
role="link"
aria-disabled="true"
aria-current="page"
className={cn("font-normal text-foreground", className)}
{...props}
/>
))
BreadcrumbPage.displayName = "BreadcrumbPage"
const BreadcrumbSeparator = ({
children,
className,
...props
}: React.ComponentProps<"li">) => (
<li
role="presentation"
aria-hidden="true"
className={cn("[&>svg]:w-3.5 [&>svg]:h-3.5", className)}
{...props}
>
{children ?? <ChevronRight />}
</li>
)
BreadcrumbSeparator.displayName = "BreadcrumbSeparator"
const BreadcrumbEllipsis = ({
className,
...props
}: React.ComponentProps<"span">) => (
<span
role="presentation"
aria-hidden="true"
className={cn("flex h-9 w-9 items-center justify-center", className)}
{...props}
>
<MoreHorizontal className="h-4 w-4" />
<span className="sr-only">More</span>
</span>
)
BreadcrumbEllipsis.displayName = "BreadcrumbElipssis"
export {
Breadcrumb,
BreadcrumbList,
BreadcrumbItem,
BreadcrumbLink,
BreadcrumbPage,
BreadcrumbSeparator,
BreadcrumbEllipsis,
}

View File

@ -0,0 +1,76 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Card = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
"rounded-xl border bg-card text-card-foreground shadow",
className
)}
{...props}
/>
))
Card.displayName = "Card"
const CardHeader = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex flex-col space-y-1.5 p-6", className)}
{...props}
/>
))
CardHeader.displayName = "CardHeader"
const CardTitle = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("font-semibold leading-none tracking-tight", className)}
{...props}
/>
))
CardTitle.displayName = "CardTitle"
const CardDescription = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
CardDescription.displayName = "CardDescription"
const CardContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
))
CardContent.displayName = "CardContent"
const CardFooter = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex items-center p-6 pt-0", className)}
{...props}
/>
))
CardFooter.displayName = "CardFooter"
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }

View File

@ -3,7 +3,6 @@
import { categorySchema } from "@/lib/validation/zod/category"; import { categorySchema } from "@/lib/validation/zod/category";
import { api } from "@/trpc/server"; import { api } from "@/trpc/server";
import { revalidatePath } from "next/cache"; import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { z } from "zod"; import { z } from "zod";
export async function createCategory(category: z.infer<typeof categorySchema>) { export async function createCategory(category: z.infer<typeof categorySchema>) {
@ -11,7 +10,7 @@ export async function createCategory(category: z.infer<typeof categorySchema>) {
category, category,
}); });
if (!result[0]?.slug?.length) return false; if (!result[0]?.slug?.length) return false;
return redirect(`/kategorie/${result[0].slug}/edit`); return revalidatePath("/");
} }
export async function updateCategory( export async function updateCategory(
category: z.infer<typeof categorySchema>, category: z.infer<typeof categorySchema>,

View File

@ -2,6 +2,7 @@ import { articleRouter } from "./routers/article";
import { categoryRouter } from "@/server/api/routers/category"; import { categoryRouter } from "@/server/api/routers/category";
import { createCallerFactory, createTRPCRouter } from "@/server/api/trpc"; import { createCallerFactory, createTRPCRouter } from "@/server/api/trpc";
import { usersRouter } from "./routers/users"; import { usersRouter } from "./routers/users";
import { authorRouter } from "./routers/author";
/** /**
* This is the primary router for your server. * This is the primary router for your server.
@ -12,6 +13,7 @@ export const appRouter = createTRPCRouter({
article: articleRouter, article: articleRouter,
category: categoryRouter, category: categoryRouter,
users: usersRouter, users: usersRouter,
author: authorRouter,
}); });
// export type definition of API // export type definition of API

View File

@ -7,11 +7,12 @@ import {
} from "@/server/api/trpc"; } from "@/server/api/trpc";
import { articles } from "@/server/db/schema"; import { articles } from "@/server/db/schema";
import { articleSchema } from "@/lib/validation/zod/article"; import { articleSchema } from "@/lib/validation/zod/article";
import { eq } from "drizzle-orm"; import { count, eq } from "drizzle-orm";
import { hasPermission, Role } from "@/lib/validation/permissions"; import { hasPermission, Role } from "@/lib/validation/permissions";
import { generateSlug } from "@/lib/utils"; import { generateSlug } from "@/lib/utils";
export const articleRouter = createTRPCRouter({ export const articleRouter = createTRPCRouter({
// queries
get: publicProcedure get: publicProcedure
.input(z.object({ slug: z.string() })) .input(z.object({ slug: z.string() }))
.query(async ({ ctx, input }) => { .query(async ({ ctx, input }) => {
@ -43,6 +44,21 @@ export const articleRouter = createTRPCRouter({
}, },
}); });
}), }),
getCount: publicProcedure
.input(z.object({ categoryId: z.string() }).optional())
.query(async ({ ctx, input }) => {
return (
await ctx.db
.select({ count: count() })
.from(articles)
.where(
input?.categoryId
? eq(articles.categoryId, input.categoryId)
: undefined,
)
)[0]?.count;
}),
// mutations
create: protectedProcedure create: protectedProcedure
.input(z.object({ article: articleSchema })) .input(z.object({ article: articleSchema }))
.mutation(async ({ ctx, input }) => { .mutation(async ({ ctx, input }) => {

View File

@ -0,0 +1,7 @@
import { createTRPCRouter, protectedProcedure, publicProcedure } from "../trpc";
export const authorRouter = createTRPCRouter({
getCount: publicProcedure.query(async ({ ctx }) => {
return 7;
}),
});

View File

@ -6,7 +6,7 @@ import {
} from "@/server/api/trpc"; } from "@/server/api/trpc";
import { categories } from "@/server/db/schema"; import { categories } from "@/server/db/schema";
import { eq } from "drizzle-orm"; import { count, eq } from "drizzle-orm";
import { hasPermission, Role } from "@/lib/validation/permissions"; import { hasPermission, Role } from "@/lib/validation/permissions";
import { categorySchema } from "@/lib/validation/zod/category"; import { categorySchema } from "@/lib/validation/zod/category";
import { generateSlug } from "@/lib/utils"; import { generateSlug } from "@/lib/utils";
@ -24,6 +24,10 @@ export const categoryRouter = createTRPCRouter({
return await ctx.db.query.categories.findMany(); return await ctx.db.query.categories.findMany();
}), }),
getCount: publicProcedure.query(async ({ ctx }) => {
return (await ctx.db.select({ count: count() }).from(categories))[0]?.count;
}),
create: protectedProcedure create: protectedProcedure
.input(z.object({ category: categorySchema })) .input(z.object({ category: categorySchema }))
.mutation(async ({ ctx, input }) => { .mutation(async ({ ctx, input }) => {