adsdasd
This commit is contained in:
@@ -1,203 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { clientFetch } from "@/lib/api";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { ImageUploader } from "@/components/dashboard/image-uploader";
|
||||
import { Loader2, PlusCircle } from "lucide-react";
|
||||
import { PostStatus, ContentFormat, UserRole } from "@/lib/types";
|
||||
|
||||
interface Props {
|
||||
userRole: UserRole;
|
||||
onCreated: () => void;
|
||||
}
|
||||
|
||||
export function CreatePostForm({ userRole, onCreated }: Props) {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [status, setStatus] = useState<PostStatus>(PostStatus.DRAFT);
|
||||
const [contentFormat, setContentFormat] = useState<ContentFormat>(
|
||||
ContentFormat.MARKDOWN
|
||||
);
|
||||
const [isFeatured, setIsFeatured] = useState("false");
|
||||
|
||||
// Controlled image state (ImageUploader is not a native input element)
|
||||
const [featuredImageUrl, setFeaturedImageUrl] = useState("");
|
||||
const [featuredImageAlt, setFeaturedImageAlt] = useState("");
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
const fd = new FormData(e.currentTarget);
|
||||
const body = {
|
||||
title: fd.get("title"),
|
||||
slug: fd.get("slug") || undefined,
|
||||
excerpt: fd.get("excerpt") || undefined,
|
||||
content: fd.get("content"),
|
||||
contentFormat,
|
||||
status: userRole === UserRole.ADMIN ? status : PostStatus.DRAFT,
|
||||
isFeatured: isFeatured === "true",
|
||||
categories: fd.get("categories") || undefined,
|
||||
tags: fd.get("tags") || undefined,
|
||||
// image values come from controlled state, not FormData
|
||||
featuredImageUrl: featuredImageUrl || undefined,
|
||||
featuredImageAlt: featuredImageAlt || undefined,
|
||||
};
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
await clientFetch("/blog-posts", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
toast.success("Post created!");
|
||||
(e.target as HTMLFormElement).reset();
|
||||
// Reset controlled image state
|
||||
setFeaturedImageUrl("");
|
||||
setFeaturedImageAlt("");
|
||||
onCreated();
|
||||
} catch (err: unknown) {
|
||||
toast.error(err instanceof Error ? err.message : "Failed to create post");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="space-y-4 rounded-xl border bg-muted/30 p-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="font-semibold flex items-center gap-2">
|
||||
<PlusCircle className="h-4 w-4" /> Create New Post
|
||||
</h3>
|
||||
{userRole !== UserRole.ADMIN && (
|
||||
<span className="text-xs text-muted-foreground border rounded-full px-2 py-0.5">
|
||||
Status forced to Draft (Manager)
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="cp-title">Title *</Label>
|
||||
<Input id="cp-title" name="title" placeholder="Post title" required />
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="cp-slug">Slug (optional)</Label>
|
||||
<Input id="cp-slug" name="slug" placeholder="custom-slug" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="cp-excerpt">Excerpt</Label>
|
||||
<Textarea
|
||||
id="cp-excerpt"
|
||||
name="excerpt"
|
||||
placeholder="Short description…"
|
||||
rows={2}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="cp-content">Content *</Label>
|
||||
<Textarea
|
||||
id="cp-content"
|
||||
name="content"
|
||||
placeholder="Write your post content…"
|
||||
rows={8}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
<div className="space-y-1">
|
||||
<Label>Format</Label>
|
||||
<Select
|
||||
value={contentFormat}
|
||||
onValueChange={(v) => setContentFormat(v as ContentFormat)}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value={ContentFormat.MARKDOWN}>Markdown</SelectItem>
|
||||
<SelectItem value={ContentFormat.HTML}>HTML</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{userRole === UserRole.ADMIN && (
|
||||
<>
|
||||
<div className="space-y-1">
|
||||
<Label>Status</Label>
|
||||
<Select
|
||||
value={status}
|
||||
onValueChange={(v) => setStatus(v as PostStatus)}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value={PostStatus.DRAFT}>Draft</SelectItem>
|
||||
<SelectItem value={PostStatus.PUBLISHED}>Published</SelectItem>
|
||||
<SelectItem value={PostStatus.ARCHIVED}>Archived</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label>Featured</Label>
|
||||
<Select value={isFeatured} onValueChange={setIsFeatured}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="false">Not featured</SelectItem>
|
||||
<SelectItem value="true">Featured</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="cp-categories">Categories (comma separated)</Label>
|
||||
<Input
|
||||
id="cp-categories"
|
||||
name="categories"
|
||||
placeholder="backend,api"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="cp-tags">Tags (comma separated)</Label>
|
||||
<Input id="cp-tags" name="tags" placeholder="rest,pagination" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ── Featured image upload ─────────────────────────────────────────── */}
|
||||
<ImageUploader
|
||||
value={featuredImageUrl}
|
||||
onChange={setFeaturedImageUrl}
|
||||
altValue={featuredImageAlt}
|
||||
onAltChange={setFeaturedImageAlt}
|
||||
label="Featured Image"
|
||||
/>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<Button type="submit" disabled={loading}>
|
||||
{loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
Create Post
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
373
frontend/app/dashboard/components/post-sheet.tsx
Normal file
373
frontend/app/dashboard/components/post-sheet.tsx
Normal file
@@ -0,0 +1,373 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { clientFetch } from "@/lib/api";
|
||||
import { toast } from "sonner";
|
||||
import { BlogPost, PostStatus, ContentFormat, UserRole } from "@/lib/types";
|
||||
import { TiptapEditor } from "@/components/dashboard/tiptap-editor";
|
||||
import { ImageUploader } from "@/components/dashboard/image-uploader";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetDescription,
|
||||
} from "@/components/ui/sheet";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { Loader2, FileText, Settings2 } from "lucide-react";
|
||||
|
||||
interface Props {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
/** If provided, the sheet is in edit mode. Otherwise, create mode. */
|
||||
post?: BlogPost | null;
|
||||
userRole: UserRole;
|
||||
onSuccess: () => void;
|
||||
}
|
||||
|
||||
const defaultStatus = (role: UserRole): PostStatus =>
|
||||
role === UserRole.ADMIN ? PostStatus.PUBLISHED : PostStatus.DRAFT;
|
||||
|
||||
export function PostSheet({ open, onOpenChange, post, userRole, onSuccess }: Props) {
|
||||
const isEdit = !!post;
|
||||
|
||||
/* ── form state ─────────────────────────────────────────────────────────── */
|
||||
const [title, setTitle] = useState("");
|
||||
const [slug, setSlug] = useState("");
|
||||
const [excerpt, setExcerpt] = useState("");
|
||||
const [content, setContent] = useState("");
|
||||
const [contentFormat, setContentFormat] = useState<ContentFormat>(ContentFormat.HTML);
|
||||
const [status, setStatus] = useState<PostStatus>(defaultStatus(userRole));
|
||||
const [isFeatured, setIsFeatured] = useState(false);
|
||||
const [categories, setCategories] = useState("");
|
||||
const [tags, setTags] = useState("");
|
||||
const [imageUrl, setImageUrl] = useState("");
|
||||
const [imageAlt, setImageAlt] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
/* ── populate when sheet opens ──────────────────────────────────────────── */
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
if (post) {
|
||||
setTitle(post.title);
|
||||
setSlug(post.slug);
|
||||
setExcerpt(post.excerpt ?? "");
|
||||
setContent(post.content ?? "");
|
||||
setContentFormat(post.contentFormat);
|
||||
setStatus(post.status);
|
||||
setIsFeatured(post.isFeatured);
|
||||
setCategories(post.categories.join(","));
|
||||
setTags(post.tags.join(","));
|
||||
setImageUrl(post.featuredImageUrl ?? "");
|
||||
setImageAlt(post.featuredImageAlt ?? "");
|
||||
} else {
|
||||
setTitle("");
|
||||
setSlug("");
|
||||
setExcerpt("");
|
||||
setContent("");
|
||||
setContentFormat(ContentFormat.HTML);
|
||||
setStatus(defaultStatus(userRole));
|
||||
setIsFeatured(false);
|
||||
setCategories("");
|
||||
setTags("");
|
||||
setImageUrl("");
|
||||
setImageAlt("");
|
||||
}
|
||||
}, [open, post, userRole]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!content || content === "<p></p>") {
|
||||
toast.error("Content cannot be empty.");
|
||||
return;
|
||||
}
|
||||
|
||||
const body = {
|
||||
title: title.trim(),
|
||||
slug: slug.trim() || undefined,
|
||||
excerpt: excerpt.trim() || undefined,
|
||||
content,
|
||||
contentFormat,
|
||||
status: userRole !== UserRole.ADMIN ? PostStatus.DRAFT : status,
|
||||
isFeatured,
|
||||
categories: categories.trim() || undefined,
|
||||
tags: tags.trim() || undefined,
|
||||
featuredImageUrl: imageUrl || undefined,
|
||||
featuredImageAlt: imageAlt || undefined,
|
||||
};
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
if (isEdit && post) {
|
||||
await clientFetch(`/blog-posts/${post.id}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
toast.success("Post updated!");
|
||||
} else {
|
||||
await clientFetch("/blog-posts", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
toast.success("Post created!");
|
||||
}
|
||||
onOpenChange(false);
|
||||
onSuccess();
|
||||
} catch (err: unknown) {
|
||||
toast.error(err instanceof Error ? err.message : "Something went wrong");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const statusColor: Record<PostStatus, string> = {
|
||||
[PostStatus.PUBLISHED]: "text-emerald-600",
|
||||
[PostStatus.DRAFT]: "text-zinc-500",
|
||||
[PostStatus.ARCHIVED]: "text-amber-600",
|
||||
};
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={onOpenChange}>
|
||||
{/* Wide sheet — takes 60% of screen on large displays */}
|
||||
<SheetContent
|
||||
side="right"
|
||||
className="w-full sm:max-w-2xl lg:max-w-3xl flex flex-col p-0 gap-0"
|
||||
>
|
||||
{/* ── Sheet header ──────────────────────────────────────────────────── */}
|
||||
<SheetHeader className="px-6 py-4 border-b shrink-0">
|
||||
<SheetTitle className="flex items-center gap-2">
|
||||
<FileText className="h-4 w-4 text-muted-foreground" />
|
||||
{isEdit ? "Edit Post" : "New Post"}
|
||||
</SheetTitle>
|
||||
<SheetDescription>
|
||||
{isEdit
|
||||
? `Editing "${post?.title}"`
|
||||
: "Fill in the details below and hit Publish (or save as Draft)."}
|
||||
</SheetDescription>
|
||||
</SheetHeader>
|
||||
|
||||
{/* ── Scrollable form body ──────────────────────────────────────────── */}
|
||||
<form
|
||||
id="post-sheet-form"
|
||||
onSubmit={handleSubmit}
|
||||
className="flex-1 overflow-y-auto"
|
||||
>
|
||||
<div className="px-6 py-5 space-y-5">
|
||||
|
||||
{/* Title + Slug */}
|
||||
<div className="space-y-3">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="ps-title">
|
||||
Title <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="ps-title"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
placeholder="My awesome post"
|
||||
required
|
||||
className="text-base font-medium"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="ps-slug" className="text-muted-foreground text-xs">
|
||||
Slug <span className="text-muted-foreground/60">(auto-generated if empty)</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="ps-slug"
|
||||
value={slug}
|
||||
onChange={(e) => setSlug(e.target.value)}
|
||||
placeholder="my-awesome-post"
|
||||
className="font-mono text-xs"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Content editor */}
|
||||
<div className="space-y-1.5">
|
||||
<Label>
|
||||
Content <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<TiptapEditor
|
||||
value={content}
|
||||
onChange={setContent}
|
||||
placeholder="Write your post content here…"
|
||||
minHeight="340px"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Excerpt */}
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="ps-excerpt">Excerpt</Label>
|
||||
<Textarea
|
||||
id="ps-excerpt"
|
||||
value={excerpt}
|
||||
onChange={(e) => setExcerpt(e.target.value)}
|
||||
placeholder="A short description shown in post listings…"
|
||||
rows={2}
|
||||
className="resize-none"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Settings row */}
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center gap-1.5 text-sm font-medium text-muted-foreground">
|
||||
<Settings2 className="h-3.5 w-3.5" />
|
||||
Post settings
|
||||
</div>
|
||||
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
{/* Status — admin only */}
|
||||
{userRole === UserRole.ADMIN ? (
|
||||
<div className="space-y-1.5">
|
||||
<Label>Status</Label>
|
||||
<Select
|
||||
value={status}
|
||||
onValueChange={(v) => setStatus(v as PostStatus)}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value={PostStatus.DRAFT}>
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="h-2 w-2 rounded-full bg-zinc-400" />
|
||||
Draft
|
||||
</span>
|
||||
</SelectItem>
|
||||
<SelectItem value={PostStatus.PUBLISHED}>
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="h-2 w-2 rounded-full bg-emerald-500" />
|
||||
Published
|
||||
</span>
|
||||
</SelectItem>
|
||||
<SelectItem value={PostStatus.ARCHIVED}>
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="h-2 w-2 rounded-full bg-amber-500" />
|
||||
Archived
|
||||
</span>
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-muted-foreground">Status</Label>
|
||||
<div className="flex h-9 items-center text-sm text-muted-foreground border rounded-md px-3">
|
||||
Saved as Draft (Manager)
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Format */}
|
||||
<div className="space-y-1.5">
|
||||
<Label>Content format</Label>
|
||||
<Select
|
||||
value={contentFormat}
|
||||
onValueChange={(v) => setContentFormat(v as ContentFormat)}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value={ContentFormat.HTML}>HTML (Tiptap)</SelectItem>
|
||||
<SelectItem value={ContentFormat.MARKDOWN}>Markdown</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Categories + Tags */}
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="ps-cats">Categories</Label>
|
||||
<Input
|
||||
id="ps-cats"
|
||||
value={categories}
|
||||
onChange={(e) => setCategories(e.target.value)}
|
||||
placeholder="tech, tutorials"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="ps-tags">Tags</Label>
|
||||
<Input
|
||||
id="ps-tags"
|
||||
value={tags}
|
||||
onChange={(e) => setTags(e.target.value)}
|
||||
placeholder="nextjs, react"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Featured toggle */}
|
||||
{userRole === UserRole.ADMIN && (
|
||||
<div className="flex items-center justify-between rounded-lg border px-4 py-3">
|
||||
<div>
|
||||
<p className="text-sm font-medium">Featured post</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Shown in the hero/featured section on the home page
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={isFeatured}
|
||||
onCheckedChange={setIsFeatured}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Featured image */}
|
||||
<ImageUploader
|
||||
value={imageUrl}
|
||||
onChange={setImageUrl}
|
||||
altValue={imageAlt}
|
||||
onAltChange={setImageAlt}
|
||||
label="Featured Image"
|
||||
/>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{/* ── Sticky footer ────────────────────────────────────────────────── */}
|
||||
<div className="border-t px-6 py-4 flex items-center justify-between gap-3 bg-background shrink-0">
|
||||
{isEdit && (
|
||||
<span className={`text-xs font-medium capitalize ${statusColor[status]}`}>
|
||||
● {status}
|
||||
</span>
|
||||
)}
|
||||
<div className="flex gap-2 ml-auto">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => onOpenChange(false)}
|
||||
disabled={loading}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" form="post-sheet-form" disabled={loading}>
|
||||
{loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
{isEdit ? "Save changes" : status === PostStatus.PUBLISHED ? "Publish" : "Save Draft"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -3,19 +3,11 @@
|
||||
import { useState, useCallback } from "react";
|
||||
import { clientFetch } from "@/lib/api";
|
||||
import { toast } from "sonner";
|
||||
import { BlogPost, PostStatus, ContentFormat, UserRole } from "@/lib/types";
|
||||
import { CreatePostForm } from "./create-post-form";
|
||||
import { BlogPost, PostStatus, UserRole } from "@/lib/types";
|
||||
import { PostSheet } from "./post-sheet";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
@@ -27,8 +19,16 @@ import {
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { ImageUploader } from "@/components/dashboard/image-uploader";
|
||||
import { Eye, Loader2, Pencil, Trash2, X, Check, ExternalLink } from "lucide-react";
|
||||
import {
|
||||
Eye,
|
||||
Loader2,
|
||||
Pencil,
|
||||
Trash2,
|
||||
PlusCircle,
|
||||
ExternalLink,
|
||||
Star,
|
||||
Search,
|
||||
} from "lucide-react";
|
||||
import Link from "next/link";
|
||||
|
||||
interface Props {
|
||||
@@ -36,17 +36,30 @@ interface Props {
|
||||
userRole: UserRole;
|
||||
}
|
||||
|
||||
/** Per-post edit image state so each inline form has its own uploader values. */
|
||||
interface EditImageState {
|
||||
url: string;
|
||||
alt: string;
|
||||
}
|
||||
const statusMeta: Record<PostStatus, { label: string; dot: string; row: string }> = {
|
||||
[PostStatus.PUBLISHED]: {
|
||||
label: "Published",
|
||||
dot: "bg-emerald-500",
|
||||
row: "border-l-emerald-400",
|
||||
},
|
||||
[PostStatus.DRAFT]: {
|
||||
label: "Draft",
|
||||
dot: "bg-zinc-400",
|
||||
row: "border-l-zinc-300",
|
||||
},
|
||||
[PostStatus.ARCHIVED]: {
|
||||
label: "Archived",
|
||||
dot: "bg-amber-400",
|
||||
row: "border-l-amber-400",
|
||||
},
|
||||
};
|
||||
|
||||
export function PostsTable({ initialPosts, userRole }: Props) {
|
||||
const [posts, setPosts] = useState<BlogPost[]>(initialPosts);
|
||||
const [editingId, setEditingId] = useState<string | null>(null);
|
||||
const [editImage, setEditImage] = useState<EditImageState>({ url: "", alt: "" });
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [sheetOpen, setSheetOpen] = useState(false);
|
||||
const [editingPost, setEditingPost] = useState<BlogPost | null>(null);
|
||||
const [deletingId, setDeletingId] = useState<string | null>(null);
|
||||
const [search, setSearch] = useState("");
|
||||
|
||||
const refreshPosts = useCallback(async () => {
|
||||
try {
|
||||
@@ -59,16 +72,18 @@ export function PostsTable({ initialPosts, userRole }: Props) {
|
||||
}
|
||||
}, []);
|
||||
|
||||
const startEditing = (post: BlogPost) => {
|
||||
setEditingId(post.id);
|
||||
setEditImage({
|
||||
url: post.featuredImageUrl || "",
|
||||
alt: post.featuredImageAlt || "",
|
||||
});
|
||||
const openCreate = () => {
|
||||
setEditingPost(null);
|
||||
setSheetOpen(true);
|
||||
};
|
||||
|
||||
const openEdit = (post: BlogPost) => {
|
||||
setEditingPost(post);
|
||||
setSheetOpen(true);
|
||||
};
|
||||
|
||||
const handleDelete = async (id: string) => {
|
||||
setLoading(true);
|
||||
setDeletingId(id);
|
||||
try {
|
||||
await clientFetch(`/blog-posts/${id}`, { method: "DELETE" });
|
||||
toast.success("Post deleted.");
|
||||
@@ -76,249 +91,203 @@ export function PostsTable({ initialPosts, userRole }: Props) {
|
||||
} catch (err: unknown) {
|
||||
toast.error(err instanceof Error ? err.message : "Delete failed");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setDeletingId(null);
|
||||
}
|
||||
};
|
||||
|
||||
const handleUpdate = async (
|
||||
e: React.FormEvent<HTMLFormElement>,
|
||||
id: string
|
||||
) => {
|
||||
e.preventDefault();
|
||||
const fd = new FormData(e.currentTarget);
|
||||
const body: Record<string, unknown> = {
|
||||
title: fd.get("title"),
|
||||
slug: fd.get("slug") || undefined,
|
||||
excerpt: fd.get("excerpt") || undefined,
|
||||
content: fd.get("content"),
|
||||
contentFormat: fd.get("contentFormat"),
|
||||
status: fd.get("status"),
|
||||
isFeatured: fd.get("isFeatured") === "true",
|
||||
categories: fd.get("categories") || undefined,
|
||||
tags: fd.get("tags") || undefined,
|
||||
// Image comes from controlled ImageUploader state
|
||||
featuredImageUrl: editImage.url || undefined,
|
||||
featuredImageAlt: editImage.alt || undefined,
|
||||
};
|
||||
setLoading(true);
|
||||
try {
|
||||
await clientFetch(`/blog-posts/${id}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
toast.success("Post updated!");
|
||||
setEditingId(null);
|
||||
await refreshPosts();
|
||||
} catch (err: unknown) {
|
||||
toast.error(err instanceof Error ? err.message : "Update failed");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
const canEdit = userRole === UserRole.ADMIN;
|
||||
const canCreate = userRole === UserRole.ADMIN || userRole === UserRole.MANAGER;
|
||||
|
||||
const statusColor: Record<PostStatus, string> = {
|
||||
[PostStatus.PUBLISHED]: "bg-emerald-100 text-emerald-800 border-emerald-200",
|
||||
[PostStatus.DRAFT]: "bg-zinc-100 text-zinc-700 border-zinc-200",
|
||||
[PostStatus.ARCHIVED]: "bg-amber-100 text-amber-800 border-amber-200",
|
||||
};
|
||||
const filtered = search.trim()
|
||||
? posts.filter(
|
||||
(p) =>
|
||||
p.title.toLowerCase().includes(search.toLowerCase()) ||
|
||||
p.slug.toLowerCase().includes(search.toLowerCase())
|
||||
)
|
||||
: posts;
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Create form for ADMIN/MANAGER */}
|
||||
{(userRole === UserRole.ADMIN || userRole === UserRole.MANAGER) && (
|
||||
<CreatePostForm userRole={userRole} onCreated={refreshPosts} />
|
||||
)}
|
||||
<>
|
||||
{/* ── Toolbar ───────────────────────────────────────────────────────── */}
|
||||
<div className="flex flex-wrap items-center justify-between gap-3 mb-4">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search posts…"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="pl-8 h-8 w-56 text-sm"
|
||||
/>
|
||||
</div>
|
||||
{canCreate && (
|
||||
<Button size="sm" onClick={openCreate} className="gap-1.5">
|
||||
<PlusCircle className="h-4 w-4" />
|
||||
New Post
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Posts list */}
|
||||
{posts.length === 0 ? (
|
||||
<div className="rounded-xl border border-dashed p-8 text-center text-sm text-muted-foreground">
|
||||
No posts yet.
|
||||
{/* ── Posts list ────────────────────────────────────────────────────── */}
|
||||
{filtered.length === 0 ? (
|
||||
<div className="rounded-xl border border-dashed p-10 text-center text-sm text-muted-foreground">
|
||||
{search
|
||||
? "No posts match your search."
|
||||
: "No posts yet. Create your first post!"}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{posts.map((post) => (
|
||||
<article
|
||||
key={post.id}
|
||||
className="rounded-xl border bg-card p-4 shadow-sm"
|
||||
>
|
||||
{editingId === post.id && userRole === UserRole.ADMIN ? (
|
||||
/* ── Edit form ─────────────────────────────────────────── */
|
||||
<form
|
||||
onSubmit={(e) => handleUpdate(e, post.id)}
|
||||
className="space-y-3"
|
||||
>
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="font-semibold text-sm">Editing post</span>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setEditingId(null)}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
<Input name="title" defaultValue={post.title} required placeholder="Title" />
|
||||
<Input name="slug" defaultValue={post.slug} placeholder="Slug" />
|
||||
</div>
|
||||
<Textarea name="excerpt" defaultValue={post.excerpt} placeholder="Excerpt" rows={2} />
|
||||
<Textarea name="content" defaultValue={post.content} placeholder="Content" rows={6} required />
|
||||
|
||||
<div className="grid gap-2 sm:grid-cols-3">
|
||||
<Select name="contentFormat" defaultValue={post.contentFormat}>
|
||||
<SelectTrigger><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value={ContentFormat.MARKDOWN}>Markdown</SelectItem>
|
||||
<SelectItem value={ContentFormat.HTML}>HTML</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Select name="status" defaultValue={post.status}>
|
||||
<SelectTrigger><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value={PostStatus.DRAFT}>Draft</SelectItem>
|
||||
<SelectItem value={PostStatus.PUBLISHED}>Published</SelectItem>
|
||||
<SelectItem value={PostStatus.ARCHIVED}>Archived</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Select name="isFeatured" defaultValue={String(post.isFeatured)}>
|
||||
<SelectTrigger><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="false">Not featured</SelectItem>
|
||||
<SelectItem value="true">Featured</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
<Input name="categories" defaultValue={post.categories.join(",")} placeholder="Categories" />
|
||||
<Input name="tags" defaultValue={post.tags.join(",")} placeholder="Tags" />
|
||||
</div>
|
||||
|
||||
{/* ── Image upload (replaces the old URL text inputs) ── */}
|
||||
<ImageUploader
|
||||
value={editImage.url}
|
||||
onChange={(url) => setEditImage((prev) => ({ ...prev, url }))}
|
||||
altValue={editImage.alt}
|
||||
onAltChange={(alt) => setEditImage((prev) => ({ ...prev, alt }))}
|
||||
label="Featured Image"
|
||||
<div className="rounded-xl border overflow-hidden divide-y">
|
||||
{filtered.map((post) => {
|
||||
const meta = statusMeta[post.status];
|
||||
return (
|
||||
<div
|
||||
key={post.id}
|
||||
className={`flex items-start gap-3 px-4 py-3.5 border-l-4 bg-card hover:bg-muted/30 transition-colors ${meta.row}`}
|
||||
>
|
||||
{/* Thumbnail */}
|
||||
{post.featuredImageUrl ? (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
src={post.featuredImageUrl}
|
||||
alt={post.featuredImageAlt || ""}
|
||||
className="h-12 w-20 rounded-md object-cover shrink-0 border hidden sm:block"
|
||||
/>
|
||||
|
||||
<div className="flex gap-2 justify-end">
|
||||
<Button type="button" variant="ghost" onClick={() => setEditingId(null)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={loading}>
|
||||
{loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
<Check className="mr-1 h-4 w-4" /> Save
|
||||
</Button>
|
||||
) : (
|
||||
<div className="h-12 w-20 rounded-md bg-muted shrink-0 hidden sm:flex items-center justify-center">
|
||||
<span className="text-xs text-muted-foreground/50">No img</span>
|
||||
</div>
|
||||
</form>
|
||||
) : (
|
||||
/* ── Post card view ─────────────────────────────────────── */
|
||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div className="space-y-1 min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<Link
|
||||
href={`/blog/${post.slug}`}
|
||||
className="font-semibold hover:text-primary transition-colors"
|
||||
target="_blank"
|
||||
>
|
||||
{post.title}
|
||||
<ExternalLink className="inline-block ml-1 h-3 w-3" />
|
||||
</Link>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
)}
|
||||
|
||||
{/* Main content */}
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex flex-wrap items-center gap-1.5 mb-0.5">
|
||||
<span
|
||||
className={`inline-block h-1.5 w-1.5 rounded-full ${meta.dot}`}
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{meta.label}
|
||||
</span>
|
||||
{post.isFeatured && (
|
||||
<Star className="h-3 w-3 text-amber-500 fill-amber-500" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Link
|
||||
href={`/blog/${post.slug}`}
|
||||
target="_blank"
|
||||
className="font-semibold text-sm hover:text-primary transition-colors line-clamp-1"
|
||||
>
|
||||
{post.title}
|
||||
<ExternalLink className="inline-block ml-1 h-2.5 w-2.5 opacity-50" />
|
||||
</Link>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2 mt-1">
|
||||
<span className="text-xs text-muted-foreground font-mono">
|
||||
/{post.slug}
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-1.5 pt-1">
|
||||
<span className={`inline-flex items-center rounded-full border px-2 py-0.5 text-xs font-medium ${statusColor[post.status]}`}>
|
||||
{post.status}
|
||||
</span>
|
||||
<span className="flex items-center gap-1 text-xs text-muted-foreground">
|
||||
<Eye className="h-3 w-3" /> {post.views.toLocaleString()}
|
||||
</span>
|
||||
{post.author && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{post.author.name || post.author.email}
|
||||
</span>
|
||||
<span className="inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-xs text-muted-foreground">
|
||||
<Eye className="h-3 w-3" /> {post.views.toLocaleString()}
|
||||
</span>
|
||||
{post.isFeatured && (
|
||||
<Badge variant="secondary" className="text-xs">⭐ featured</Badge>
|
||||
)}
|
||||
{post.author && (
|
||||
)}
|
||||
</div>
|
||||
|
||||
{(post.categories.length > 0 || post.tags.length > 0) && (
|
||||
<div className="flex flex-wrap gap-1 mt-1.5">
|
||||
{post.categories.map((c) => (
|
||||
<Badge
|
||||
key={c}
|
||||
variant="secondary"
|
||||
className="text-xs h-4 px-1.5"
|
||||
>
|
||||
{c}
|
||||
</Badge>
|
||||
))}
|
||||
{post.tags.slice(0, 3).map((t) => (
|
||||
<Badge
|
||||
key={t}
|
||||
variant="outline"
|
||||
className="text-xs h-4 px-1.5"
|
||||
>
|
||||
#{t}
|
||||
</Badge>
|
||||
))}
|
||||
{post.tags.length > 3 && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
by {post.author.name || post.author.email}
|
||||
+{post.tags.length - 3}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{post.excerpt && (
|
||||
<p className="mt-1 text-sm text-muted-foreground line-clamp-2">
|
||||
{post.excerpt}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-1 mt-1">
|
||||
{post.categories.map((c) => (
|
||||
<Badge key={c} variant="secondary" className="text-xs">{c}</Badge>
|
||||
))}
|
||||
{post.tags.map((t) => (
|
||||
<Badge key={t} variant="outline" className="text-xs">#{t}</Badge>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Thumbnail if image exists */}
|
||||
{post.featuredImageUrl && (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
src={post.featuredImageUrl}
|
||||
alt={post.featuredImageAlt || ""}
|
||||
className="mt-2 h-16 w-28 rounded-md object-cover border"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex gap-2 shrink-0">
|
||||
{userRole === UserRole.ADMIN && (
|
||||
<>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => startEditing(post)}
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger asChild>
|
||||
<Button variant="outline" size="sm" className="text-destructive border-destructive/30 hover:bg-destructive/5">
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete post?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
"{post.title}" will be permanently deleted.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
onClick={() => handleDelete(post.id)}
|
||||
disabled={loading}
|
||||
>
|
||||
{loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</article>
|
||||
))}
|
||||
|
||||
{/* Date */}
|
||||
<span className="text-xs text-muted-foreground shrink-0 hidden md:block">
|
||||
{new Date(post.updatedAt).toLocaleDateString()}
|
||||
</span>
|
||||
|
||||
{/* Actions */}
|
||||
{canEdit && (
|
||||
<div className="flex gap-1 shrink-0">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 w-7 p-0"
|
||||
onClick={() => openEdit(post)}
|
||||
>
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 w-7 p-0 text-destructive hover:text-destructive hover:bg-destructive/10"
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete post?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
"{post.title}" will be permanently deleted.
|
||||
This cannot be undone.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
onClick={() => handleDelete(post.id)}
|
||||
disabled={deletingId === post.id}
|
||||
>
|
||||
{deletingId === post.id && (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
)}
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* ── Post create/edit sheet ─────────────────────────────────────────── */}
|
||||
<PostSheet
|
||||
open={sheetOpen}
|
||||
onOpenChange={setSheetOpen}
|
||||
post={editingPost}
|
||||
userRole={userRole}
|
||||
onSuccess={refreshPosts}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import { User, UserRole } from "@/lib/types";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
@@ -14,55 +15,78 @@ import {
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { Loader2, Pencil, X, Check } from "lucide-react";
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetDescription,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
} from "@/components/ui/sheet";
|
||||
import { Loader2, Pencil, Check, Users2 } from "lucide-react";
|
||||
|
||||
interface Props {
|
||||
initialUsers: User[];
|
||||
}
|
||||
|
||||
const roleColor: Record<UserRole, string> = {
|
||||
[UserRole.ADMIN]: "bg-red-100 text-red-800 border-red-200",
|
||||
[UserRole.MANAGER]: "bg-amber-100 text-amber-800 border-amber-200",
|
||||
[UserRole.MEMBER]: "bg-blue-100 text-blue-700 border-blue-200",
|
||||
const roleMeta: Record<UserRole, { label: string; classes: string }> = {
|
||||
[UserRole.ADMIN]: {
|
||||
label: "Admin",
|
||||
classes: "bg-red-100 text-red-800 border-red-200 dark:bg-red-950 dark:text-red-300",
|
||||
},
|
||||
[UserRole.MANAGER]: {
|
||||
label: "Manager",
|
||||
classes: "bg-amber-100 text-amber-800 border-amber-200 dark:bg-amber-950 dark:text-amber-300",
|
||||
},
|
||||
[UserRole.MEMBER]: {
|
||||
label: "Member",
|
||||
classes: "bg-blue-100 text-blue-700 border-blue-200 dark:bg-blue-950 dark:text-blue-300",
|
||||
},
|
||||
};
|
||||
|
||||
function Avatar({ name, email }: { name?: string; email: string }) {
|
||||
const letter = (name || email).charAt(0).toUpperCase();
|
||||
return (
|
||||
<div className="h-9 w-9 shrink-0 rounded-full bg-primary/10 flex items-center justify-center text-sm font-semibold text-primary select-none">
|
||||
{letter}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function UsersTable({ initialUsers }: Props) {
|
||||
const [users, setUsers] = useState<User[]>(initialUsers);
|
||||
const [editingId, setEditingId] = useState<string | null>(null);
|
||||
const [editingUser, setEditingUser] = useState<User | null>(null);
|
||||
const [editName, setEditName] = useState("");
|
||||
const [editRole, setEditRole] = useState<UserRole>(UserRole.MEMBER);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const startEdit = (user: User) => {
|
||||
setEditingId(user.id);
|
||||
const openEdit = (user: User) => {
|
||||
setEditingUser(user);
|
||||
setEditName(user.name || "");
|
||||
setEditRole(user.role);
|
||||
};
|
||||
|
||||
const cancelEdit = () => {
|
||||
setEditingId(null);
|
||||
};
|
||||
const closeEdit = () => setEditingUser(null);
|
||||
|
||||
const handleUpdate = async (user: User) => {
|
||||
const handleUpdate = async () => {
|
||||
if (!editingUser) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
// Update name if changed
|
||||
let updated = user;
|
||||
if (editName !== (user.name || "")) {
|
||||
let updated = editingUser;
|
||||
|
||||
if (editName.trim() !== (editingUser.name || "")) {
|
||||
const res = await clientFetch<{ success: boolean; user: User }>(
|
||||
`/users/${user.id}`,
|
||||
`/users/${editingUser.id}`,
|
||||
{
|
||||
method: "PATCH",
|
||||
body: JSON.stringify({ name: editName || undefined }),
|
||||
body: JSON.stringify({ name: editName.trim() || undefined }),
|
||||
}
|
||||
);
|
||||
updated = res.user;
|
||||
}
|
||||
|
||||
// Update role if changed
|
||||
if (editRole !== user.role) {
|
||||
if (editRole !== editingUser.role) {
|
||||
const res = await clientFetch<{ success: boolean; user: User }>(
|
||||
`/users/${user.id}/role`,
|
||||
`/users/${editingUser.id}/role`,
|
||||
{
|
||||
method: "PATCH",
|
||||
body: JSON.stringify({ role: editRole }),
|
||||
@@ -72,8 +96,10 @@ export function UsersTable({ initialUsers }: Props) {
|
||||
}
|
||||
|
||||
toast.success("User updated.");
|
||||
setUsers((prev) => prev.map((u) => (u.id === user.id ? updated : u)));
|
||||
setEditingId(null);
|
||||
setUsers((prev) =>
|
||||
prev.map((u) => (u.id === editingUser.id ? updated : u))
|
||||
);
|
||||
closeEdit();
|
||||
} catch (err: unknown) {
|
||||
toast.error(err instanceof Error ? err.message : "Update failed");
|
||||
} finally {
|
||||
@@ -81,111 +107,156 @@ export function UsersTable({ initialUsers }: Props) {
|
||||
}
|
||||
};
|
||||
|
||||
if (users.length === 0) {
|
||||
return (
|
||||
<div className="rounded-xl border border-dashed p-10 text-center text-sm text-muted-foreground">
|
||||
No users found.
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{users.length === 0 ? (
|
||||
<div className="rounded-xl border border-dashed p-8 text-center text-sm text-muted-foreground">
|
||||
No users found.
|
||||
</div>
|
||||
) : (
|
||||
users.map((user) => (
|
||||
<div
|
||||
key={user.id}
|
||||
className="rounded-xl border bg-card p-4 shadow-sm flex flex-wrap items-center gap-3"
|
||||
>
|
||||
{editingId === user.id ? (
|
||||
/* ── Edit row ─────────────────────────────────────────────── */
|
||||
<div className="flex flex-1 flex-wrap items-center gap-2">
|
||||
<Input
|
||||
className="h-8 w-40"
|
||||
placeholder="Name"
|
||||
value={editName}
|
||||
onChange={(e) => setEditName(e.target.value)}
|
||||
/>
|
||||
<Select
|
||||
value={editRole}
|
||||
onValueChange={(v) => setEditRole(v as UserRole)}
|
||||
>
|
||||
<SelectTrigger className="h-8 w-32">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value={UserRole.MEMBER}>MEMBER</SelectItem>
|
||||
<SelectItem value={UserRole.MANAGER}>MANAGER</SelectItem>
|
||||
<SelectItem value={UserRole.ADMIN}>ADMIN</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<div className="flex gap-1">
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => handleUpdate(user)}
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Check className="h-4 w-4" />
|
||||
<>
|
||||
<div className="rounded-xl border overflow-hidden divide-y">
|
||||
{users.map((user) => {
|
||||
const role = roleMeta[user.role];
|
||||
return (
|
||||
<div
|
||||
key={user.id}
|
||||
className="flex items-center gap-3 px-4 py-3 bg-card hover:bg-muted/30 transition-colors"
|
||||
>
|
||||
<Avatar name={user.name} email={user.email} />
|
||||
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<p className="text-sm font-medium truncate">
|
||||
{user.name || (
|
||||
<span className="italic text-muted-foreground">
|
||||
No name
|
||||
</span>
|
||||
)}
|
||||
</Button>
|
||||
<Button size="sm" variant="ghost" onClick={cancelEdit}>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
/* ── View row ─────────────────────────────────────────────── */
|
||||
<>
|
||||
<div className="flex flex-1 flex-wrap items-center gap-3 min-w-0">
|
||||
{/* Avatar placeholder */}
|
||||
<div className="h-8 w-8 shrink-0 rounded-full bg-muted flex items-center justify-center text-xs font-semibold uppercase">
|
||||
{(user.name || user.email).charAt(0)}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm font-medium truncate">
|
||||
{user.name ?? (
|
||||
<span className="italic text-muted-foreground">
|
||||
No name
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground truncate">
|
||||
{user.email}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
</p>
|
||||
<span
|
||||
className={`inline-flex items-center rounded-full border px-2 py-0.5 text-xs font-medium ${roleColor[user.role]}`}
|
||||
className={`inline-flex items-center rounded-full border px-2 py-0.5 text-xs font-medium ${role.classes}`}
|
||||
>
|
||||
{user.role}
|
||||
{role.label}
|
||||
</span>
|
||||
|
||||
{!user.isActive && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="text-xs text-muted-foreground"
|
||||
>
|
||||
<Badge variant="outline" className="text-xs text-muted-foreground">
|
||||
Inactive
|
||||
</Badge>
|
||||
)}
|
||||
|
||||
<p className="text-xs text-muted-foreground shrink-0">
|
||||
Joined {new Date(user.createdAt).toLocaleDateString()}
|
||||
</p>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground truncate">
|
||||
{user.email}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => startEdit(user)}
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
<span className="text-xs text-muted-foreground shrink-0 hidden sm:block">
|
||||
{new Date(user.createdAt).toLocaleDateString()}
|
||||
</span>
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 w-7 p-0 shrink-0"
|
||||
onClick={() => openEdit(user)}
|
||||
>
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* ── Edit sheet ───────────────────────────────────────────────────── */}
|
||||
<Sheet open={!!editingUser} onOpenChange={(o) => !o && closeEdit()}>
|
||||
<SheetContent side="right" className="sm:max-w-sm">
|
||||
<SheetHeader>
|
||||
<SheetTitle className="flex items-center gap-2">
|
||||
<Users2 className="h-4 w-4 text-muted-foreground" />
|
||||
Edit User
|
||||
</SheetTitle>
|
||||
<SheetDescription>{editingUser?.email}</SheetDescription>
|
||||
</SheetHeader>
|
||||
|
||||
<div className="mt-6 space-y-4 px-1">
|
||||
{/* Avatar preview */}
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center text-lg font-semibold text-primary">
|
||||
{(editName || editingUser?.email || "?").charAt(0).toUpperCase()}
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium">{editName || "No name"}</p>
|
||||
<p className="text-xs text-muted-foreground">{editingUser?.email}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="eu-name">Display name</Label>
|
||||
<Input
|
||||
id="eu-name"
|
||||
value={editName}
|
||||
onChange={(e) => setEditName(e.target.value)}
|
||||
placeholder="Full name"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label>Role</Label>
|
||||
<Select
|
||||
value={editRole}
|
||||
onValueChange={(v) => setEditRole(v as UserRole)}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value={UserRole.MEMBER}>
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="h-2 w-2 rounded-full bg-blue-500" />
|
||||
Member
|
||||
</span>
|
||||
</SelectItem>
|
||||
<SelectItem value={UserRole.MANAGER}>
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="h-2 w-2 rounded-full bg-amber-500" />
|
||||
Manager
|
||||
</span>
|
||||
</SelectItem>
|
||||
<SelectItem value={UserRole.ADMIN}>
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="h-2 w-2 rounded-full bg-red-500" />
|
||||
Admin
|
||||
</span>
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{editRole === UserRole.ADMIN
|
||||
? "Full access: create, edit, delete posts and manage users."
|
||||
: editRole === UserRole.MANAGER
|
||||
? "Can create posts (saved as draft for review)."
|
||||
: "Read-only access to the dashboard."}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 pt-2">
|
||||
<Button variant="outline" className="flex-1" onClick={closeEdit} disabled={loading}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button className="flex-1" onClick={handleUpdate} disabled={loading}>
|
||||
{loading ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Check className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user