feat(38-02): admin tag hooks + list page with tree view and quick-add
- Create useAdminTags.ts with 5 hooks (useAdminTags, useAdminTag, useCreateAdminTag, useUpdateAdminTag, useDeleteAdminTag) - Dual query key invalidation on all mutations (admin-tags + tags) - Create admin/tags.tsx with collapsible tree view, search/filter, quick-add form - buildTree, flattenTree, filterTree utilities for hierarchy rendering - Chevron expand/collapse with LucideIcon, depth-based indent
This commit is contained in:
77
src/client/hooks/useAdminTags.ts
Normal file
77
src/client/hooks/useAdminTags.ts
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { ApiError, apiDelete, apiGet, apiPost, apiPut } from "../lib/api";
|
||||||
|
|
||||||
|
// ── Types ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface AdminTag {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
parentId: number | null;
|
||||||
|
itemCount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CreateTagPayload {
|
||||||
|
name: string;
|
||||||
|
parentId?: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UpdateTagPayload {
|
||||||
|
name?: string;
|
||||||
|
parentId?: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Hooks ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function useAdminTags() {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ["admin-tags"],
|
||||||
|
queryFn: () => apiGet<AdminTag[]>("/api/admin/tags"),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useAdminTag(id: number | null) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ["admin-tag", id],
|
||||||
|
queryFn: () => apiGet<AdminTag>(`/api/admin/tags/${id}`),
|
||||||
|
enabled: id != null,
|
||||||
|
retry: (count, error) =>
|
||||||
|
error instanceof ApiError && error.status === 404 ? false : count < 3,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useCreateAdminTag() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (data: CreateTagPayload) =>
|
||||||
|
apiPost<AdminTag>("/api/admin/tags", data),
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["admin-tags"] });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["tags"] });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useUpdateAdminTag() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: ({ id, data }: { id: number; data: UpdateTagPayload }) =>
|
||||||
|
apiPut<AdminTag>(`/api/admin/tags/${id}`, data),
|
||||||
|
onSuccess: (_result, { id }) => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["admin-tags"] });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["admin-tag", id] });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["tags"] });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useDeleteAdminTag() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (id: number) =>
|
||||||
|
apiDelete<{ success: boolean }>(`/api/admin/tags/${id}`),
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["admin-tags"] });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["tags"] });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
302
src/client/routes/admin/tags.tsx
Normal file
302
src/client/routes/admin/tags.tsx
Normal file
@@ -0,0 +1,302 @@
|
|||||||
|
import { createFileRoute, useNavigate } from "@tanstack/react-router";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import {
|
||||||
|
useAdminTags,
|
||||||
|
useCreateAdminTag,
|
||||||
|
type AdminTag,
|
||||||
|
} from "../../hooks/useAdminTags";
|
||||||
|
import { LucideIcon } from "../../lib/iconData";
|
||||||
|
|
||||||
|
export const Route = createFileRoute("/admin/tags")({
|
||||||
|
component: AdminTagsPage,
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── Tree utilities ─────────────────────────────────────────────────
|
||||||
|
|
||||||
|
interface TreeNode extends AdminTag {
|
||||||
|
children: TreeNode[];
|
||||||
|
depth: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildTree(tags: AdminTag[]): TreeNode[] {
|
||||||
|
const map = new Map<number, TreeNode>();
|
||||||
|
for (const tag of tags) {
|
||||||
|
map.set(tag.id, { ...tag, children: [], depth: 0 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const roots: TreeNode[] = [];
|
||||||
|
for (const node of map.values()) {
|
||||||
|
if (node.parentId == null || !map.has(node.parentId)) {
|
||||||
|
node.depth = 0;
|
||||||
|
roots.push(node);
|
||||||
|
} else {
|
||||||
|
const parent = map.get(node.parentId)!;
|
||||||
|
node.depth = parent.depth + 1;
|
||||||
|
parent.children.push(node);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fix depths after assignment (parents may not have been processed yet)
|
||||||
|
function fixDepths(nodes: TreeNode[], depth: number) {
|
||||||
|
for (const node of nodes) {
|
||||||
|
node.depth = depth;
|
||||||
|
fixDepths(node.children, depth + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fixDepths(roots, 0);
|
||||||
|
|
||||||
|
// Sort children alphabetically
|
||||||
|
function sortChildren(nodes: TreeNode[]) {
|
||||||
|
nodes.sort((a, b) => a.name.localeCompare(b.name));
|
||||||
|
for (const node of nodes) sortChildren(node.children);
|
||||||
|
}
|
||||||
|
sortChildren(roots);
|
||||||
|
|
||||||
|
return roots;
|
||||||
|
}
|
||||||
|
|
||||||
|
function flattenTree(nodes: TreeNode[], expanded: Set<number>): TreeNode[] {
|
||||||
|
const result: TreeNode[] = [];
|
||||||
|
for (const node of nodes) {
|
||||||
|
result.push(node);
|
||||||
|
if (node.children.length > 0 && expanded.has(node.id)) {
|
||||||
|
result.push(...flattenTree(node.children, expanded));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
function filterTree(nodes: TreeNode[], query: string): TreeNode[] {
|
||||||
|
const q = query.toLowerCase();
|
||||||
|
const result: TreeNode[] = [];
|
||||||
|
for (const node of nodes) {
|
||||||
|
const filteredChildren = filterTree(node.children, query);
|
||||||
|
const nameMatches = node.name.toLowerCase().includes(q);
|
||||||
|
if (nameMatches || filteredChildren.length > 0) {
|
||||||
|
result.push({ ...node, children: filteredChildren });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Page component ─────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function AdminTagsPage() {
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const { data, isLoading, isError } = useAdminTags();
|
||||||
|
const createMutation = useCreateAdminTag();
|
||||||
|
|
||||||
|
const [searchQuery, setSearchQuery] = useState("");
|
||||||
|
const [newName, setNewName] = useState("");
|
||||||
|
const [newParentId, setNewParentId] = useState<number | null>(null);
|
||||||
|
const [expanded, setExpanded] = useState<Set<number>>(new Set());
|
||||||
|
const [createError, setCreateError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// Initialize expanded to all parent IDs when data loads
|
||||||
|
useEffect(() => {
|
||||||
|
if (data) {
|
||||||
|
const parentIds = new Set(
|
||||||
|
data
|
||||||
|
.filter((tag) => data.some((t) => t.parentId === tag.id))
|
||||||
|
.map((tag) => tag.id),
|
||||||
|
);
|
||||||
|
setExpanded(parentIds);
|
||||||
|
}
|
||||||
|
}, [data]);
|
||||||
|
|
||||||
|
function toggleExpand(id: number) {
|
||||||
|
setExpanded((prev) => {
|
||||||
|
const next = new Set(prev);
|
||||||
|
if (next.has(id)) next.delete(id);
|
||||||
|
else next.add(id);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleCreate(e: React.FormEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!newName.trim()) return;
|
||||||
|
setCreateError(null);
|
||||||
|
try {
|
||||||
|
await createMutation.mutateAsync({
|
||||||
|
name: newName.trim(),
|
||||||
|
parentId: newParentId,
|
||||||
|
});
|
||||||
|
setNewName("");
|
||||||
|
setNewParentId(null);
|
||||||
|
} catch {
|
||||||
|
setCreateError("Failed to create tag. Please try again.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const tree = data ? buildTree(data) : [];
|
||||||
|
const filtered = searchQuery ? filterTree(tree, searchQuery) : tree;
|
||||||
|
const rows = flattenTree(filtered, expanded);
|
||||||
|
|
||||||
|
const inputClass =
|
||||||
|
"w-full rounded-lg border border-gray-200 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-300";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
{/* Header */}
|
||||||
|
<div className="flex items-center justify-between mb-4">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-lg font-semibold text-gray-900">Tags</h1>
|
||||||
|
{!isLoading && data && (
|
||||||
|
<p className="text-sm text-gray-400 mt-0.5">{data.length} tags</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
placeholder="Search tags..."
|
||||||
|
value={searchQuery}
|
||||||
|
onChange={(e) => setSearchQuery(e.target.value)}
|
||||||
|
className="w-64 rounded-lg border border-gray-200 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-300"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Quick-add form */}
|
||||||
|
<form onSubmit={handleCreate} className="flex items-center gap-3 mb-4">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={newName}
|
||||||
|
onChange={(e) => setNewName(e.target.value)}
|
||||||
|
placeholder="Tag name..."
|
||||||
|
className={`flex-1 ${inputClass}`}
|
||||||
|
/>
|
||||||
|
<select
|
||||||
|
value={newParentId ?? ""}
|
||||||
|
onChange={(e) =>
|
||||||
|
setNewParentId(e.target.value ? Number(e.target.value) : null)
|
||||||
|
}
|
||||||
|
className="rounded-lg border border-gray-200 px-3 py-2 text-sm focus:outline-none bg-white appearance-none w-48"
|
||||||
|
>
|
||||||
|
<option value="">No parent (top-level)</option>
|
||||||
|
{data?.map((t) => (
|
||||||
|
<option key={t.id} value={t.id}>
|
||||||
|
{t.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={createMutation.isPending || !newName.trim()}
|
||||||
|
className="px-4 py-2 rounded-lg bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium transition-colors disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{createMutation.isPending ? "Adding..." : "Add Tag"}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
{createError && (
|
||||||
|
<p className="text-sm text-red-500 mt-1 mb-4">{createError}</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Error state */}
|
||||||
|
{isError && (
|
||||||
|
<div className="py-12 text-center text-sm text-red-500">
|
||||||
|
Failed to load tags. Please try again.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Tree table */}
|
||||||
|
{!isError && (
|
||||||
|
<div className="w-full overflow-hidden rounded-xl border border-gray-100 bg-white">
|
||||||
|
<table className="w-full text-sm">
|
||||||
|
<thead className="bg-gray-50 border-b border-gray-100">
|
||||||
|
<tr>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-semibold text-gray-400 uppercase tracking-wide">
|
||||||
|
Tag
|
||||||
|
</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-semibold text-gray-400 uppercase tracking-wide">
|
||||||
|
Items
|
||||||
|
</th>
|
||||||
|
<th className="px-4 py-3 text-right text-xs font-semibold text-gray-400 uppercase tracking-wide">
|
||||||
|
Actions
|
||||||
|
</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{isLoading
|
||||||
|
? Array.from({ length: 6 }).map((_, i) => (
|
||||||
|
<tr key={i} className="border-b border-gray-50">
|
||||||
|
{Array.from({ length: 3 }).map((_, j) => (
|
||||||
|
<td key={j} className="px-4 py-3">
|
||||||
|
<div className="h-4 bg-gray-100 rounded animate-pulse" />
|
||||||
|
</td>
|
||||||
|
))}
|
||||||
|
</tr>
|
||||||
|
))
|
||||||
|
: rows.map((node) => (
|
||||||
|
<tr
|
||||||
|
key={node.id}
|
||||||
|
className="border-b border-gray-50 hover:bg-gray-50 cursor-pointer transition-colors"
|
||||||
|
onClick={() =>
|
||||||
|
navigate({
|
||||||
|
to: "/admin/tags/$tagId",
|
||||||
|
params: { tagId: String(node.id) },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<td className="px-4 py-2.5">
|
||||||
|
<div
|
||||||
|
className="flex items-center gap-1"
|
||||||
|
style={{ paddingLeft: `${node.depth * 20}px` }}
|
||||||
|
>
|
||||||
|
{node.children.length > 0 ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
toggleExpand(node.id);
|
||||||
|
}}
|
||||||
|
className="text-gray-400 hover:text-gray-600 w-5 h-5 flex items-center justify-center rounded hover:bg-gray-100 p-0.5"
|
||||||
|
>
|
||||||
|
<LucideIcon
|
||||||
|
name={
|
||||||
|
expanded.has(node.id)
|
||||||
|
? "chevron-down"
|
||||||
|
: "chevron-right"
|
||||||
|
}
|
||||||
|
size={14}
|
||||||
|
/>
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
<span className="w-5" />
|
||||||
|
)}
|
||||||
|
<span className="font-medium text-gray-900">
|
||||||
|
{node.name}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-2.5 text-sm text-gray-400">
|
||||||
|
{node.itemCount} items
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-2.5 text-right">
|
||||||
|
<span className="text-xs text-gray-400">Edit</span>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
{/* Empty state */}
|
||||||
|
{!isLoading && rows.length === 0 && !isError && (
|
||||||
|
<div className="py-12 text-center">
|
||||||
|
{searchQuery ? (
|
||||||
|
<p className="text-sm text-gray-900 font-medium">
|
||||||
|
No tags match your search.
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<p className="text-sm font-medium text-gray-900">No tags yet</p>
|
||||||
|
<p className="text-sm text-gray-400 mt-1">
|
||||||
|
Add your first tag using the form above.
|
||||||
|
</p>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user