All files / src/pages/admin/blogs categories.tsx

95.6% Statements 87/91
100% Branches 40/40
85.18% Functions 23/27
95.55% Lines 86/90

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427                                                                277x 277x           277x 277x 277x 277x 277x         277x 277x 277x 277x 277x   277x 88x     277x 17x 17x 17x 17x 17x 17x 17x     277x 9x 9x 9x 9x 9x 9x 9x     277x 8x   8x               8x 8x 3x   5x   6x     6x 6x   2x 2x       277x 5x               2x   3x 3x 2x       1x 1x       277x 21x       21x         277x 277x 277x     277x 69x       277x 69x 1x   68x         277x 278x 278x 69x 1x         277x 277x     277x   277x       69x                                   9x             5x             1x         277x                                             26x                             1x                                                                         68x                                                     132x   13x 11x                                   11x                                                                                       88x   70x                                                             1x                          
import { useState } from "react";
import { notify } from "../../../lib/notify";
import { useQueryClient } from "@tanstack/react-query";
import { Plus, Search } from "lucide-react";
 
import {
	AdminPageHead,
	AdminToolbar,
} from "../../../components/admin/AdminPageHead";
import { Alert } from "../../../components/ui/alert";
import { Card } from "../../../components/ui/card";
import { DrawerDialog } from "../../../components/ui/drawer-dialog";
import { Button } from "../../../components/ui/button";
import { Input } from "../../../components/ui/input";
import { adminApi } from "../../../lib/api/admin";
import type { BlogCategory } from "../../../lib/api/blogs";
import { useConfirmDialog } from "../../../hooks";
import { useAdminBlogCategories } from "../../../hooks/queries/useAdminBlogQueries";
import { queryKeys } from "../../../lib/query-keys";
import { Select } from "../../../components/ui/select";
import { Textarea } from "../../../components/ui/textarea";
import {
	Table,
	TableBody,
	TableCaption,
	TableCell,
	TableHead,
	TableHeader,
	TableRow,
} from "../../../components/ui/table";
 
export function AdminBlogCategoriesPage() {
	const queryClient = useQueryClient();
	const { confirm, dialog: confirmDialog } = useConfirmDialog();
	const {
		data: categories = [],
		isLoading,
		error: loadErrorObj,
		refetch,
	} = useAdminBlogCategories();
	const loadError = loadErrorObj ? "Failed to load categories" : null;
	const [search, setSearch] = useState("");
	const [showForm, setShowForm] = useState(false);
	const [editingCategory, setEditingCategory] = useState<BlogCategory | null>(
		null,
	);
 
	// Form state
	const [formName, setFormName] = useState("");
	const [formSlug, setFormSlug] = useState("");
	const [formDescription, setFormDescription] = useState("");
	const [formParentId, setFormParentId] = useState("");
	const [formDisplayOrder, setFormDisplayOrder] = useState(0);
 
	const filteredCategories = categories.filter((cat) =>
		cat.name.toLowerCase().includes(search.toLowerCase()),
	);
 
	const handleCreate = () => {
		setEditingCategory(null);
		setFormName("");
		setFormSlug("");
		setFormDescription("");
		setFormParentId("");
		setFormDisplayOrder(0);
		setShowForm(true);
	};
 
	const handleEdit = (category: BlogCategory) => {
		setEditingCategory(category);
		setFormName(category.name);
		setFormSlug(category.slug);
		setFormDescription(category.description || "");
		setFormParentId(category.parentId || "");
		setFormDisplayOrder(category.displayOrder);
		setShowForm(true);
	};
 
	const handleSubmit = async (e: React.FormEvent) => {
		e.preventDefault();
 
		const data = {
			name: formName,
			slug: formSlug,
			description: formDescription || undefined,
			parentId: formParentId || undefined,
			displayOrder: formDisplayOrder,
		};
 
		try {
			if (editingCategory) {
				await adminApi.updateBlogCategory(editingCategory.id, data);
			} else {
				await adminApi.createBlogCategory(data);
			}
			queryClient.invalidateQueries({
				queryKey: queryKeys.admin.blogs.categories(),
			});
			setShowForm(false);
			setEditingCategory(null);
		} catch (err) {
			console.error("Failed to save category:", err);
			notify.error("Failed to save category. Please try again.");
		}
	};
 
	const handleDelete = async (category: BlogCategory) => {
		if (
			!(await confirm({
				title: "Delete category",
				description: `Are you sure you want to delete "${category.name}"?`,
				confirmLabel: "Delete",
				variant: "destructive",
			}))
		)
			return;
 
		try {
			await adminApi.deleteBlogCategory(category.id);
			queryClient.invalidateQueries({
				queryKey: queryKeys.admin.blogs.categories(),
			});
		} catch (err) {
			console.error("Failed to delete category:", err);
			notify.error("Failed to delete category. Please try again.");
		}
	};
 
	const generateSlug = () => {
		const autoSlug = formName
			.toLowerCase()
			.replace(/[^a-z0-9]+/g, "-")
			.replace(/^-|-$/g, "");
		setFormSlug(autoSlug);
	};
 
	// Build hierarchy for display
	type CategoryNode = BlogCategory & { children: CategoryNode[] };
	const buildHierarchy = (categories: BlogCategory[]): CategoryNode[] => {
		const categoryMap = new Map<string, CategoryNode>();
		const rootCategories: CategoryNode[] = [];
 
		// Initialize map
		for (const cat of categories) {
			categoryMap.set(cat.id, { ...cat, children: [] });
		}
 
		// Build hierarchy
		for (const cat of categoryMap.values()) {
			if (cat.parentId && categoryMap.has(cat.parentId)) {
				categoryMap.get(cat.parentId)?.children.push(cat);
			} else {
				rootCategories.push(cat);
			}
		}
 
		// Sort by displayOrder
		const sortByDisplayOrder = (items: CategoryNode[]) => {
			items.sort((a, b) => a.displayOrder - b.displayOrder);
			for (const item of items) {
				if (item.children?.length > 0) {
					sortByDisplayOrder(item.children);
				}
			}
		};
 
		sortByDisplayOrder(rootCategories);
		return rootCategories;
	};
 
	const hierarchicalCategories = buildHierarchy(filteredCategories);
 
	const renderCategoryRow = (
		category: BlogCategory & { children?: BlogCategory[] },
		level = 0,
	): React.ReactNode => {
		return (
			<>
				<TableRow key={category.id}>
					<TableCell>
						<div style={{ paddingLeft: `${level * 24}px` }}>
							<p className="text-sm font-medium">{category.name}</p>
							<p className="text-xs text-foreground-subtle">{category.slug}</p>
						</div>
					</TableCell>
					<TableCell className="text-sm text-foreground-subtle">
						{category.description || "-"}
					</TableCell>
					<TableCell className="text-sm text-center">
						{category.displayOrder}
					</TableCell>
					<TableCell className="space-x-2 text-right">
						<button
							type="button"
							onClick={() => handleEdit(category)}
							className="text-primary-600 hover:text-primary-800 text-sm"
						>
							Edit
						</button>
						<button
							type="button"
							onClick={() => handleDelete(category)}
							className="text-error hover:text-error-dark text-sm"
						>
							Delete
						</button>
					</TableCell>
				</TableRow>
				{category.children?.map((child) => renderCategoryRow(child, level + 1))}
			</>
		);
	};
 
	return (
		<>
			<div className="space-y-6">
				<AdminPageHead
					title="Blog Categories"
					description="Manage blog category hierarchy"
					actions={
						<Button onClick={handleCreate}>
							<Plus aria-hidden="true" />
							Create Category
						</Button>
					}
				/>
 
				<AdminToolbar aria-label="Category filters">
					<div className="relative min-w-56 grow">
						<Search
							aria-hidden="true"
							className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-foreground-subtle"
						/>
						<Input
							aria-label="Search categories"
							value={search}
							onChange={(e) => setSearch(e.target.value)}
							placeholder="Search categories..."
							className="pl-10"
						/>
					</div>
				</AdminToolbar>
 
				{loadError && (
					<Alert variant="error">
						<span className="flex flex-wrap items-center justify-between gap-3">
							<span>{loadError}</span>
							<Button
								variant="ghost"
								size="sm"
								onClick={() => {
									refetch();
								}}
							>
								Retry
							</Button>
						</span>
					</Alert>
				)}
 
				{/* Categories Table */}
				<Card className="overflow-hidden">
					<Table density="dense">
						<TableCaption>
							Blog categories, with their slugs and post counts.
						</TableCaption>
						<TableHeader>
							<TableRow>
								<TableHead>Name</TableHead>
								<TableHead>Description</TableHead>
								<TableHead className="text-center">Order</TableHead>
								<TableHead className="text-right">Actions</TableHead>
							</TableRow>
						</TableHeader>
						<TableBody>
							{isLoading ? (
								<TableRow>
									<TableCell colSpan={4} className="text-center text-sm">
										Loading...
									</TableCell>
								</TableRow>
							) : hierarchicalCategories.length === 0 && !loadError ? (
								<TableRow>
									<TableCell colSpan={4} className="text-center text-sm">
										No categories found
									</TableCell>
								</TableRow>
							) : (
								hierarchicalCategories.map((cat) => renderCategoryRow(cat))
							)}
						</TableBody>
					</Table>
				</Card>
 
				{/*
				 * Form — on the DrawerDialog primitive, which carries the focus
				 * trap, the Escape handler and the dialog role the hand-rolled
				 * overlay did not.
				 */}
				<DrawerDialog
					open={showForm}
					onClose={() => setShowForm(false)}
					title={editingCategory ? "Edit Category" : "Create Category"}
				>
					<form onSubmit={handleSubmit} className="space-y-4">
						<div>
							<label
								htmlFor="name"
								className="mb-1.5 block text-xs font-semibold uppercase tracking-wider text-foreground-muted"
							>
								Name <span className="text-error">*</span>
							</label>
							<Input
								id="name"
								value={formName}
								onChange={(e) => setFormName(e.target.value)}
								onBlur={() => {
									if (formName && !formSlug) {
										generateSlug();
									}
								}}
								required
							/>
						</div>
 
						<div>
							<label
								htmlFor="slug"
								className="mb-1.5 block text-xs font-semibold uppercase tracking-wider text-foreground-muted"
							>
								Slug <span className="text-error">*</span>
							</label>
							<div className="flex gap-2">
								<Input
									id="slug"
									value={formSlug}
									onChange={(e) => setFormSlug(e.target.value)}
									required
								/>
								<button
									type="button"
									onClick={generateSlug}
									className="px-4 py-2 text-sm border border-border-default rounded-md hover:bg-background-muted whitespace-nowrap"
								>
									Generate
								</button>
							</div>
						</div>
 
						<div>
							<label
								htmlFor="description"
								className="mb-1.5 block text-xs font-semibold uppercase tracking-wider text-foreground-muted"
							>
								Description
							</label>
							<Textarea
								id="description"
								value={formDescription}
								onChange={(e) => setFormDescription(e.target.value)}
								rows={3}
								className="w-full"
							/>
						</div>
 
						<div>
							<label
								htmlFor="parentId"
								className="mb-1.5 block text-xs font-semibold uppercase tracking-wider text-foreground-muted"
							>
								Parent Category
							</label>
							<Select
								id="parentId"
								value={formParentId}
								onChange={(e) => setFormParentId(e.target.value)}
								className="w-full"
							>
								<option value="">None (Top Level)</option>
								{categories
									.filter((c) => c.id !== editingCategory?.id)
									.map((cat) => (
										<option key={cat.id} value={cat.id}>
											{cat.name}
										</option>
									))}
							</Select>
						</div>
 
						<div>
							<label
								htmlFor="displayOrder"
								className="mb-1.5 block text-xs font-semibold uppercase tracking-wider text-foreground-muted"
							>
								Display Order
							</label>
							<Input
								id="displayOrder"
								type="number"
								value={formDisplayOrder}
								onChange={(e) =>
									setFormDisplayOrder(Number.parseInt(e.target.value, 10))
								}
							/>
						</div>
 
						<div className="flex gap-3 border-t border-border-default pt-4">
							<Button type="submit" className="flex-1">
								{editingCategory ? "Update" : "Create"}
							</Button>
							<Button
								type="button"
								variant="outline"
								onClick={() => setShowForm(false)}
								className="flex-1"
							>
								Cancel
							</Button>
						</div>
					</form>
				</DrawerDialog>
			</div>
			{confirmDialog}
		</>
	);
}