feat: add admin area with item CRUD, Lexical editor and access control (M6)
Backend: - Item model (title, url, points, username, content, created_at) - is_admin flag on User + startup migration for pre-existing DBs - get_current_admin dependency (401 without/invalid token, 403 for non-admins); server-side check on every admin endpoint - /api/v1/admin/items CRUD: pagination, case-insensitive title/url search, sort by title/created_at/points, in-memory rate limiting (1000 req/60s per admin -> 429) - seed_admin.py (ADMIN_USERNAME/ADMIN_PASSWORD), documented in backend/.env.example Frontend: - Auth context exposes is_admin; RequireAdmin route guard (redirects signed-out users, renders 403 page for non-admins) - AdminLayout with responsive dark sidebar; Admin link in header for admins only - AdminDashboard: paginated table (page size 10/20/50), 300ms debounced search, sortable title/points/created_at columns, edit/delete row actions - EditItemPage: create + edit with client-side validation and a Lexical (0.25) WYSIWYG editor (bold/italic/underline, H1-H6, lists, code blocks, links, undo/redo), optional debounced auto-save - DeleteConfirmation modal with warning icon and explicit "Yes, delete" confirmation - Unit tests (34) and mocked E2E workflow tests (10) All acceptance criteria for milestones/m6-setup-admin-area-prompt.md verified: 108 backend, 87 frontend unit and 29 E2E tests pass.
This commit is contained in:
1 parent
b186d0f797
commit
b440809548
38 files changed
+5415
-50
No files matched your search
@@ -0,0 +1,480 @@
|
||||
/**
|
||||
* Admin dashboard (M6): paginated list of all items with debounced
|
||||
* search (300ms), sortable columns (title / points / created date),
|
||||
* page-size selector, row actions (edit / delete) and a success notice
|
||||
* after saves coming back from the edit page.
|
||||
*/
|
||||
import {
|
||||
ArrowDown,
|
||||
ArrowUp,
|
||||
ArrowUpDown,
|
||||
Pencil,
|
||||
Plus,
|
||||
RefreshCw,
|
||||
Search,
|
||||
Trash2,
|
||||
} from 'lucide-react';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { Link, useLocation } from 'react-router-dom';
|
||||
import { adminDeleteItem, adminListItems } from '../api/admin';
|
||||
import { DeleteConfirmation } from '../components/DeleteConfirmation';
|
||||
import { ApiError } from '../api/client';
|
||||
import { cn } from '../lib/utils';
|
||||
import type {
|
||||
AdminItem,
|
||||
AdminItemsPage,
|
||||
AdminSortBy,
|
||||
AdminSortOrder,
|
||||
} from '../types/admin';
|
||||
|
||||
const PAGE_SIZES = [10, 20, 50];
|
||||
const SEARCH_DEBOUNCE_MS = 300;
|
||||
|
||||
interface AdminDashboardState {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
search: string;
|
||||
sortBy: AdminSortBy;
|
||||
sortOrder: AdminSortOrder;
|
||||
}
|
||||
|
||||
const INITIAL_STATE: AdminDashboardState = {
|
||||
page: 1,
|
||||
pageSize: 20,
|
||||
search: '',
|
||||
sortBy: 'created_at',
|
||||
sortOrder: 'desc',
|
||||
};
|
||||
|
||||
/** "2024-05-01T12:30:00Z" -> "01 May 2024, 12:30" (empty on bad input). */
|
||||
function formatDateTime(value: string): string {
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return value;
|
||||
return date.toLocaleString('en-GB', {
|
||||
day: '2-digit',
|
||||
month: 'short',
|
||||
year: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
});
|
||||
}
|
||||
|
||||
/** Compact page-number window with ellipses, e.g. [1, '…', 4, 5, 6, '…', 12]. */
|
||||
function pageWindow(current: number, total: number): (number | '…')[] {
|
||||
if (total <= 7) return Array.from({ length: total }, (_, i) => i + 1);
|
||||
const pages = new Set<number>([1, 2, total - 1, total, current - 1, current, current + 1]);
|
||||
const sorted = [...pages].filter((p) => p >= 1 && p <= total).sort((a, b) => a - b);
|
||||
const out: (number | '…')[] = [];
|
||||
let previous = 0;
|
||||
for (const p of sorted) {
|
||||
if (p - previous > 1) out.push('…');
|
||||
out.push(p);
|
||||
previous = p;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function AdminDashboard() {
|
||||
const [state, setState] = useState<AdminDashboardState>(INITIAL_STATE);
|
||||
const [debouncedSearch, setDebouncedSearch] = useState('');
|
||||
const [data, setData] = useState<AdminItemsPage | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [pendingDelete, setPendingDelete] = useState<AdminItem | null>(null);
|
||||
const [deleteBusy, setDeleteBusy] = useState(false);
|
||||
const [deleteError, setDeleteError] = useState<string | null>(null);
|
||||
const [notice, setNotice] = useState<string | null>(null);
|
||||
|
||||
const location = useLocation();
|
||||
// Success notice passed by the edit page after a save.
|
||||
useEffect(() => {
|
||||
const passed = (location.state as { notice?: string } | null)?.notice;
|
||||
if (passed) {
|
||||
setNotice(passed);
|
||||
// Clear it from router state so a refresh does not re-show it.
|
||||
window.history.replaceState({}, '');
|
||||
}
|
||||
}, [location.state]);
|
||||
|
||||
// Debounce the search input (300ms) before it reaches the API.
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => setDebouncedSearch(state.search), SEARCH_DEBOUNCE_MS);
|
||||
return () => clearTimeout(timer);
|
||||
}, [state.search]);
|
||||
|
||||
const searchActive = debouncedSearch.trim();
|
||||
|
||||
const load = useCallback(
|
||||
async (signal?: { cancelled: boolean }) => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const result = await adminListItems({
|
||||
page: state.page,
|
||||
pageSize: state.pageSize,
|
||||
search: searchActive,
|
||||
sortBy: state.sortBy,
|
||||
sortOrder: state.sortOrder,
|
||||
});
|
||||
if (signal?.cancelled) return;
|
||||
setData(result);
|
||||
} catch (err) {
|
||||
if (signal?.cancelled) return;
|
||||
setError(
|
||||
err instanceof ApiError
|
||||
? err.message
|
||||
: 'Something went wrong while loading items.',
|
||||
);
|
||||
} finally {
|
||||
if (!signal?.cancelled) setLoading(false);
|
||||
}
|
||||
},
|
||||
[state, searchActive],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const signal = { cancelled: false };
|
||||
void load(signal);
|
||||
return () => {
|
||||
signal.cancelled = true;
|
||||
};
|
||||
}, [load]);
|
||||
|
||||
const update = (patch: Partial<AdminDashboardState>) =>
|
||||
setState((current) => ({ ...current, ...patch }));
|
||||
|
||||
// Search resets to page 1 (the debounced value drives the fetch).
|
||||
const onSearchChange = (value: string) => update({ search: value, page: 1 });
|
||||
|
||||
const onSort = (field: AdminSortBy) =>
|
||||
setState((current) =>
|
||||
current.sortBy === field
|
||||
? {
|
||||
...current,
|
||||
sortOrder: current.sortOrder === 'asc' ? 'desc' : 'asc',
|
||||
page: 1,
|
||||
}
|
||||
: { ...current, sortBy: field, sortOrder: 'asc', page: 1 },
|
||||
);
|
||||
|
||||
const onPageSizeChange = (size: number) => update({ pageSize: size, page: 1 });
|
||||
const onPageChange = (page: number) => update({ page });
|
||||
|
||||
const confirmDelete = async () => {
|
||||
if (!pendingDelete) return;
|
||||
setDeleteBusy(true);
|
||||
setDeleteError(null);
|
||||
try {
|
||||
await adminDeleteItem(pendingDelete.id);
|
||||
setPendingDelete(null);
|
||||
setNotice(`“${pendingDelete.title}” was deleted.`);
|
||||
await load();
|
||||
} catch (err) {
|
||||
setDeleteError(err instanceof ApiError ? err.message : 'Deleting the item failed.');
|
||||
} finally {
|
||||
setDeleteBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const cancelDelete = () => {
|
||||
setPendingDelete(null);
|
||||
setDeleteError(null);
|
||||
};
|
||||
|
||||
const range = useMemo(() => {
|
||||
if (!data || data.total === 0) return null;
|
||||
const start = (data.page - 1) * data.page_size + 1;
|
||||
const end = Math.min(data.page * data.page_size, data.total);
|
||||
return { start, end, total: data.total };
|
||||
}, [data]);
|
||||
|
||||
const totalPages = data?.total_pages ?? 0;
|
||||
|
||||
const sortIndicator = (field: AdminSortBy) =>
|
||||
state.sortBy !== field ? (
|
||||
<ArrowUpDown size={13} className="text-slate-400" aria-hidden="true" />
|
||||
) : state.sortOrder === 'asc' ? (
|
||||
<ArrowUp size={13} className="text-blue-600" aria-hidden="true" />
|
||||
) : (
|
||||
<ArrowDown size={13} className="text-blue-600" aria-hidden="true" />
|
||||
);
|
||||
|
||||
const thClasses =
|
||||
'px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500';
|
||||
const sortButtonClasses =
|
||||
'inline-flex items-center gap-1.5 uppercase tracking-wide hover:text-slate-800';
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* Heading + primary action */}
|
||||
<div className="mb-6 flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-slate-900">Items</h1>
|
||||
<p className="text-sm text-slate-500">
|
||||
Create, edit and delete the news items shown on the site.
|
||||
</p>
|
||||
</div>
|
||||
<Link to="/admin/items/new" className="btn">
|
||||
<Plus size={15} aria-hidden="true" />
|
||||
New item
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{notice && (
|
||||
<div
|
||||
className="mb-4 flex items-center justify-between gap-3 rounded-md border border-green-200 bg-green-50 px-4 py-2.5 text-sm text-green-800"
|
||||
role="status"
|
||||
>
|
||||
<span>{notice}</span>
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Dismiss notice"
|
||||
className="text-green-700 hover:text-green-900"
|
||||
onClick={() => setNotice(null)}
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Search + filters */}
|
||||
<form
|
||||
role="search"
|
||||
className="mb-4 flex items-center gap-3"
|
||||
onSubmit={(event) => event.preventDefault()}
|
||||
>
|
||||
<label htmlFor="admin-item-search" className="sr-only">
|
||||
Search items
|
||||
</label>
|
||||
<div className="relative w-full max-w-sm">
|
||||
<Search
|
||||
className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<input
|
||||
id="admin-item-search"
|
||||
type="search"
|
||||
placeholder="Search by title or URL…"
|
||||
value={state.search}
|
||||
onChange={(event) => onSearchChange(event.target.value)}
|
||||
className="w-full rounded-md border border-slate-300 bg-white py-2 pl-9 pr-3 text-sm text-slate-900 placeholder:text-slate-400 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500/40"
|
||||
/>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{error && (
|
||||
<div
|
||||
className="mb-4 flex items-center justify-between gap-3 rounded-md border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700"
|
||||
role="alert"
|
||||
>
|
||||
<span>{error}</span>
|
||||
<button type="button" className="btn-secondary !py-1.5" onClick={() => void load()}>
|
||||
<RefreshCw size={14} aria-hidden="true" />
|
||||
Retry
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Item table */}
|
||||
<div className="overflow-x-auto rounded-xl border border-slate-200 bg-white shadow-sm">
|
||||
<table className="min-w-full divide-y divide-slate-200 text-sm">
|
||||
<thead className="bg-slate-50">
|
||||
<tr>
|
||||
<th scope="col" className={thClasses}>
|
||||
<button
|
||||
type="button"
|
||||
className={sortButtonClasses}
|
||||
onClick={() => onSort('title')}
|
||||
aria-label="Sort by title"
|
||||
>
|
||||
Title {sortIndicator('title')}
|
||||
</button>
|
||||
</th>
|
||||
<th scope="col" className={thClasses}>
|
||||
URL
|
||||
</th>
|
||||
<th scope="col" className={cn(thClasses, 'text-right')}>
|
||||
<button
|
||||
type="button"
|
||||
className={cn(sortButtonClasses, 'ml-auto flex-row-reverse')}
|
||||
onClick={() => onSort('points')}
|
||||
aria-label="Sort by points"
|
||||
>
|
||||
Points {sortIndicator('points')}
|
||||
</button>
|
||||
</th>
|
||||
<th scope="col" className={thClasses}>
|
||||
Author
|
||||
</th>
|
||||
<th scope="col" className={thClasses}>
|
||||
<button
|
||||
type="button"
|
||||
className={sortButtonClasses}
|
||||
onClick={() => onSort('created_at')}
|
||||
aria-label="Sort by creation date"
|
||||
>
|
||||
Created {sortIndicator('created_at')}
|
||||
</button>
|
||||
</th>
|
||||
<th scope="col" className={cn(thClasses, 'text-right')}>
|
||||
<span className="sr-only">Actions</span>
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-slate-100">
|
||||
{loading && data === null ? (
|
||||
<tr>
|
||||
<td colSpan={6} className="px-4 py-12 text-center text-sm text-slate-500">
|
||||
<span className="animate-pulse">Loading items…</span>
|
||||
</td>
|
||||
</tr>
|
||||
) : data && data.items.length > 0 ? (
|
||||
data.items.map((item) => (
|
||||
<tr key={item.id} className="transition-colors hover:bg-slate-50">
|
||||
<td className="max-w-xs px-4 py-3">
|
||||
<span className="block truncate font-medium text-slate-900" title={item.title}>
|
||||
{item.title}
|
||||
</span>
|
||||
</td>
|
||||
<td className="max-w-[14rem] px-4 py-3">
|
||||
{item.url ? (
|
||||
<a
|
||||
href={item.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="block truncate text-blue-700 hover:underline"
|
||||
title={item.url}
|
||||
>
|
||||
{item.url}
|
||||
</a>
|
||||
) : (
|
||||
<span className="text-slate-400">—</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-right tabular-nums text-slate-700">
|
||||
{item.points}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-slate-600">{item.username}</td>
|
||||
<td className="whitespace-nowrap px-4 py-3 text-slate-500">
|
||||
{formatDateTime(item.created_at)}
|
||||
</td>
|
||||
<td className="whitespace-nowrap px-4 py-3 text-right">
|
||||
<div className="inline-flex items-center gap-1">
|
||||
<Link
|
||||
to={`/admin/items/${item.id}/edit`}
|
||||
className="inline-flex items-center gap-1.5 rounded-md border border-slate-300 bg-white px-2.5 py-1.5 text-xs font-medium text-slate-700 transition-colors hover:bg-slate-100"
|
||||
>
|
||||
<Pencil size={13} aria-hidden="true" />
|
||||
Edit
|
||||
</Link>
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex items-center gap-1.5 rounded-md border border-red-200 bg-white px-2.5 py-1.5 text-xs font-medium text-red-700 transition-colors hover:bg-red-50"
|
||||
onClick={() => setPendingDelete(item)}
|
||||
>
|
||||
<Trash2 size={13} aria-hidden="true" />
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
) : (
|
||||
<tr>
|
||||
<td colSpan={6} className="px-4 py-12 text-center text-sm text-slate-500">
|
||||
{searchActive
|
||||
? `No items match “${searchActive}”.`
|
||||
: 'No items yet — create the first one.'}
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{/* Pagination */}
|
||||
<nav
|
||||
aria-label="Pagination"
|
||||
className="mt-4 flex flex-wrap items-center justify-between gap-3"
|
||||
>
|
||||
<div className="flex items-center gap-3 text-sm text-slate-600">
|
||||
<label htmlFor="admin-page-size" className="inline-flex items-center gap-2">
|
||||
Rows per page
|
||||
<select
|
||||
id="admin-page-size"
|
||||
className="rounded-md border border-slate-300 bg-white py-1.5 pl-2 pr-7 text-sm"
|
||||
value={state.pageSize}
|
||||
onChange={(event) => onPageSizeChange(Number(event.target.value))}
|
||||
>
|
||||
{PAGE_SIZES.map((size) => (
|
||||
<option key={size} value={size}>
|
||||
{size}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{range && (
|
||||
<span aria-live="polite">
|
||||
Showing {range.start}–{range.end} of {range.total}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1">
|
||||
<button
|
||||
type="button"
|
||||
className="btn-secondary !px-3 !py-1.5"
|
||||
disabled={state.page <= 1 || loading}
|
||||
onClick={() => onPageChange(state.page - 1)}
|
||||
>
|
||||
Previous
|
||||
</button>
|
||||
{pageWindow(state.page, totalPages).map((page, index) =>
|
||||
page === '…' ? (
|
||||
<span key={`gap-${index}`} className="px-1.5 text-sm text-slate-400">
|
||||
…
|
||||
</span>
|
||||
) : (
|
||||
<button
|
||||
key={page}
|
||||
type="button"
|
||||
aria-current={page === state.page ? 'page' : undefined}
|
||||
className={cn(
|
||||
'min-w-[2.1rem] rounded-md px-2 py-1.5 text-sm font-medium',
|
||||
page === state.page
|
||||
? 'bg-blue-600 text-white'
|
||||
: 'border border-slate-300 bg-white text-slate-700 hover:bg-slate-100',
|
||||
)}
|
||||
disabled={loading}
|
||||
onClick={() => onPageChange(page)}
|
||||
>
|
||||
{page}
|
||||
</button>
|
||||
),
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="btn-secondary !px-3 !py-1.5"
|
||||
disabled={state.page >= totalPages || loading}
|
||||
onClick={() => onPageChange(state.page + 1)}
|
||||
>
|
||||
Next
|
||||
</button>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
{/* Delete confirmation dialog */}
|
||||
{pendingDelete && (
|
||||
<DeleteConfirmation
|
||||
item={pendingDelete}
|
||||
busy={deleteBusy}
|
||||
error={deleteError}
|
||||
onConfirm={() => void confirmDelete()}
|
||||
onCancel={cancelDelete}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default AdminDashboard;
|
||||
Reference in new issue
Block a user