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:
Daniel Samson committed 2026-10-30 21:36:15 +00:00
1 parent b186d0f797
commit b440809548
38 files changed
+5415 -50

No files matched your search

+346 -1
View File
@@ -9,8 +9,16 @@
"version": "0.1.0",
"license": "MIT",
"dependencies": {
"@lexical/code": "^0.25.0",
"@lexical/html": "^0.25.0",
"@lexical/link": "^0.25.0",
"@lexical/list": "^0.25.0",
"@lexical/react": "^0.25.0",
"@lexical/rich-text": "^0.25.0",
"@lexical/selection": "^0.25.0",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.0",
"lexical": "^0.25.0",
"lucide-react": "^0.263.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
@@ -356,7 +364,6 @@
"version": "7.29.10",
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.10.tgz",
"integrity": "sha512-NpugTzbKgGrNe45Ui32cN8vCFFMxVtP/9rtfwv0nP5FRDAjvYBxJcLVpYA9mr1jxP6cnIT7x9LUzuDTbWYYNRA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6.9.0"
@@ -1128,6 +1135,262 @@
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
"node_modules/@lexical/clipboard": {
"version": "0.25.0",
"resolved": "https://registry.npmjs.org/@lexical/clipboard/-/clipboard-0.25.0.tgz",
"integrity": "sha512-z0Dx6fDSLfbfK/LsfjkFbOTO87kHXQ6FNi8eCvVHtMLnME91kHTaotIalEdlS69Hw6032AThnEqeN5rAB24BlQ==",
"license": "MIT",
"dependencies": {
"@lexical/html": "0.25.0",
"@lexical/list": "0.25.0",
"@lexical/selection": "0.25.0",
"@lexical/utils": "0.25.0",
"lexical": "0.25.0"
}
},
"node_modules/@lexical/code": {
"version": "0.25.0",
"resolved": "https://registry.npmjs.org/@lexical/code/-/code-0.25.0.tgz",
"integrity": "sha512-jTUFIYbbsud4qdLV+zAYj1UhzC2LiKSly5uprsJgTvBwdZppexcNOiHFvH1kEODVXVSLgU6WCg0XROPB+fXh9A==",
"license": "MIT",
"dependencies": {
"@lexical/utils": "0.25.0",
"lexical": "0.25.0",
"prismjs": "^1.27.0"
}
},
"node_modules/@lexical/devtools-core": {
"version": "0.25.0",
"resolved": "https://registry.npmjs.org/@lexical/devtools-core/-/devtools-core-0.25.0.tgz",
"integrity": "sha512-DJl5reXPdohZulAfemZCzhkglJfSJnQbu7bAtBMhUx0U0t51YOycCqXcKeXwNge74h3T3aG4/N4fPV50Cq1izA==",
"license": "MIT",
"dependencies": {
"@lexical/html": "0.25.0",
"@lexical/link": "0.25.0",
"@lexical/mark": "0.25.0",
"@lexical/table": "0.25.0",
"@lexical/utils": "0.25.0",
"lexical": "0.25.0"
},
"peerDependencies": {
"react": ">=17.x",
"react-dom": ">=17.x"
}
},
"node_modules/@lexical/dragon": {
"version": "0.25.0",
"resolved": "https://registry.npmjs.org/@lexical/dragon/-/dragon-0.25.0.tgz",
"integrity": "sha512-mMMX2clk8nQHZEgPuVlTOPYMCH0Kg4EevJ4dg6q5sGJzkHjXerooGm+PYfLEcOk7SQC0YOhvW7gkM/UQYYHHWA==",
"license": "MIT",
"dependencies": {
"lexical": "0.25.0"
}
},
"node_modules/@lexical/hashtag": {
"version": "0.25.0",
"resolved": "https://registry.npmjs.org/@lexical/hashtag/-/hashtag-0.25.0.tgz",
"integrity": "sha512-di9pcBeCS/hx5z4EudOp7J6m4bNVqxVzm4J/15D4WDz6Jen3dh2Jha0N2pmFuHbOiuLyPAhYAV4PacFi5+ne+w==",
"license": "MIT",
"dependencies": {
"@lexical/utils": "0.25.0",
"lexical": "0.25.0"
}
},
"node_modules/@lexical/history": {
"version": "0.25.0",
"resolved": "https://registry.npmjs.org/@lexical/history/-/history-0.25.0.tgz",
"integrity": "sha512-mUkXhVZDbgUYkpjFLcMDSOorOVeX/l2eV2wxnju9hjodGenEfVK1yWv1A2siCiG0K9y8o1Eksa4F7zf3ZlXRuA==",
"license": "MIT",
"dependencies": {
"@lexical/utils": "0.25.0",
"lexical": "0.25.0"
}
},
"node_modules/@lexical/html": {
"version": "0.25.0",
"resolved": "https://registry.npmjs.org/@lexical/html/-/html-0.25.0.tgz",
"integrity": "sha512-bjO5RbMpyFw4H6kCgYcdAlxzhoF1tjtRZ1w0MxSHReLg9wqNaeg4uNwdW+uVMbxRv+cYqaO0To66qMAcND6tiQ==",
"license": "MIT",
"dependencies": {
"@lexical/selection": "0.25.0",
"@lexical/utils": "0.25.0",
"lexical": "0.25.0"
}
},
"node_modules/@lexical/link": {
"version": "0.25.0",
"resolved": "https://registry.npmjs.org/@lexical/link/-/link-0.25.0.tgz",
"integrity": "sha512-epFwgLWfmYgtXgI1n7oJJ3ana48qTm+WHEAYnFK7mxXEV6V93j5hm3MJgAJL4Lut/iHkrBXhT9PVMwkg75ImRQ==",
"license": "MIT",
"dependencies": {
"@lexical/utils": "0.25.0",
"lexical": "0.25.0"
}
},
"node_modules/@lexical/list": {
"version": "0.25.0",
"resolved": "https://registry.npmjs.org/@lexical/list/-/list-0.25.0.tgz",
"integrity": "sha512-hAEcNuE9WxDHJGUcwkTN+4sGn1/j5/wBqkuaYrBrhf7vCHeKUAu7er7T7Gdfj1HPfjqZm6YxdqFF4LYqejwuRg==",
"license": "MIT",
"dependencies": {
"@lexical/utils": "0.25.0",
"lexical": "0.25.0"
}
},
"node_modules/@lexical/mark": {
"version": "0.25.0",
"resolved": "https://registry.npmjs.org/@lexical/mark/-/mark-0.25.0.tgz",
"integrity": "sha512-J3T35abTjvri5rq+3P/exWdB6uHTQDmAi3gy1PkHSGLODhfKypo1gZdFY80QZmxcR9yewhMr9d9o5YwRsfZqSw==",
"license": "MIT",
"dependencies": {
"@lexical/utils": "0.25.0",
"lexical": "0.25.0"
}
},
"node_modules/@lexical/markdown": {
"version": "0.25.0",
"resolved": "https://registry.npmjs.org/@lexical/markdown/-/markdown-0.25.0.tgz",
"integrity": "sha512-KHj/AdjJIzCYtWRPyb8LjPo19gqGuLHu5Q3S2+n1OgCEwhpemPFHQPGk8AGd21jyF4h2psAe7d7ikMQj81wOrw==",
"license": "MIT",
"dependencies": {
"@lexical/code": "0.25.0",
"@lexical/link": "0.25.0",
"@lexical/list": "0.25.0",
"@lexical/rich-text": "0.25.0",
"@lexical/text": "0.25.0",
"@lexical/utils": "0.25.0",
"lexical": "0.25.0"
}
},
"node_modules/@lexical/offset": {
"version": "0.25.0",
"resolved": "https://registry.npmjs.org/@lexical/offset/-/offset-0.25.0.tgz",
"integrity": "sha512-3qcqMb07OyA174nB/ghWCj6fgGSPlqjYNzJ75xuvg1n8S3RpobDarin2iEEUb/n74wA4w5fwufJPe/Nu0NRJ/g==",
"license": "MIT",
"dependencies": {
"lexical": "0.25.0"
}
},
"node_modules/@lexical/overflow": {
"version": "0.25.0",
"resolved": "https://registry.npmjs.org/@lexical/overflow/-/overflow-0.25.0.tgz",
"integrity": "sha512-TEgn3HMx1pNI3VwlPcmFo29H+yLKvuX+zNlvdGwQh6tHHvw7DEyJ7iAuK74V4UZZT2bWcOr0ZArBYSDV/9bZtQ==",
"license": "MIT",
"dependencies": {
"lexical": "0.25.0"
}
},
"node_modules/@lexical/plain-text": {
"version": "0.25.0",
"resolved": "https://registry.npmjs.org/@lexical/plain-text/-/plain-text-0.25.0.tgz",
"integrity": "sha512-k0SG0mmsF/pKsvMMSnilysfu22NqapaNtJHtF3QPvOv8ryDuILm9HgwD8svALVvR9BI8PeCSspnoVKEELwVzCw==",
"license": "MIT",
"dependencies": {
"@lexical/clipboard": "0.25.0",
"@lexical/selection": "0.25.0",
"@lexical/utils": "0.25.0",
"lexical": "0.25.0"
}
},
"node_modules/@lexical/react": {
"version": "0.25.0",
"resolved": "https://registry.npmjs.org/@lexical/react/-/react-0.25.0.tgz",
"integrity": "sha512-cdrwfNyknAwbFyO+3vUDjRADJ/3yckVeUKrZSQN32/71kdIas4OXYDYbPNdsUVEiIvicTkQJof8naG+cj9LtTQ==",
"license": "MIT",
"dependencies": {
"@lexical/clipboard": "0.25.0",
"@lexical/code": "0.25.0",
"@lexical/devtools-core": "0.25.0",
"@lexical/dragon": "0.25.0",
"@lexical/hashtag": "0.25.0",
"@lexical/history": "0.25.0",
"@lexical/link": "0.25.0",
"@lexical/list": "0.25.0",
"@lexical/mark": "0.25.0",
"@lexical/markdown": "0.25.0",
"@lexical/overflow": "0.25.0",
"@lexical/plain-text": "0.25.0",
"@lexical/rich-text": "0.25.0",
"@lexical/selection": "0.25.0",
"@lexical/table": "0.25.0",
"@lexical/text": "0.25.0",
"@lexical/utils": "0.25.0",
"@lexical/yjs": "0.25.0",
"lexical": "0.25.0",
"react-error-boundary": "^3.1.4"
},
"peerDependencies": {
"react": ">=17.x",
"react-dom": ">=17.x"
}
},
"node_modules/@lexical/rich-text": {
"version": "0.25.0",
"resolved": "https://registry.npmjs.org/@lexical/rich-text/-/rich-text-0.25.0.tgz",
"integrity": "sha512-cNQeqKtJGnAp1ndRlohGoWcEE59WS17bfjMmPbbHbWUSlvFMIsa/7GopauW4KyuEjFkNNhDVEB21r1zDX97unA==",
"license": "MIT",
"dependencies": {
"@lexical/clipboard": "0.25.0",
"@lexical/selection": "0.25.0",
"@lexical/utils": "0.25.0",
"lexical": "0.25.0"
}
},
"node_modules/@lexical/selection": {
"version": "0.25.0",
"resolved": "https://registry.npmjs.org/@lexical/selection/-/selection-0.25.0.tgz",
"integrity": "sha512-zbUflzM5bAER5JyDXNbaw4s9w5kp8Y2oYqpplkZhMXj8Ri3CUE5bQgt4vH6XbyKVl4hsJlVcZ3qmw3HJAcnWNQ==",
"license": "MIT",
"dependencies": {
"lexical": "0.25.0"
}
},
"node_modules/@lexical/table": {
"version": "0.25.0",
"resolved": "https://registry.npmjs.org/@lexical/table/-/table-0.25.0.tgz",
"integrity": "sha512-gWOvqyz1eGv504fxH7r0hZACYgxEldr5GlzS2GoII3S1OjGhEOjBkM5JNMzATFaxvfdUkL2ywbmBfhk5hI/spg==",
"license": "MIT",
"dependencies": {
"@lexical/clipboard": "0.25.0",
"@lexical/utils": "0.25.0",
"lexical": "0.25.0"
}
},
"node_modules/@lexical/text": {
"version": "0.25.0",
"resolved": "https://registry.npmjs.org/@lexical/text/-/text-0.25.0.tgz",
"integrity": "sha512-u5WtmkbYYMePRQGAMFKqtbq4JhEMtSFwPYvtbS/5WUoYBf55IE+0kQA3meMK9MqBsxWil6TTekWOnKYmoLXv4w==",
"license": "MIT",
"dependencies": {
"lexical": "0.25.0"
}
},
"node_modules/@lexical/utils": {
"version": "0.25.0",
"resolved": "https://registry.npmjs.org/@lexical/utils/-/utils-0.25.0.tgz",
"integrity": "sha512-LAB/5OniVCDFMWh8zuKejqU4blAP5CEIpPXBtevbHROtbz3fqo/xqcHK3bGGP9w1UKYH0S6n+MA8Uv9hdVzf7w==",
"license": "MIT",
"dependencies": {
"@lexical/list": "0.25.0",
"@lexical/selection": "0.25.0",
"@lexical/table": "0.25.0",
"lexical": "0.25.0"
}
},
"node_modules/@lexical/yjs": {
"version": "0.25.0",
"resolved": "https://registry.npmjs.org/@lexical/yjs/-/yjs-0.25.0.tgz",
"integrity": "sha512-fRXLfwt7Qp897GqRnzQ5Ew+kWaFmdixRtD3BhGoMh8/KfvccbFeL7M4d29KbQe+jOWljlpO57X1sKBZ/OWNjJw==",
"license": "MIT",
"dependencies": {
"@lexical/offset": "0.25.0",
"@lexical/selection": "0.25.0",
"lexical": "0.25.0"
},
"peerDependencies": {
"yjs": ">=13.5.22"
}
},
"node_modules/@nodelib/fs.scandir": {
"version": "2.1.5",
"resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz",
@@ -4608,6 +4871,17 @@
"dev": true,
"license": "ISC"
},
"node_modules/isomorphic.js": {
"version": "0.2.5",
"resolved": "https://registry.npmjs.org/isomorphic.js/-/isomorphic.js-0.2.5.tgz",
"integrity": "sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw==",
"license": "MIT",
"peer": true,
"funding": {
"type": "GitHub Sponsors ❤",
"url": "https://github.com/sponsors/dmonad"
}
},
"node_modules/istanbul-lib-coverage": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz",
@@ -4847,6 +5121,34 @@
"node": ">= 0.8.0"
}
},
"node_modules/lexical": {
"version": "0.25.0",
"resolved": "https://registry.npmjs.org/lexical/-/lexical-0.25.0.tgz",
"integrity": "sha512-yZNfC+3Df/qGAbGD1Lsh+dkG0COJKGuDlT1e/t0qS9F1jaKvoz7Fm0tACQ3eRTbOYncJiaJveLiT9GADac2hrA==",
"license": "MIT"
},
"node_modules/lib0": {
"version": "0.2.119",
"resolved": "https://registry.npmjs.org/lib0/-/lib0-0.2.119.tgz",
"integrity": "sha512-vh+TiejVy8Xm+hCdnRfn9BthGNvNUZdEXltNjVZL3TzRIKP3s1lnQh8pWd/Q0wCgY0FPAGVVjFF4ZiHUV3LFgA==",
"license": "MIT",
"peer": true,
"dependencies": {
"isomorphic.js": "^0.2.4"
},
"bin": {
"0ecdsa-generate-keypair": "bin/0ecdsa-generate-keypair.js",
"0gentesthtml": "bin/gentesthtml.js",
"0serve": "bin/0serve.js"
},
"engines": {
"node": ">=16"
},
"funding": {
"type": "GitHub Sponsors ❤",
"url": "https://github.com/sponsors/dmonad"
}
},
"node_modules/lilconfig": {
"version": "3.1.4",
"resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.4.tgz",
@@ -5799,6 +6101,15 @@
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
}
},
"node_modules/prismjs": {
"version": "1.30.0",
"resolved": "https://registry.npmjs.org/prismjs/-/prismjs-1.30.0.tgz",
"integrity": "sha512-DEvV2ZF2r2/63V+tK8hQvrR2ZGn10srHbXviTlcv7Kpzw8jWiNTqbVgjO3IY8RxrrOUF8VPMQQFysYYYv0YZxw==",
"license": "MIT",
"engines": {
"node": ">=6"
}
},
"node_modules/prop-types": {
"version": "15.8.1",
"resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",
@@ -5894,6 +6205,22 @@
"react": "^18.3.1"
}
},
"node_modules/react-error-boundary": {
"version": "3.1.4",
"resolved": "https://registry.npmjs.org/react-error-boundary/-/react-error-boundary-3.1.4.tgz",
"integrity": "sha512-uM9uPzZJTF6wRQORmSrvOIgt4lJ9MC1sNgEOj2XGsDTRE4kmpWxg7ENK9EWNKJRMAOY9z0MuF4yIfl6gp4sotA==",
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.12.5"
},
"engines": {
"node": ">=10",
"npm": ">=6"
},
"peerDependencies": {
"react": ">=16.13.1"
}
},
"node_modules/react-is": {
"version": "17.0.2",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
@@ -7579,6 +7906,24 @@
"dev": true,
"license": "ISC"
},
"node_modules/yjs": {
"version": "13.6.33",
"resolved": "https://registry.npmjs.org/yjs/-/yjs-13.6.33.tgz",
"integrity": "sha512-q/UYvr1gOk4XII+Cu1CW2dINjYqJJFifTzogEaIARznrvX7uOlHsdTEXcnOBMuIsrCGEEKdNxi74kyMLZlKVfw==",
"license": "MIT",
"peer": true,
"dependencies": {
"lib0": "^0.2.99"
},
"engines": {
"node": ">=16.0.0",
"npm": ">=8.0.0"
},
"funding": {
"type": "GitHub Sponsors ❤",
"url": "https://github.com/sponsors/dmonad"
}
},
"node_modules/yocto-queue": {
"version": "0.1.0",
"resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",
+8
View File
@@ -20,8 +20,16 @@
"lint": "eslint . --ext .js,.jsx,.ts,.tsx"
},
"dependencies": {
"@lexical/code": "^0.25.0",
"@lexical/html": "^0.25.0",
"@lexical/link": "^0.25.0",
"@lexical/list": "^0.25.0",
"@lexical/react": "^0.25.0",
"@lexical/rich-text": "^0.25.0",
"@lexical/selection": "^0.25.0",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.0",
"lexical": "^0.25.0",
"lucide-react": "^0.263.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
+408
View File
@@ -0,0 +1,408 @@
import { expect, test, type Page } from '@playwright/test';
/**
* E2E tests for the admin area (M6) with a fully mocked backend
* (in-memory item store + token-based auth), following the approach of
* the other specs in this directory.
*/
const ADMIN_TOKEN = 'mock-admin-token';
const USER_TOKEN = 'mock-user-token';
const TOKEN_KEY = 'AUTH_TOKEN';
interface Item {
id: number;
title: string;
url: string;
points: number;
username: string;
content: string;
created_at: string;
}
const envelope = (detail: string, code: string) => JSON.stringify({ detail, code });
/** Build the auth + admin API mock with a per-test item store. */
function mockAdminApi(page: Page): { store: Item[]; nextId: () => number } {
let idCounter = 100;
const store: Item[] = [
{
id: 1,
title: 'Breaking: local cat discovers keyboard',
url: 'https://example.com/cat-keyboard',
points: 42,
username: 'alice',
content: '<p>Amazing news.</p>',
created_at: '2024-05-01T10:00:00Z',
},
{
id: 2,
title: 'Study: coffee improves code reviews',
url: 'https://example.com/coffee-reviews',
points: 17,
username: 'bob',
content: '<p>Peer-reviewed.</p>',
created_at: '2024-05-02T11:30:00Z',
},
{
id: 3,
title: 'Show HN: I built a tiny news app',
url: 'https://example.com/show-hn-newz',
points: 5,
username: 'alice',
content: '<p>Feedback welcome.</p>',
created_at: '2024-05-03T09:15:00Z',
},
];
const requireAdmin = (route: Parameters<Parameters<Page['route']>[1]>[0]): boolean => {
const header = route.request().headers()['authorization'];
if (header !== `Bearer ${ADMIN_TOKEN}`) {
route.fulfill({
status: 403,
contentType: 'application/json',
body: envelope('Admin access required', 'forbidden'),
});
return false;
}
return true;
};
page.route('**/api/v1/auth/me', (route) => {
const header = route.request().headers()['authorization'];
if (header === `Bearer ${ADMIN_TOKEN}`) {
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ username: 'alice', is_admin: true }),
});
}
if (header === `Bearer ${USER_TOKEN}`) {
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ username: 'bob', is_admin: false }),
});
}
return route.fulfill({
status: 401,
contentType: 'application/json',
body: envelope('Invalid or expired token', 'unauthorized'),
});
});
page.route('**/api/v1/auth/logout', (route) => route.fulfill({ status: 204 }));
// Collection endpoint: GET (list) + POST (create).
page.route(/\/api\/v1\/admin\/items(\?.*)?$/, (route) => {
const request = route.request();
if (request.method() === 'GET') {
if (!requireAdmin(route)) return;
const url = new URL(request.url());
const search = (url.searchParams.get('search') ?? '').toLowerCase();
const sortBy = (url.searchParams.get('sort_by') ?? 'created_at') as keyof Item;
const sortOrder = url.searchParams.get('sort_order') ?? 'desc';
const pageSize = Number(url.searchParams.get('page_size') ?? 20);
const page_ = Number(url.searchParams.get('page') ?? 1);
const filtered = store.filter(
(item) =>
!search ||
item.title.toLowerCase().includes(search) ||
item.url.toLowerCase().includes(search),
);
filtered.sort((a, b) => {
const cmp = String(a[sortBy]).localeCompare(String(b[sortBy]));
return sortOrder === 'asc' ? cmp : -cmp;
});
const start = (page_ - 1) * pageSize;
const slice = filtered.slice(start, start + pageSize);
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
items: slice,
total: filtered.length,
page: page_,
page_size: pageSize,
total_pages: Math.ceil(filtered.length / pageSize) || 0,
}),
});
}
if (request.method() === 'POST') {
if (!requireAdmin(route)) return;
const body = request.postDataJSON() as Partial<Item>;
const item: Item = {
id: ++idCounter,
title: body.title ?? '',
url: body.url ?? '',
points: body.points ?? 0,
username: body.username ?? 'alice',
content: body.content ?? '',
created_at: new Date().toISOString(),
};
store.push(item);
return route.fulfill({
status: 201,
contentType: 'application/json',
body: JSON.stringify(item),
});
}
return route.fulfill({ status: 405, contentType: 'application/json', body: envelope('Method not allowed', 'method_not_allowed') });
});
// Item endpoint: GET / PUT / DELETE by id.
page.route('**/api/v1/admin/items/*', (route) => {
const request = route.request();
const id = Number(request.url().split('/').pop());
if (!requireAdmin(route)) return;
const item = store.find((entry) => entry.id === id);
if (request.method() === 'GET') {
if (!item) {
return route.fulfill({
status: 404,
contentType: 'application/json',
body: envelope('Item not found', 'not_found'),
});
}
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(item) });
}
if (request.method() === 'PUT') {
if (!item) {
return route.fulfill({
status: 404,
contentType: 'application/json',
body: envelope('Item not found', 'not_found'),
});
}
const body = request.postDataJSON() as Partial<Item>;
Object.assign(item, body);
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(item) });
}
if (request.method() === 'DELETE') {
if (!item) {
return route.fulfill({
status: 404,
contentType: 'application/json',
body: envelope('Item not found', 'not_found'),
});
}
store.splice(store.indexOf(item), 1);
return route.fulfill({ status: 204 });
}
return route.fulfill({ status: 405, contentType: 'application/json', body: envelope('Method not allowed', 'method_not_allowed') });
});
return { store, nextId: () => idCounter };
}
async function seedToken(page: Page, token: string | null): Promise<void> {
if (token === null) {
await page.addInitScript((key) => localStorage.removeItem(key), TOKEN_KEY);
} else {
await page.addInitScript(
([key, value]) => localStorage.setItem(key, value),
[TOKEN_KEY, token] as const,
);
}
}
test.describe('admin area (M6)', () => {
test('signed-out users are redirected to /login', async ({ page }) => {
mockAdminApi(page);
await seedToken(page, null);
await page.goto('/admin');
await expect(page).toHaveURL('/login');
});
test('non-admins see the 403 page', async ({ page }) => {
mockAdminApi(page);
await seedToken(page, USER_TOKEN);
await page.goto('/admin');
await expect(page.getByRole('heading', { level: 1, name: '403' })).toBeVisible();
await expect(
page.getByTestId('forbidden-page').getByText(/admin area/i),
).toBeVisible();
});
test('admins see the dashboard with all items and an Admin header link', async ({
page,
}) => {
mockAdminApi(page);
await seedToken(page, ADMIN_TOKEN);
// The header exposes the admin link for admin accounts.
await page.goto('/');
await expect(page.getByRole('navigation', { name: 'Main navigation' }).getByRole('link', { name: /admin/i })).toBeVisible();
await page.goto('/admin');
await expect(page.getByRole('heading', { level: 1, name: 'Items' })).toBeVisible();
await expect(page.getByText('Breaking: local cat discovers keyboard')).toBeVisible();
await expect(page.getByText('Study: coffee improves code reviews')).toBeVisible();
await expect(page.getByText('Show HN: I built a tiny news app')).toBeVisible();
await expect(page.getByText('Showing 1–3 of 3')).toBeVisible();
});
test('non-admin accounts do not get the Admin header link', async ({ page }) => {
mockAdminApi(page);
await seedToken(page, USER_TOKEN);
await page.goto('/');
await expect(
page.getByRole('navigation', { name: 'Main navigation' }).getByRole('link', { name: /admin/i }),
).toHaveCount(0);
});
test('search filters the list by title or URL', async ({ page }) => {
mockAdminApi(page);
await seedToken(page, ADMIN_TOKEN);
await page.goto('/admin');
await expect(page.getByText('Breaking: local cat discovers keyboard')).toBeVisible();
await page.getByLabel('Search items').fill('coffee');
await expect(page.getByText('Study: coffee improves code reviews')).toBeVisible();
await expect(
page.getByText('Breaking: local cat discovers keyboard'),
).toHaveCount(0);
// URL search (case-insensitive on the server side).
await page.getByLabel('Search items').fill('EXAMPLE.COM/CAT');
await expect(page.getByText('Breaking: local cat discovers keyboard')).toBeVisible();
await expect(page.getByText('Showing 1–1 of 1')).toBeVisible();
});
test('sorting by title toggles direction', async ({ page }) => {
mockAdminApi(page);
await seedToken(page, ADMIN_TOKEN);
await page.goto('/admin');
const firstTitle = page.locator('tbody tr').first().locator('td').first().locator('span, a').first();
// Default: created_at desc -> newest first.
await expect(firstTitle).toHaveText('Show HN: I built a tiny news app');
await page.getByRole('button', { name: /sort by title/i }).click();
await expect(firstTitle).toHaveText('Breaking: local cat discovers keyboard');
await page.getByRole('button', { name: /sort by title/i }).click();
await expect(firstTitle).toHaveText('Study: coffee improves code reviews');
});
test('create: fills the form, saves with the Lexical editor and lists the item', async ({
page,
}) => {
const { store } = mockAdminApi(page);
await seedToken(page, ADMIN_TOKEN);
await page.goto('/admin/items/new');
await expect(page.getByRole('heading', { level: 1, name: 'New item' })).toBeVisible();
await page.getByLabel(/^Title/).fill('E2E: fresh story from the admin area');
await page.getByLabel(/^URL/).fill('https://example.com/e2e-story');
await page.getByLabel('Points').fill('3');
// The author is pre-filled from the session.
await expect(page.getByLabel('Author')).toHaveValue('alice');
// Type into the Lexical contenteditable (rich text editor).
await page.getByLabel('Item content').click();
await page.keyboard.type('Written with the Lexical editor.');
await page.getByRole('button', { name: /create item/i }).click();
// Back on the dashboard with the success notice.
await expect(page).toHaveURL('/admin');
await expect(page.getByRole('status')).toHaveText(/was saved/i);
await expect(page.getByText('E2E: fresh story from the admin area', { exact: true })).toBeVisible();
// The backend received the rich content.
const created = store.find((item) =>
item.title.includes('E2E: fresh story'),
);
expect(created).toBeTruthy();
expect(created?.content).toContain('Written with the Lexical editor.');
expect(created?.points).toBe(3);
expect(created?.username).toBe('alice');
});
test('edit: loads the item, updates fields and saves', async ({ page }) => {
const { store } = mockAdminApi(page);
await seedToken(page, ADMIN_TOKEN);
await page.goto('/admin');
await page.locator('tbody tr', { hasText: 'Breaking: local cat' }).getByRole('link', { name: /edit/i }).click();
await expect(page.getByRole('heading', { level: 1, name: /edit item/i })).toBeVisible();
await expect(page.getByLabel(/^Title/)).toHaveValue('Breaking: local cat discovers keyboard');
await expect(page.getByLabel('Points')).toHaveValue('42');
await page.getByLabel(/^Title/).fill('Breaking: local cat becomes famous');
await page.getByRole('button', { name: /save changes/i }).click();
await expect(page).toHaveURL('/admin');
await expect(page.getByRole('status')).toHaveText(/was saved/i);
await expect(page.getByRole('cell', { name: 'Breaking: local cat becomes famous', exact: true })).toBeVisible();
const updated = store.find((item) => item.id === 1);
expect(updated?.title).toBe('Breaking: local cat becomes famous');
// Untouched fields survive the partial save.
expect(updated?.points).toBe(42);
});
test('delete: requires confirmation, then removes the item', async ({ page }) => {
const { store } = mockAdminApi(page);
await seedToken(page, ADMIN_TOKEN);
await page.goto('/admin');
const target = page.getByText('Study: coffee improves code reviews');
await expect(target).toBeVisible();
// Open the confirmation dialog (first row's delete button).
page.locator('tbody tr', { hasText: 'Study: coffee' }).getByRole('button', { name: /delete/i }).click();
const dialog = page.getByRole('dialog');
await expect(dialog).toBeVisible();
await expect(
dialog.getByRole('heading', { name: /are you sure you want to delete/i }),
).toBeVisible();
await expect(dialog.getByText(/cannot be undone/i)).toBeVisible();
// Cancel keeps the item.
await dialog.getByRole('button', { name: /cancel/i }).click();
await expect(dialog).toHaveCount(0);
await expect(target).toBeVisible();
expect(store).toHaveLength(3);
// Confirm with the explicit "Yes, delete" action.
page.locator('tbody tr', { hasText: 'Study: coffee' }).getByRole('button', { name: /delete/i }).click();
await expect(page.getByRole('dialog')).toBeVisible();
await page.getByRole('button', { name: /yes, delete/i }).click();
await expect(page.getByText('Breaking: local cat discovers keyboard')).toBeVisible();
await expect(page.getByRole('cell', { name: 'Study: coffee improves code reviews', exact: true })).toHaveCount(0);
await expect(page.getByRole('status')).toHaveText(/was deleted/i);
expect(store).toHaveLength(2);
});
test('pagination: next/previous and the page size selector work', async ({ page }) => {
mockAdminApi(page);
await seedToken(page, ADMIN_TOKEN);
await page.goto('/admin');
// 3 seeded items fit on one page: navigation is disabled.
await expect(page.getByRole('button', { name: /next/i })).toBeDisabled();
await expect(page.getByRole('button', { name: /previous/i })).toBeDisabled();
// Smaller page size splits the list across pages.
await page.getByLabel('Rows per page').selectOption('10');
await expect(page).toHaveURL(/\/admin/);
// (Still one page for 3 items — assert the selector round-trips.)
await expect(page.getByLabel('Rows per page')).toHaveValue('10');
});
});
+55 -25
View File
@@ -1,9 +1,12 @@
import { BrowserRouter, Link, Route, Routes } from 'react-router-dom';
import { AuthProvider, RequireAuth } from './auth';
import { AuthProvider, RequireAdmin, RequireAuth } from './auth';
import AdminLayout from './components/AdminLayout';
import Layout from './components/ui/Layout';
import Account from './pages/Account';
import AdminDashboard from './pages/AdminDashboard';
import ArticlePage from './pages/ArticlePage';
import CategoriesPage from './pages/CategoriesPage';
import EditItemPage from './pages/EditItemPage';
import Home from './pages/Home';
import Login from './pages/Login';
import Register from './pages/Register';
@@ -28,10 +31,15 @@ function NotFound() {
* Root component: owns the React Router + auth setup.
*
* BrowserRouter wraps the whole app; AuthProvider restores the JWT
* session and exposes login/register/logout (see src/auth.tsx); Layout
* provides the shared shell (header/footer); Routes maps URLs to page
* components in src/pages/. In-app navigation always uses
* react-router-dom <Link>/<NavLink>.
* session and exposes login/register/logout (see src/auth.tsx).
*
* Two shells are used:
* - the admin area (`/admin/*`, M6) renders inside its own dark sidebar
* layout (`AdminLayout`) and is guarded by `RequireAdmin`;
* - everything else renders inside the public site `Layout`
* (header/footer) with `RequireAuth` guarding the account page.
*
* In-app navigation always uses react-router-dom <Link>/<NavLink>.
*/
export default function App() {
return (
@@ -42,26 +50,48 @@ export default function App() {
}}
>
<AuthProvider>
<Layout>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/articles" element={<ArticlePage />} />
<Route path="/articles/:id" element={<ArticlePage />} />
<Route path="/categories" element={<CategoriesPage />} />
<Route path="/login" element={<Login />} />
<Route path="/register" element={<Register />} />
<Route path="/sign-out" element={<SignOut />} />
<Route
path="/account"
element={
<RequireAuth>
<Account />
</RequireAuth>
}
/>
<Route path="*" element={<NotFound />} />
</Routes>
</Layout>
<Routes>
{/* Admin area (own shell, admin-only) */}
<Route
path="/admin"
element={
<RequireAdmin>
<AdminLayout />
</RequireAdmin>
}
>
<Route index element={<AdminDashboard />} />
<Route path="items/new" element={<EditItemPage />} />
<Route path="items/:id/edit" element={<EditItemPage />} />
</Route>
{/* Public site */}
<Route
path="*"
element={
<Layout>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/articles" element={<ArticlePage />} />
<Route path="/articles/:id" element={<ArticlePage />} />
<Route path="/categories" element={<CategoriesPage />} />
<Route path="/login" element={<Login />} />
<Route path="/register" element={<Register />} />
<Route path="/sign-out" element={<SignOut />} />
<Route
path="/account"
element={
<RequireAuth>
<Account />
</RequireAuth>
}
/>
<Route path="*" element={<NotFound />} />
</Routes>
</Layout>
}
/>
</Routes>
</AuthProvider>
</BrowserRouter>
);
+46
View File
@@ -0,0 +1,46 @@
/**
* Admin API client (item CRUD, admin-only endpoints).
*
* Built on the shared fetch wrapper from `api/client.ts`, which attaches
* the JWT session token to every request. All endpoints require the
* `is_admin` flag server-side; non-admins receive 403 (see the backend
* `api/v1/admin.py`).
*/
import { api } from './client';
import type {
AdminItem,
AdminItemInput,
AdminItemsPage,
AdminListParams,
} from '../types/admin';
/** `GET /api/v1/admin/items` — paginated, searchable, sortable list. */
export function adminListItems(params: AdminListParams): Promise<AdminItemsPage> {
const query = new URLSearchParams();
query.set('page', String(params.page));
query.set('page_size', String(params.pageSize));
if (params.search.trim()) query.set('search', params.search.trim());
query.set('sort_by', params.sortBy);
query.set('sort_order', params.sortOrder);
return api.get<AdminItemsPage>(`/admin/items?${query.toString()}`);
}
/** `GET /api/v1/admin/items/{id}` — a single item (including content). */
export function adminGetItem(id: number): Promise<AdminItem> {
return api.get<AdminItem>(`/admin/items/${id}`);
}
/** `POST /api/v1/admin/items` — create a new item. */
export function adminCreateItem(input: AdminItemInput): Promise<AdminItem> {
return api.post<AdminItem>('/admin/items', input);
}
/** `PUT /api/v1/admin/items/{id}` — update an item. */
export function adminUpdateItem(id: number, input: AdminItemInput): Promise<AdminItem> {
return api.put<AdminItem>(`/admin/items/${id}`, input);
}
/** `DELETE /api/v1/admin/items/{id}` — hard-delete an item (204). */
export function adminDeleteItem(id: number): Promise<void> {
return api.delete<void>(`/admin/items/${id}`);
}
+339
View File
@@ -0,0 +1,339 @@
/* ==========================================================================
newzy admin area (M6)
Admin shell (fixed sidebar + main content) and Lexical editor content.
Loaded after globals.css; scoped under .admin-shell / .lex-editor.
========================================================================== */
/* --- Admin shell ---------------------------------------------------------- */
.admin-shell {
display: flex;
min-height: 100vh;
background: #f8fafc;
}
/* Sidebar: fixed 250px column on desktop, slide-in overlay on mobile. */
.admin-sidebar {
width: 250px;
flex-shrink: 0;
display: flex;
flex-direction: column;
background: #0f172a;
color: #cbd5e1;
padding: 1rem 0.75rem;
position: sticky;
top: 0;
height: 100vh;
z-index: 50;
}
.admin-sidebar__brand {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.25rem 0.75rem 1rem;
font-size: 1.05rem;
font-weight: 700;
color: #f8fafc;
letter-spacing: -0.01em;
}
.admin-sidebar__brand span {
opacity: 0.6;
font-weight: 500;
font-size: 0.85rem;
}
.admin-sidebar__nav {
display: flex;
flex-direction: column;
gap: 0.25rem;
flex: 1;
}
.admin-sidebar__link {
display: flex;
align-items: center;
gap: 0.6rem;
padding: 0.55rem 0.75rem;
border-radius: 0.5rem;
font-size: 0.875rem;
font-weight: 500;
color: #cbd5e1;
transition: background-color 150ms, color 150ms;
}
.admin-sidebar__link:hover {
background: #1e293b;
color: #f8fafc;
}
.admin-sidebar__link.is-active {
background: #1d4ed8;
color: #ffffff;
}
.admin-sidebar__footer {
border-top: 1px solid #1e293b;
padding-top: 0.75rem;
margin-top: 0.75rem;
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.admin-sidebar__user {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0 0.75rem;
font-size: 0.8rem;
color: #94a3b8;
overflow: hidden;
}
.admin-sidebar__user strong {
color: #e2e8f0;
font-weight: 600;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
/* Main content: offset by the sidebar on desktop. */
.admin-main {
flex: 1;
min-width: 0;
padding: 2rem 2rem 3rem;
}
.admin-main__inner {
max-width: 56rem;
margin: 0 auto;
}
/* Mobile top bar with the sidebar toggle (< md). */
.admin-mobilebar {
display: none;
}
@media (max-width: 767px) {
.admin-sidebar {
position: fixed;
left: 0;
top: 0;
bottom: 0;
transform: translateX(-100%);
transition: transform 200ms ease-out;
box-shadow: 0 0 40px rgba(15, 23, 42, 0.4);
}
.admin-sidebar.is-open {
transform: translateX(0);
}
.admin-main {
padding: 1rem 1rem 2.5rem;
}
.admin-mobilebar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
padding: 0.65rem 1rem;
background: #0f172a;
color: #f8fafc;
font-weight: 600;
font-size: 0.95rem;
}
.admin-mobilebar__toggle {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 0.4rem;
border-radius: 0.5rem;
color: #cbd5e1;
background: transparent;
}
.admin-mobilebar__toggle:hover {
background: #1e293b;
color: #f8fafc;
}
/* Backdrop behind the slide-in sidebar. */
.admin-backdrop {
position: fixed;
inset: 0;
background: rgba(15, 23, 42, 0.5);
z-index: 40;
}
}
/* --- Lexical editor -------------------------------------------------------- */
.lex-editor {
border: 1px solid #cbd5e1;
border-radius: 0.5rem;
background: #ffffff;
overflow: hidden;
}
.lex-editor__toolbar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.25rem;
padding: 0.4rem 0.5rem;
border-bottom: 1px solid #e2e8f0;
background: #f8fafc;
}
.lex-toolbar-btn {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 1.9rem;
height: 1.9rem;
padding: 0 0.35rem;
border-radius: 0.375rem;
font-size: 0.8rem;
font-weight: 600;
color: #475569;
background: transparent;
transition: background-color 120ms, color 120ms;
}
.lex-toolbar-btn:hover {
background: #e2e8f0;
color: #0f172a;
}
.lex-toolbar-btn.is-active {
background: #1d4ed8;
color: #ffffff;
}
.lex-toolbar-btn:disabled {
opacity: 0.4;
cursor: not-allowed;
}
.lex-toolbar-sep {
width: 1px;
height: 1.4rem;
background: #e2e8f0;
margin: 0 0.25rem;
}
.lex-toolbar-select {
height: 1.9rem;
border-radius: 0.375rem;
border: 1px solid #e2e8f0;
background: #ffffff;
padding: 0 0.3rem;
font-size: 0.8rem;
color: #334155;
}
.lex-toolbar-link {
display: inline-flex;
align-items: center;
gap: 0.3rem;
}
.lex-toolbar-link input {
width: 11rem;
height: 1.9rem;
border-radius: 0.375rem;
border: 1px solid #bfdbfe;
padding: 0 0.5rem;
font-size: 0.8rem;
}
/* Editor content (Lexical theme classes are mapped to these). */
.lex-editor__content {
min-height: 14rem;
max-height: 32rem;
overflow-y: auto;
padding: 1rem 1.25rem;
outline: none;
font-size: 0.925rem;
line-height: 1.65;
color: #0f172a;
}
.lex-editor__content p {
margin: 0.5rem 0;
}
.lex-editor__content h1 {
font-size: 1.6rem;
font-weight: 700;
margin: 1rem 0 0.5rem;
}
.lex-editor__content h2 {
font-size: 1.35rem;
font-weight: 700;
margin: 0.9rem 0 0.4rem;
}
.lex-editor__content h3 {
font-size: 1.15rem;
font-weight: 600;
margin: 0.8rem 0 0.35rem;
}
.lex-editor__content h4,
.lex-editor__content h5,
.lex-editor__content h6 {
font-size: 1rem;
font-weight: 600;
margin: 0.7rem 0 0.3rem;
}
.lex-editor__content ul {
list-style: disc;
padding-left: 1.4rem;
margin: 0.5rem 0;
}
.lex-editor__content ol {
list-style: decimal;
padding-left: 1.4rem;
margin: 0.5rem 0;
}
.lex-editor__content a {
color: #1d4ed8;
text-decoration: underline;
}
.lex-editor__content pre {
background: #0f172a;
color: #e2e8f0;
border-radius: 0.5rem;
padding: 0.85rem 1rem;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 0.85rem;
overflow-x: auto;
margin: 0.75rem 0;
white-space: pre-wrap;
}
.lex-editor__content blockquote {
border-left: 3px solid #cbd5e1;
padding-left: 0.9rem;
color: #475569;
margin: 0.5rem 0;
}
/* Placeholder for the empty editor. */
.lex-editor__placeholder {
position: absolute;
pointer-events: none;
color: #94a3b8;
}
+56 -5
View File
@@ -5,7 +5,11 @@
* stored under `AUTH_TOKEN` against `GET /api/v1/auth/me`, drops it
* when invalid/expired) and exposes `login` / `register` / `logout`.
* - The JWT is attached to every API request automatically (see
* `api/client.ts`); this module only owns the username + ready state.
* `api/client.ts`); this module owns username, admin flag and ready
* state.
* - `RequireAuth` guards signed-in routes; `RequireAdmin` (M6)
* additionally requires the `is_admin` flag and renders a 403 page
* for authenticated non-admins.
*/
import {
ReactNode,
@@ -16,7 +20,7 @@ import {
useMemo,
useState,
} from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { Link, Navigate, useLocation } from 'react-router-dom';
import {
TOKEN_KEY,
login as apiLogin,
@@ -28,6 +32,8 @@ import {
export interface AuthState {
/** Logged-in username, or `null` when signed out. */
username: string | null;
/** Whether the signed-in user may access the admin area (M6). */
isAdmin: boolean;
/** `false` until the initial session-restore attempt has finished. */
ready: boolean;
/** Authenticate; stores the returned JWT and signs the user in. */
@@ -42,6 +48,7 @@ const AuthContext = createContext<AuthState | null>(null);
export function AuthProvider({ children }: { children: ReactNode }) {
const [username, setUsername] = useState<string | null>(null);
const [isAdmin, setIsAdmin] = useState(false);
const [ready, setReady] = useState(false);
// Restore the session on first load: validate the stored token and drop
@@ -53,7 +60,10 @@ export function AuthProvider({ children }: { children: ReactNode }) {
return;
}
apiMe(stored)
.then((user) => setUsername(user.username))
.then((user) => {
setUsername(user.username);
setIsAdmin(user.is_admin ?? false);
})
.catch(() => localStorage.removeItem(TOKEN_KEY))
.finally(() => setReady(true));
}, []);
@@ -62,12 +72,14 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const res = await apiLogin(name, password);
localStorage.setItem(TOKEN_KEY, res.token);
setUsername(res.username);
setIsAdmin(res.is_admin ?? false);
}, []);
const register = useCallback(async (name: string, password: string) => {
const res = await apiRegister(name, password);
localStorage.setItem(TOKEN_KEY, res.token);
setUsername(res.username);
setIsAdmin(res.is_admin ?? false);
}, []);
const logout = useCallback(() => {
@@ -76,11 +88,12 @@ export function AuthProvider({ children }: { children: ReactNode }) {
apiLogout().catch(() => undefined);
localStorage.removeItem(TOKEN_KEY);
setUsername(null);
setIsAdmin(false);
}, []);
const value = useMemo(
() => ({ username, ready, login, register, logout }),
[username, ready, login, register, logout],
() => ({ username, isAdmin, ready, login, register, logout }),
[username, isAdmin, ready, login, register, logout],
);
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
@@ -114,3 +127,41 @@ export function RequireAuth({ children }: { children: ReactNode }) {
}
return <>{children}</>;
}
/**
* Route guard for the admin area (M6): behaves like `RequireAuth` but
* additionally requires the `is_admin` flag. Authenticated non-admins
* see a 403 page (the server enforces the same rule on every admin
* endpoint, so this is UX, not security).
*/
export function RequireAdmin({ children }: { children: ReactNode }) {
const { username, isAdmin, ready } = useAuth();
const location = useLocation();
if (!ready) {
return (
<div className="container-page flex justify-center py-16" role="status">
<span className="animate-pulse text-sm text-slate-500">Checking session…</span>
</div>
);
}
if (username === null) {
return <Navigate to="/login" replace state={{ from: location.pathname }} />;
}
if (!isAdmin) {
return (
<div className="container-page text-center" data-testid="forbidden-page" role="alert">
<h1 className="mb-2 text-5xl font-bold text-slate-900">403</h1>
<p className="mb-1 text-lg font-semibold text-slate-700">Forbidden</p>
<p className="mb-6 text-sm text-slate-600">
Your account does not have access to the admin area. Ask a site
administrator if you believe this is a mistake.
</p>
<Link to="/" className="btn">
Back to home
</Link>
</div>
);
}
return <>{children}</>;
}
+134
View File
@@ -0,0 +1,134 @@
/**
* Admin area shell (M6): dark fixed sidebar (250px) with navigation,
* "back to newzy" link and the signed-in user, plus the routed page
* content in the main area. Responsive: the sidebar becomes a slide-in
* overlay with a mobile top bar below the `md` breakpoint.
*
* Routes are guarded by `RequireAdmin` (see `App.tsx`); this component
* is pure presentation + navigation.
*/
import {
ArrowLeft,
LayoutDashboard,
LogOut,
Menu,
Plus,
ShieldCheck,
X,
} from 'lucide-react';
import { useEffect, useState } from 'react';
import { Link, NavLink, Outlet, useLocation } from 'react-router-dom';
import { useAuth } from '../auth';
import { cn } from '../lib/utils';
export interface AdminLayoutProps {
/** Extra classes for the outer shell. */
className?: string;
}
const sidebarLinkClasses = ({ isActive }: { isActive: boolean }): string =>
cn('admin-sidebar__link', isActive && 'is-active');
/**
* Layout wrapper for the `/admin` routes. Renders the sidebar, the
* mobile top bar and the current route via `<Outlet/>`.
*/
export function AdminLayout({ className }: AdminLayoutProps) {
const { username } = useAuth();
const [mobileOpen, setMobileOpen] = useState(false);
const location = useLocation();
// Close the mobile sidebar on route changes.
useEffect(() => {
setMobileOpen(false);
}, [location.pathname]);
// Close on Escape while the mobile sidebar is open.
useEffect(() => {
if (!mobileOpen) return;
const onKey = (event: KeyboardEvent) => {
if (event.key === 'Escape') setMobileOpen(false);
};
document.addEventListener('keydown', onKey);
return () => document.removeEventListener('keydown', onKey);
}, [mobileOpen]);
return (
<div className={cn('admin-shell', className)} data-testid="admin-layout">
{mobileOpen && (
<div
className="admin-backdrop"
aria-hidden="true"
onClick={() => setMobileOpen(false)}
/>
)}
{/* Mobile top bar (sidebar collapses on small screens) */}
<div className="admin-mobilebar">
<span className="flex items-center gap-2">
<ShieldCheck size={18} aria-hidden="true" />
newzy <span aria-hidden="true" style={{ opacity: 0.6 }}>admin</span>
</span>
<button
type="button"
className="admin-mobilebar__toggle"
aria-label={mobileOpen ? 'Close menu' : 'Open menu'}
aria-expanded={mobileOpen}
aria-controls="admin-sidebar"
onClick={() => setMobileOpen((open) => !open)}
>
{mobileOpen ? <X size={20} aria-hidden="true" /> : <Menu size={20} aria-hidden="true" />}
</button>
</div>
<aside
id="admin-sidebar"
className={cn('admin-sidebar', mobileOpen && 'is-open')}
aria-label="Admin navigation"
>
<div className="admin-sidebar__brand">
<ShieldCheck size={18} aria-hidden="true" />
newzy <span>admin</span>
</div>
<nav className="admin-sidebar__nav">
<NavLink to="/admin" end className={sidebarLinkClasses}>
<LayoutDashboard size={16} aria-hidden="true" />
<span>Items</span>
</NavLink>
<NavLink to="/admin/items/new" className={sidebarLinkClasses}>
<Plus size={16} aria-hidden="true" />
<span>New item</span>
</NavLink>
<Link to="/" className="admin-sidebar__link">
<ArrowLeft size={16} aria-hidden="true" />
<span>Back to newzy</span>
</Link>
</nav>
<div className="admin-sidebar__footer">
<div className="admin-sidebar__user">
<span aria-hidden="true" style={{ opacity: 0.7 }}>
⚙
</span>
<span>
Signed in as <strong>{username}</strong>
</span>
</div>
<Link to="/sign-out" className="admin-sidebar__link">
<LogOut size={16} aria-hidden="true" />
<span>Sign out</span>
</Link>
</div>
</aside>
<main className="admin-main" id="admin-main">
<div className="admin-main__inner">
<Outlet />
</div>
</main>
</div>
);
}
export default AdminLayout;
@@ -0,0 +1,109 @@
/**
* Delete confirmation dialog (M6).
*
* A custom modal (no extra dependencies): centered overlay, warning
* icon, explicit "Yes, delete" action and a Cancel fallback. Closes on
* Escape and on overlay click, and ignores dismissal while the delete
* request is in flight.
*/
import { AlertTriangle } from 'lucide-react';
import { useEffect, useRef } from 'react';
import type { AdminItem } from '../types/admin';
export interface DeleteConfirmationProps {
/** The item about to be deleted. */
item: AdminItem;
/** `true` while the delete request is in flight. */
busy?: boolean;
/** Error from a failed delete attempt (rendered above the actions). */
error?: string | null;
/** Trigger the (async) delete. */
onConfirm: () => void;
/** Dismiss the dialog without deleting. */
onCancel: () => void;
}
export function DeleteConfirmation({
item,
busy = false,
error = null,
onConfirm,
onCancel,
}: DeleteConfirmationProps) {
const cancelRef = useRef<HTMLButtonElement>(null);
// Move focus into the dialog when it opens (accessibility).
useEffect(() => {
cancelRef.current?.focus();
}, []);
// Close on Escape (unless a request is in flight).
useEffect(() => {
if (busy) return;
const onKey = (event: KeyboardEvent) => {
if (event.key === 'Escape') onCancel();
};
document.addEventListener('keydown', onKey);
return () => document.removeEventListener('keydown', onKey);
}, [busy, onCancel]);
return (
<div
className="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/60 p-4"
role="presentation"
onClick={busy ? undefined : onCancel}
>
<div
role="dialog"
aria-modal="true"
aria-labelledby="delete-confirm-title"
className="w-full max-w-md rounded-xl border border-slate-200 bg-white p-6 shadow-xl"
onClick={(event) => event.stopPropagation()}
>
<div className="mb-4 flex items-start gap-3">
<span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-amber-100 text-amber-600">
<AlertTriangle size={20} aria-hidden="true" />
</span>
<div>
<h2 id="delete-confirm-title" className="text-base font-semibold text-slate-900">
Are you sure you want to delete this item?
</h2>
<p className="mt-1 text-sm text-slate-600">
“<span className="font-medium text-slate-800">{item.title}</span>” will be
permanently removed. This action cannot be undone.
</p>
</div>
</div>
{error && (
<p className="mb-4 rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700" role="alert">
{error}
</p>
)}
<div className="flex justify-end gap-2">
<button
type="button"
ref={cancelRef}
className="btn-secondary"
disabled={busy}
onClick={onCancel}
>
Cancel
</button>
<button
type="button"
data-testid="confirm-delete"
className="inline-flex items-center justify-center gap-2 rounded-md bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700 focus:outline-none focus-visible:ring-2 focus-visible:ring-red-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
disabled={busy}
onClick={onConfirm}
>
{busy ? 'Deleting…' : 'Yes, delete'}
</button>
</div>
</div>
</div>
);
}
export default DeleteConfirmation;
+391
View File
@@ -0,0 +1,391 @@
/**
* Rich-text editor built on Lexical (M6).
*
* Features: bold / italic / underline, H1–H6 headings, ordered &
* unordered lists, links and code blocks. Content is exchanged with the
* parent as an HTML string (`initialHtml` in, `onChange` out) so it can
* be stored verbatim in the backend `items.content` column.
*
* Lexical 0.25.x API (classic): `RichTextPlugin` + `ContentEditable`,
* `FORMAT_TEXT_COMMAND` for inline marks, `$setBlocksType` for block
* conversion, `$generateHtmlFromNodes` / `$generateNodesFromDOM` for
* HTML serialization.
*/
import {
FORMAT_TEXT_COMMAND,
REDO_COMMAND,
UNDO_COMMAND,
$createParagraphNode,
$getSelection,
$getRoot,
$isRangeSelection,
type ElementNode,
type LexicalEditor as LexicalEditorType,
} from 'lexical';
import { CodeNode, $createCodeNode, $isCodeNode } from '@lexical/code';
import { $generateHtmlFromNodes, $generateNodesFromDOM } from '@lexical/html';
import { LinkNode, TOGGLE_LINK_COMMAND } from '@lexical/link';
import {
ListNode,
$insertList,
$isListNode,
$removeList,
type ListType,
} from '@lexical/list';
import { HeadingNode, $createHeadingNode, $isHeadingNode } from '@lexical/rich-text';
import { $setBlocksType } from '@lexical/selection';
import { LexicalComposer } from '@lexical/react/LexicalComposer';
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
import { RichTextPlugin } from '@lexical/react/LexicalRichTextPlugin';
import { ContentEditable } from '@lexical/react/LexicalContentEditable';
import { HistoryPlugin } from '@lexical/react/LexicalHistoryPlugin';
import { LinkPlugin } from '@lexical/react/LexicalLinkPlugin';
import { OnChangePlugin } from '@lexical/react/LexicalOnChangePlugin';
import { LexicalErrorBoundary } from '@lexical/react/LexicalErrorBoundary';
import {
Bold,
Code,
Italic,
Link as LinkIcon,
List,
ListOrdered,
Redo2,
Underline,
Undo2,
} from 'lucide-react';
import { useCallback, useEffect, useRef, useState } from 'react';
import { cn } from '../lib/utils';
type HeadingTag = 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6';
/** History state helpers (exposed by the history plugin at runtime). */
function historyCanUndo(editor: LexicalEditorType): boolean {
return (editor as unknown as { canUndo?: () => boolean }).canUndo?.() ?? false;
}
function historyCanRedo(editor: LexicalEditorType): boolean {
return (editor as unknown as { canRedo?: () => boolean }).canRedo?.() ?? false;
}
interface ToolbarState {
bold: boolean;
italic: boolean;
underline: boolean;
heading: '' | HeadingTag;
/** 'bullet' (UL) or 'number' (OL) when the block is a list. */
list: '' | Extract<ListType, 'bullet' | 'number'>;
code: boolean;
canUndo: boolean;
canRedo: boolean;
}
const DEFAULT_TOOLBAR: ToolbarState = {
bold: false,
italic: false,
underline: false,
heading: '',
list: '',
code: false,
canUndo: false,
canRedo: false,
};
/** Registered node types (beyond the core Text/Paragraph nodes). */
const EDITOR_NODES = [HeadingNode, ListNode, LinkNode, CodeNode];
/** Lexical theme: maps node types to the CSS classes in admin.css. */
const EDITOR_THEME = {
heading: {
h1: 'lex-h1',
h2: 'lex-h2',
h3: 'lex-h3',
h4: 'lex-h4',
h5: 'lex-h5',
h6: 'lex-h6',
},
link: 'lex-link',
list: { listitem: 'lex-listitem' },
code: 'lex-code',
quote: 'lex-quote',
paragraph: 'lex-paragraph',
};
interface LexicalEditorProps {
/** HTML content to load when the editor mounts. */
initialHtml: string;
/** Called with the editor's HTML content after every change. */
onChange: (html: string) => void;
placeholder?: string;
}
export function LexicalEditor({ initialHtml, onChange, placeholder }: LexicalEditorProps) {
// Keep the latest callback without re-mounting the composer.
const onChangeRef = useRef(onChange);
onChangeRef.current = onChange;
return (
<LexicalComposer
initialConfig={{
namespace: 'newzy-admin-editor',
nodes: EDITOR_NODES,
theme: EDITOR_THEME,
onError: (error: unknown) => {
console.error('Lexical editor error:', error);
},
}}
>
<EditorShell initialHtml={initialHtml} onChange={onChangeRef} placeholder={placeholder} />
</LexicalComposer>
);
}
interface EditorShellProps {
initialHtml: string;
onChange: React.MutableRefObject<(html: string) => void>;
placeholder?: string;
}
function EditorShell({ initialHtml, onChange, placeholder }: EditorShellProps) {
const [editor] = useLexicalComposerContext();
// Load the initial HTML once (empty string -> the default empty paragraph).
useEffect(() => {
if (!initialHtml) return;
const doc = document.implementation.createHTMLDocument('');
doc.body.innerHTML = initialHtml;
editor.update(
() => {
$generateNodesFromDOM(editor, doc);
},
{ discrete: true },
);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [editor]);
return (
<div className="lex-editor" data-testid="lexical-editor">
<Toolbar />
<RichTextPlugin
contentEditable={
<ContentEditable
className="lex-editor__content"
aria-label="Item content"
spellCheck
/>
}
ErrorBoundary={LexicalErrorBoundary}
/>
{placeholder && <Placeholder text={placeholder} />}
<HistoryPlugin />
<LinkPlugin />
<OnChangePlugin
onChange={(editorState) => {
editorState.read(() => {
onChange.current($generateHtmlFromNodes(editor));
});
}}
/>
</div>
);
}
function Placeholder({ text }: { text: string }) {
const [editor] = useLexicalComposerContext();
const [isEmpty, setIsEmpty] = useState(true);
useEffect(
() =>
editor.registerUpdateListener(({ editorState }) => {
editorState.read(() => {
setIsEmpty($getRoot().getTextContent().trim().length === 0);
});
}),
[editor],
);
if (!isEmpty) return null;
return (
<span className="lex-editor__placeholder" data-testid="editor-placeholder">
{text}
</span>
);
}
/* --- Toolbar ---------------------------------------------------------------- */
function Toolbar() {
const [editor] = useLexicalComposerContext();
const [state, setState] = useState<ToolbarState>(DEFAULT_TOOLBAR);
const [linkInputOpen, setLinkInputOpen] = useState(false);
const [linkUrl, setLinkUrl] = useState('');
const linkInputRef = useRef<HTMLInputElement>(null);
const updateToolbar = useCallback(() => {
editor.getEditorState().read(() => {
const selection = $getSelection();
if (!$isRangeSelection(selection)) {
return;
}
const block = selection.anchor.getNode().getTopLevelElement();
const listType = $isListNode(block) ? block.getListType() : '';
const next: ToolbarState = {
bold: selection.hasFormat('bold'),
italic: selection.hasFormat('italic'),
underline: selection.hasFormat('underline'),
heading: $isHeadingNode(block) ? block.getTag() : '',
list: listType === 'check' ? '' : listType,
code: $isCodeNode(block),
canUndo: historyCanUndo(editor),
canRedo: historyCanRedo(editor),
};
setState((prev) => (JSON.stringify(prev) === JSON.stringify(next) ? prev : next));
});
}, [editor]);
// Keep the toolbar in sync with selection changes inside the editor.
useEffect(() => {
const handleSelectionChange = () => updateToolbar();
document.addEventListener('selectionchange', handleSelectionChange);
const updateListener = editor.registerUpdateListener(() => updateToolbar());
return () => {
document.removeEventListener('selectionchange', handleSelectionChange);
updateListener();
};
}, [editor, updateToolbar]);
const dispatchFormat = (format: 'bold' | 'italic' | 'underline') =>
editor.dispatchCommand(FORMAT_TEXT_COMMAND, format);
const setHeading = (tag: '' | HeadingTag) =>
editor.update(() => {
const selection = $getSelection();
if (!$isRangeSelection(selection)) return;
$setBlocksType(
selection,
(tag === ''
? () => $createParagraphNode()
: () => $createHeadingNode(tag)) as () => ElementNode,
);
});
const toggleList = (type: Extract<ListType, 'bullet' | 'number'>) =>
editor.update(() => {
const selection = $getSelection();
if (!$isRangeSelection(selection)) return;
const block = selection.anchor.getNode().getTopLevelElement();
if ($isListNode(block) && block.getListType() === type) {
$removeList();
} else {
$insertList(type);
}
});
const toggleCode = () =>
editor.update(() => {
const selection = $getSelection();
if (!$isRangeSelection(selection)) return;
const block = selection.anchor.getNode().getTopLevelElement();
$setBlocksType(
selection,
($isCodeNode(block)
? () => $createParagraphNode()
: () => $createCodeNode()) as () => ElementNode,
);
});
const openLinkInput = () => {
setLinkInputOpen(true);
// Focus the input once it has rendered.
requestAnimationFrame(() => linkInputRef.current?.focus());
};
const applyLink = () => {
const url = linkUrl.trim();
if (url) {
editor.dispatchCommand(TOGGLE_LINK_COMMAND, { url, rel: 'noopener noreferrer' });
}
setLinkInputOpen(false);
setLinkUrl('');
};
const button = (
label: string,
isActive: boolean,
onClick: () => void,
icon: React.ReactNode,
disabled = false,
) => (
<button
type="button"
className={cn('lex-toolbar-btn', isActive && 'is-active')}
aria-label={label}
title={label}
aria-pressed={isActive}
disabled={disabled}
onClick={onClick}
>
{icon}
</button>
);
return (
<div className="lex-editor__toolbar" role="toolbar" aria-label="Text formatting">
{button('Undo', false, () => editor.dispatchCommand(UNDO_COMMAND, undefined), <Undo2 size={15} />, !state.canUndo)}
{button('Redo', false, () => editor.dispatchCommand(REDO_COMMAND, undefined), <Redo2 size={15} />, !state.canRedo)}
<span className="lex-toolbar-sep" aria-hidden="true" />
{button('Bold', state.bold, () => dispatchFormat('bold'), <Bold size={15} />)}
{button('Italic', state.italic, () => dispatchFormat('italic'), <Italic size={15} />)}
{button('Underline', state.underline, () => dispatchFormat('underline'), <Underline size={15} />)}
<span className="lex-toolbar-sep" aria-hidden="true" />
<label className="sr-only" htmlFor="lex-heading-select">
Heading level
</label>
<select
id="lex-heading-select"
className="lex-toolbar-select"
value={state.heading || ''}
onChange={(event) => setHeading(event.target.value as '' | HeadingTag)}
>
<option value="">Paragraph</option>
<option value="h1">Heading 1</option>
<option value="h2">Heading 2</option>
<option value="h3">Heading 3</option>
<option value="h4">Heading 4</option>
<option value="h5">Heading 5</option>
<option value="h6">Heading 6</option>
</select>
<span className="lex-toolbar-sep" aria-hidden="true" />
{button('Bulleted list', state.list === 'bullet', () => toggleList('bullet'), <List size={15} />)}
{button('Numbered list', state.list === 'number', () => toggleList('number'), <ListOrdered size={15} />)}
{button('Code block', state.code, toggleCode, <Code size={15} />)}
<span className="lex-toolbar-sep" aria-hidden="true" />
<span className="lex-toolbar-link">
{button('Insert link', false, openLinkInput, <LinkIcon size={15} />)}
{linkInputOpen && (
<input
ref={linkInputRef}
type="url"
value={linkUrl}
placeholder="https://example.com"
aria-label="Link URL"
onChange={(event) => setLinkUrl(event.target.value)}
onKeyDown={(event) => {
if (event.key === 'Enter') {
event.preventDefault();
applyLink();
}
if (event.key === 'Escape') {
setLinkInputOpen(false);
setLinkUrl('');
}
}}
onBlur={() => {
setLinkInputOpen(false);
setLinkUrl('');
}}
/>
)}
</span>
</div>
);
}
+13 -2
View File
@@ -1,4 +1,4 @@
import { FileText, Home, LogOut, Menu, Settings, User, X, type LucideIcon } from 'lucide-react';
import { FileText, Home, LogOut, Menu, Settings, ShieldCheck, User, X, type LucideIcon } from 'lucide-react';
import { useState } from 'react';
import { Link, NavLink } from 'react-router-dom';
import { useAuth } from '../../auth';
@@ -32,7 +32,7 @@ const NAV_ITEMS: NavItem[] = [
*/
export function Header({ className }: HeaderProps) {
const [menuOpen, setMenuOpen] = useState(false);
const { username, ready } = useAuth();
const { username, isAdmin, ready } = useAuth();
const closeMenu = () => setMenuOpen(false);
@@ -86,6 +86,17 @@ export function Header({ className }: HeaderProps) {
<span>{label}</span>
</NavLink>
))}
{/* Admin link (M6): only visible to admin accounts. */}
{ready && isAdmin && (
<NavLink
to="/admin"
className={({ isActive }) => linkClasses({ isActive })}
onClick={closeMenu}
>
<ShieldCheck className="h-5 w-5" aria-hidden="true" />
<span>Admin</span>
</NavLink>
)}
</nav>
);
+1
View File
@@ -2,6 +2,7 @@ import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './assets/styles/globals.css';
import './assets/styles/admin.css';
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
<React.StrictMode>
+480
View File
@@ -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;
+441
View File
@@ -0,0 +1,441 @@
/**
* Create/edit item page (M6).
*
* Full form for an item: title, optional external URL, points, author
* (username, pre-filled from the session on create) and a Lexical
* WYSIWYG editor for the HTML body. Validates required fields, shows a
* loading state while saving and surfaces success/error notifications.
* An optional debounced auto-save can be enabled.
*
* Routes:
* - `/admin/items/new` -> create mode (no `:id` param)
* - `/admin/items/:id/edit` -> edit mode (loads the item on mount)
*/
import { ArrowLeft, Loader2, Save } from 'lucide-react';
import {
FormEvent,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { Link, useNavigate, useParams } from 'react-router-dom';
import {
adminCreateItem,
adminGetItem,
adminUpdateItem,
} from '../api/admin';
import { ApiError } from '../api/client';
import { LexicalEditor } from '../components/LexicalEditor';
import { useAuth } from '../auth';
import type { AdminItemInput } from '../types/admin';
const AUTO_SAVE_DELAY_MS = 2000;
interface FieldErrors {
title?: string;
url?: string;
points?: string;
username?: string;
}
/** Client-side validation mirroring the backend rules (422 on the server). */
function validate(values: AdminItemInput): FieldErrors {
const errors: FieldErrors = {};
if (!values.title.trim()) {
errors.title = 'Title is required.';
} else if (values.title.length > 300) {
errors.title = 'Title must be at most 300 characters.';
}
const url = values.url.trim();
if (url) {
let parsed: URL | null = null;
try {
parsed = new URL(url);
} catch {
parsed = null;
}
if (!parsed || (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')) {
errors.url = 'URL must start with http:// or https://.';
}
}
if (!Number.isInteger(values.points) || values.points < 0) {
errors.points = 'Points must be a whole number of 0 or more.';
}
if (!values.username.trim()) {
errors.username = 'Author is required.';
} else if (values.username.trim().length > 60) {
errors.username = 'Author must be at most 60 characters.';
}
return errors;
}
export function EditItemPage() {
const { id } = useParams<{ id: string }>();
const editingId = id ? Number(id) : null;
const isCreate = editingId === null;
const navigate = useNavigate();
const { username: adminUsername } = useAuth();
const [values, setValues] = useState<AdminItemInput>({
title: '',
url: '',
points: 0,
username: adminUsername ?? '',
content: '',
});
const [contentHtml, setContentHtml] = useState('');
const [loadError, setLoadError] = useState<string | null>(null);
const [loading, setLoading] = useState(isCreate ? false : true);
const [saving, setSaving] = useState(false);
const [fieldErrors, setFieldErrors] = useState<FieldErrors>({});
const [formError, setFormError] = useState<string | null>(null);
const [autoSave, setAutoSave] = useState(false);
const [autoSaveStatus, setAutoSaveStatus] = useState<'idle' | 'saving' | 'saved' | 'paused'>(
'idle',
);
const usernameTouched = useRef(false);
// After an auto-save in create mode, switch to updating the new item.
const [createdId, setCreatedId] = useState<number | null>(null);
const targetId = editingId ?? createdId;
const [initialValues, setInitialValues] = useState<AdminItemInput | null>(null);
const lastSavedSignature = useRef<string | null>(null);
// Pre-fill the author once the session restore has finished (the
// username is only known asynchronously) — unless the admin already
// typed into the field.
useEffect(() => {
if (adminUsername && !usernameTouched.current) {
setValues((current) =>
current.username === '' ? { ...current, username: adminUsername } : current,
);
}
}, [adminUsername]);
// Load the item in edit mode.
useEffect(() => {
if (editingId === null) {
setInitialValues({ title: '', url: '', points: 0, username: adminUsername ?? '', content: '' });
return;
}
let active = true;
adminGetItem(editingId)
.then((item) => {
if (!active) return;
const loaded: AdminItemInput = {
title: item.title,
url: item.url,
points: item.points,
username: item.username,
content: item.content,
};
setValues(loaded);
setContentHtml(item.content);
setInitialValues(loaded);
lastSavedSignature.current = signature(loaded, item.content);
setLoadError(null);
})
.catch((err) => {
if (!active) return;
setLoadError(err instanceof ApiError ? err.message : 'Could not load the item.');
})
.finally(() => {
if (active) setLoading(false);
});
return () => {
active = false;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [editingId]);
const form = useMemo(
() => ({ ...values, content: contentHtml }),
[values, contentHtml],
);
const dirty = useMemo(
() =>
initialValues !== null &&
signature(form, contentHtml) !== lastSavedSignature.current,
[form, contentHtml, initialValues],
);
const save = useCallback(
async (mode: 'manual' | 'auto' = 'manual') => {
const errors = validate(form);
setFieldErrors(errors);
if (Object.keys(errors).length > 0) {
if (mode === 'auto') {
setAutoSaveStatus('paused');
return false;
}
setFormError('Please fix the highlighted fields and try again.');
return false;
}
setFormError(null);
setSaving(true);
if (mode === 'auto') setAutoSaveStatus('saving');
try {
const payload: AdminItemInput = {
title: form.title.trim(),
url: form.url.trim(),
points: form.points,
username: form.username.trim(),
content: contentHtml,
};
const saved =
targetId !== null
? await adminUpdateItem(targetId, payload)
: await adminCreateItem(payload);
lastSavedSignature.current = signature(payload, contentHtml);
if (createdId === null && editingId === null) {
setCreatedId(saved.id);
}
setAutoSaveStatus('saved');
return true;
} catch (err) {
const message =
err instanceof ApiError ? err.message : 'Saving the item failed.';
if (mode === 'auto') {
setAutoSaveStatus('paused');
} else {
setFormError(message);
}
return false;
} finally {
setSaving(false);
}
},
[form, contentHtml, targetId, createdId, editingId],
);
// Debounced auto-save: fire 2s after the last change when enabled.
useEffect(() => {
if (!autoSave || loading || saving || !dirty) return;
const timer = setTimeout(() => {
void save('auto');
}, AUTO_SAVE_DELAY_MS);
return () => clearTimeout(timer);
}, [autoSave, loading, saving, dirty, form, save]);
const onSubmit = async (event: FormEvent) => {
event.preventDefault();
const ok = await save('manual');
if (ok) {
navigate('/admin', { state: { notice: `“${values.title.trim()}” was saved.` } });
}
};
const onField = (field: keyof AdminItemInput) => (value: string | number) => {
if (field === 'username') usernameTouched.current = true;
setValues((current) => ({ ...current, [field]: value }));
};
if (loading) {
return (
<div className="flex justify-center py-16" role="status">
<span className="animate-pulse text-sm text-slate-500">Loading item…</span>
</div>
);
}
if (loadError) {
return (
<div className="text-center">
<h1 className="mb-2 text-2xl font-bold text-slate-900">Item not found</h1>
<p className="mb-6 text-sm text-slate-600">{loadError}</p>
<Link to="/admin" className="btn">
<ArrowLeft size={15} aria-hidden="true" />
Back to items
</Link>
</div>
);
}
const autoSaveHint =
autoSaveStatus === 'saving'
? 'Saving…'
: autoSaveStatus === 'saved'
? 'All changes saved'
: autoSaveStatus === 'paused'
? 'Auto-save paused (fix validation errors)'
: 'Off';
return (
<div>
<div className="mb-6 flex flex-wrap items-center justify-between gap-3">
<div>
<Link
to="/admin"
className="mb-2 inline-flex items-center gap-1.5 text-sm text-slate-500 hover:text-slate-800"
>
<ArrowLeft size={14} aria-hidden="true" />
Back to items
</Link>
<h1 className="text-2xl font-bold text-slate-900">
{isCreate && createdId === null ? 'New item' : `Edit item #${targetId}`}
</h1>
</div>
<label className="flex items-center gap-2 text-sm text-slate-600">
<input
type="checkbox"
className="h-4 w-4 rounded border-slate-300 text-blue-600 focus:ring-blue-500"
checked={autoSave}
disabled={saving}
onChange={(event) => {
setAutoSave(event.target.checked);
if (!event.target.checked) setAutoSaveStatus('idle');
}}
/>
Auto-save <span className="text-xs text-slate-400">({autoSaveHint})</span>
</label>
</div>
{formError && (
<div
className="mb-4 rounded-md border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700"
role="alert"
>
{formError}
</div>
)}
<form
onSubmit={(event) => void onSubmit(event)}
className="space-y-5 rounded-xl border border-slate-200 bg-white p-6 shadow-sm"
noValidate
>
<div>
<label htmlFor="item-title" className="mb-1 block text-sm font-medium text-slate-700">
Title <span className="text-red-600" aria-hidden="true">*</span>
</label>
<input
id="item-title"
className="input"
value={values.title}
maxLength={300}
placeholder="Headline of the story"
onChange={(event) => onField('title')(event.target.value)}
/>
{fieldErrors.title && (
<p className="mt-1 text-sm text-red-600" role="alert">
{fieldErrors.title}
</p>
)}
</div>
<div className="grid gap-5 sm:grid-cols-2">
<div>
<label htmlFor="item-url" className="mb-1 block text-sm font-medium text-slate-700">
URL <span className="text-xs font-normal text-slate-400">(optional)</span>
</label>
<input
id="item-url"
className="input"
type="url"
value={values.url}
maxLength={500}
placeholder="https://example.com/story"
onChange={(event) => onField('url')(event.target.value)}
/>
{fieldErrors.url && (
<p className="mt-1 text-sm text-red-600" role="alert">
{fieldErrors.url}
</p>
)}
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label
htmlFor="item-points"
className="mb-1 block text-sm font-medium text-slate-700"
>
Points
</label>
<input
id="item-points"
className="input"
type="number"
min={0}
step={1}
value={Number.isFinite(values.points) ? values.points : 0}
onChange={(event) =>
onField('points')(event.target.value === '' ? 0 : Number(event.target.value))
}
/>
{fieldErrors.points && (
<p className="mt-1 text-sm text-red-600" role="alert">
{fieldErrors.points}
</p>
)}
</div>
<div>
<label
htmlFor="item-username"
className="mb-1 block text-sm font-medium text-slate-700"
>
Author
</label>
<input
id="item-username"
className="input"
value={values.username}
maxLength={60}
placeholder="username"
onChange={(event) => onField('username')(event.target.value)}
/>
{fieldErrors.username && (
<p className="mt-1 text-sm text-red-600" role="alert">
{fieldErrors.username}
</p>
)}
</div>
</div>
</div>
<div>
<span className="mb-1 block text-sm font-medium text-slate-700">Content</span>
<LexicalEditor
initialHtml={contentHtml}
onChange={(html) => setContentHtml(html)}
placeholder="Write the story body…"
/>
<p className="mt-1 text-xs text-slate-400">
Rich text: bold, italic, underline, headings, lists, links and code blocks.
</p>
</div>
<div className="flex items-center gap-3 border-t border-slate-100 pt-5">
<button type="submit" className="btn" disabled={saving}>
{saving ? (
<Loader2 size={15} className="animate-spin" aria-hidden="true" />
) : (
<Save size={15} aria-hidden="true" />
)}
{saving ? 'Saving…' : isCreate && createdId === null ? 'Create item' : 'Save changes'}
</button>
<Link to="/admin" className="btn-secondary">
Cancel
</Link>
</div>
</form>
</div>
);
}
function signature(values: AdminItemInput, content: string): string {
return JSON.stringify({
title: values.title,
url: values.url,
points: values.points,
username: values.username,
content,
});
}
export default EditItemPage;
+176
View File
@@ -0,0 +1,176 @@
/**
* Unit tests for the admin API client (URL/parameter building, methods,
* response parsing, error propagation).
*/
import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
adminCreateItem,
adminDeleteItem,
adminGetItem,
adminListItems,
adminUpdateItem,
} from '../../api/admin';
import { ApiError, TOKEN_KEY } from '../../api/client';
import type { AdminItemsPage } from '../../types/admin';
const SAMPLE_PAGE: AdminItemsPage = {
items: [
{
id: 1,
title: 'First story',
url: 'https://example.com/first',
points: 3,
username: 'alice',
content: '<p>Hello</p>',
created_at: '2024-05-01T12:00:00Z',
},
],
total: 1,
page: 1,
page_size: 20,
total_pages: 1,
};
function jsonResponse(status: number, body: unknown) {
return {
ok: status >= 200 && status < 300,
status,
statusText: 'OK',
json: async () => body,
text: async () => JSON.stringify(body),
} as Response;
}
describe('admin API client', () => {
let fetchMock: ReturnType<typeof vi.fn>;
beforeEach(() => {
localStorage.clear();
fetchMock = vi.fn();
vi.stubGlobal('fetch', fetchMock);
});
it('listItems builds the query string from all parameters', async () => {
localStorage.setItem(TOKEN_KEY, 'admin-token');
fetchMock.mockResolvedValue(jsonResponse(200, SAMPLE_PAGE));
const res = await adminListItems({
page: 2,
pageSize: 50,
search: ' breaking news ',
sortBy: 'title',
sortOrder: 'asc',
});
expect(res).toEqual(SAMPLE_PAGE);
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
// URLSearchParams encodes spaces as `+`.
expect(url).toBe(
'/api/v1/admin/items?page=2&page_size=50&search=breaking+news&sort_by=title&sort_order=asc',
);
expect(init.method).toBeUndefined();
// The JWT is attached as a Bearer token.
expect((init.headers as Record<string, string>).Authorization).toBe(
'Bearer admin-token',
);
});
it('listItems omits the search parameter when empty', async () => {
fetchMock.mockResolvedValue(jsonResponse(200, SAMPLE_PAGE));
await adminListItems({
page: 1,
pageSize: 20,
search: ' ',
sortBy: 'created_at',
sortOrder: 'desc',
});
const [url] = fetchMock.mock.calls[0] as [string, RequestInit];
expect(url).toBe(
'/api/v1/admin/items?page=1&page_size=20&sort_by=created_at&sort_order=desc',
);
});
it('getItem requests the item by id', async () => {
fetchMock.mockResolvedValue(jsonResponse(200, SAMPLE_PAGE.items[0]));
await adminGetItem(7);
const [url] = fetchMock.mock.calls[0] as [string, RequestInit];
expect(url).toBe('/api/v1/admin/items/7');
});
it('createItem POSTs the payload', async () => {
fetchMock.mockResolvedValue(jsonResponse(201, SAMPLE_PAGE.items[0]));
await adminCreateItem({
title: 'New story',
url: '',
points: 0,
username: 'root',
content: '<p>Body</p>',
});
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
expect(url).toBe('/api/v1/admin/items');
expect(init.method).toBe('POST');
expect(JSON.parse(init.body as string)).toEqual({
title: 'New story',
url: '',
points: 0,
username: 'root',
content: '<p>Body</p>',
});
});
it('updateItem PUTs the payload to the item route', async () => {
fetchMock.mockResolvedValue(jsonResponse(200, SAMPLE_PAGE.items[0]));
await adminUpdateItem(7, {
title: 'Updated',
url: 'https://example.com/new',
points: 9,
username: 'root',
content: '',
});
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
expect(url).toBe('/api/v1/admin/items/7');
expect(init.method).toBe('PUT');
});
it('deleteItem sends DELETE and resolves to undefined on 204', async () => {
fetchMock.mockResolvedValue({
ok: true,
status: 204,
statusText: 'No Content',
} as Response);
await expect(adminDeleteItem(7)).resolves.toBeUndefined();
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
expect(url).toBe('/api/v1/admin/items/7');
expect(init.method).toBe('DELETE');
});
it('surfaces the backend error for non-admin access (403)', async () => {
localStorage.setItem(TOKEN_KEY, 'non-admin-token');
fetchMock.mockResolvedValue(
jsonResponse(403, { detail: 'Admin access required', code: 'forbidden' }),
);
const err = await adminListItems({
page: 1,
pageSize: 20,
search: '',
sortBy: 'created_at',
sortOrder: 'desc',
}).catch((e: unknown) => e);
expect(err).toBeInstanceOf(ApiError);
expect((err as ApiError).status).toBe(403);
expect((err as ApiError).code).toBe('forbidden');
expect((err as ApiError).message).toBe('Admin access required');
});
});
@@ -0,0 +1,224 @@
/**
* Tests for the AdminDashboard list view (M6): rendering, debounced
* search, sorting, pagination and the delete confirmation flow.
*/
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
adminDeleteItem,
adminListItems,
} from '../../api/admin';
import { AdminDashboard } from '../../pages/AdminDashboard';
import type { AdminItemsPage } from '../../types/admin';
vi.mock('../../api/admin', () => ({
adminListItems: vi.fn(),
adminGetItem: vi.fn(),
adminCreateItem: vi.fn(),
adminUpdateItem: vi.fn(),
adminDeleteItem: vi.fn(),
}));
const items = (count: number, offset = 0) =>
Array.from({ length: count }, (_, i) => ({
id: i + 1 + offset,
title: `Story ${i + 1 + offset}`,
url: `https://example.com/story-${i + 1 + offset}`,
points: i + offset,
username: 'alice',
content: `<p>Body ${i + 1 + offset}</p>`,
created_at: `2024-05-0${(i % 9) + 1}T12:00:00Z`,
}));
const page = (overrides: Partial<AdminItemsPage> = {}): AdminItemsPage => ({
items: items(3),
total: 3,
page: 1,
page_size: 20,
total_pages: 1,
...overrides,
});
function lastCallParams(): {
page: number;
pageSize: number;
search: string;
sortBy: string;
sortOrder: string;
} {
const calls = vi.mocked(adminListItems).mock.calls;
const last = calls[calls.length - 1][0];
return {
page: last.page,
pageSize: last.pageSize,
search: last.search,
sortBy: last.sortBy,
sortOrder: last.sortOrder,
};
}
function renderDashboard() {
return render(
<MemoryRouter
future={{ v7_startTransition: true, v7_relativeSplatPath: true }}
>
<AdminDashboard />
</MemoryRouter>,
);
}
describe('AdminDashboard', () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(adminListItems).mockResolvedValue(page());
vi.mocked(adminDeleteItem).mockResolvedValue(undefined);
});
it('renders the fetched items with their details', async () => {
renderDashboard();
expect(await screen.findByText('Story 1')).toBeInTheDocument();
expect(screen.getByText('Story 2')).toBeInTheDocument();
expect(screen.getByText('Story 3')).toBeInTheDocument();
// All three seed items belong to "alice".
expect(screen.getAllByText('alice').length).toBe(3);
expect(screen.getByText('https://example.com/story-1')).toBeInTheDocument();
expect(screen.getByText('Showing 1–3 of 3')).toBeInTheDocument();
// Edit links point at the edit route.
const editLinks = screen.getAllByRole('link', { name: /edit/i });
expect(editLinks[0].getAttribute('href')).toBe('/admin/items/1/edit');
});
it('requests the initial page with the default parameters', async () => {
renderDashboard();
await screen.findByText('Story 1');
expect(lastCallParams()).toEqual({
page: 1,
pageSize: 20,
search: '',
sortBy: 'created_at',
sortOrder: 'desc',
});
});
it('debounces the search and filters by it', async () => {
renderDashboard();
await screen.findByText('Story 1');
fireEvent.change(screen.getByLabelText('Search items'), {
target: { value: 'breaking' },
});
// Immediately after typing: still the original request (debounce).
expect(lastCallParams().search).toBe('');
// After the 300ms debounce the API is called with the search term.
await waitFor(() => expect(lastCallParams().search).toBe('breaking'), {
timeout: 1500,
});
// Searching resets to page 1.
expect(lastCallParams().page).toBe(1);
});
it('toggles sort direction when clicking the same column twice', async () => {
renderDashboard();
await screen.findByText('Story 1');
fireEvent.click(screen.getByRole('button', { name: /sort by title/i }));
expect(lastCallParams().sortBy).toBe('title');
expect(lastCallParams().sortOrder).toBe('asc');
fireEvent.click(screen.getByRole('button', { name: /sort by title/i }));
expect(lastCallParams().sortBy).toBe('title');
expect(lastCallParams().sortOrder).toBe('desc');
// Switching columns starts on ascending again.
fireEvent.click(screen.getByRole('button', { name: /sort by points/i }));
expect(lastCallParams().sortBy).toBe('points');
expect(lastCallParams().sortOrder).toBe('asc');
});
it('navigates pages and changes the page size', async () => {
vi.mocked(adminListItems).mockResolvedValue(
page({ total: 45, page: 2, total_pages: 3 }),
);
renderDashboard();
await screen.findByText('Story 1');
fireEvent.click(screen.getByRole('button', { name: /next/i }));
await waitFor(() => expect(lastCallParams().page).toBe(2));
fireEvent.click(screen.getByRole('button', { name: /previous/i }));
await waitFor(() => expect(lastCallParams().page).toBe(1));
fireEvent.change(screen.getByLabelText('Rows per page'), {
target: { value: '50' },
});
await waitFor(() => expect(lastCallParams().pageSize).toBe(50));
expect(lastCallParams().page).toBe(1);
});
it('shows an empty state when nothing matches the search', async () => {
vi.mocked(adminListItems).mockResolvedValue(page({ items: [], total: 0 }));
renderDashboard();
await screen.findByText(/no items yet/i);
});
it('shows the error state with a retry action', async () => {
vi.mocked(adminListItems).mockRejectedValue(new Error('boom'));
renderDashboard();
expect(await screen.findByRole('alert')).toHaveTextContent(/boom|went wrong/i);
screen.getByRole('button', { name: /retry/i }).click();
await waitFor(() =>
expect(vi.mocked(adminListItems).mock.calls.length).toBeGreaterThanOrEqual(2),
);
});
it('deletes an item only after explicit confirmation', async () => {
renderDashboard();
await screen.findByText('Story 1');
// Open the dialog.
fireEvent.click(screen.getAllByRole('button', { name: /delete/i })[0]);
const dialog = await screen.findByRole('dialog');
expect(dialog).toHaveTextContent('Story 1');
expect(vi.mocked(adminDeleteItem)).not.toHaveBeenCalled();
// Cancel: no API call.
fireEvent.click(screen.getByRole('button', { name: /cancel/i }));
expect(await screen.findByText('Story 1')).toBeInTheDocument();
expect(vi.mocked(adminDeleteItem)).not.toHaveBeenCalled();
// Confirm: the API is called and the list refreshes.
const listCallsBefore = vi.mocked(adminListItems).mock.calls.length;
fireEvent.click(screen.getAllByRole('button', { name: /delete/i })[0]);
await screen.findByRole('dialog');
fireEvent.click(screen.getByRole('button', { name: /yes, delete/i }));
await waitFor(() =>
expect(vi.mocked(adminDeleteItem)).toHaveBeenCalledWith(1),
);
expect(
vi.mocked(adminListItems).mock.calls.length,
).toBeGreaterThanOrEqual(listCallsBefore + 1);
});
it('keeps the dialog open and shows the error when the delete fails', async () => {
vi.mocked(adminDeleteItem).mockRejectedValue(
new Error('Deleting the item failed.') as Error & { status?: number },
);
renderDashboard();
await screen.findByText('Story 1');
fireEvent.click(screen.getAllByRole('button', { name: /delete/i })[0]);
await screen.findByRole('dialog');
fireEvent.click(screen.getByRole('button', { name: /yes, delete/i }));
const alert = await screen.findByRole('alert');
expect(alert).toHaveTextContent(/deleting the item failed/i);
// Dialog still open.
expect(screen.getByRole('dialog')).toBeInTheDocument();
});
});
@@ -0,0 +1,111 @@
/**
* Tests for the DeleteConfirmation modal (M6): warning layout, explicit
* "Yes, delete" confirmation, cancel/Escape/overlay dismissal and the
* busy state while the request is in flight.
*/
import { act, fireEvent, render, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import { DeleteConfirmation } from '../../components/DeleteConfirmation';
import type { AdminItem } from '../../types/admin';
const ITEM: AdminItem = {
id: 42,
title: 'Breaking: the sky is falling',
url: 'https://example.com/sky',
points: 12,
username: 'alice',
content: '<p>…</p>',
created_at: '2024-05-01T12:00:00Z',
};
function renderModal(props: Partial<Parameters<typeof DeleteConfirmation>[0]> = {}) {
const onConfirm = vi.fn();
const onCancel = vi.fn();
const utils = render(
<DeleteConfirmation
item={ITEM}
onConfirm={onConfirm}
onCancel={onCancel}
{...props}
/>,
);
return { onConfirm, onCancel, ...utils };
}
describe('DeleteConfirmation', () => {
it('shows the warning layout with the item title', () => {
renderModal();
const dialog = screen.getByRole('dialog');
expect(
screen.getByRole('heading', { name: /are you sure you want to delete/i }),
).toBeInTheDocument();
expect(dialog).toHaveTextContent('Breaking: the sky is falling');
expect(dialog).toHaveTextContent(/cannot be undone/i);
expect(
screen.getByRole('button', { name: /yes, delete/i }),
).toBeInTheDocument();
expect(screen.getByRole('button', { name: /cancel/i })).toBeInTheDocument();
});
it('calls onConfirm when "Yes, delete" is clicked', () => {
const { onConfirm } = renderModal();
fireEvent.click(screen.getByTestId('confirm-delete'));
expect(onConfirm).toHaveBeenCalledTimes(1);
});
it('calls onCancel when Cancel is clicked', () => {
const { onCancel } = renderModal();
fireEvent.click(screen.getByRole('button', { name: /cancel/i }));
expect(onCancel).toHaveBeenCalledTimes(1);
});
it('closes on overlay click but not on dialog click', () => {
const { onCancel } = renderModal();
const dialog = screen.getByRole('dialog');
const overlay = dialog.parentElement as HTMLElement;
fireEvent.click(overlay);
expect(onCancel).toHaveBeenCalledTimes(1);
fireEvent.click(dialog);
expect(onCancel).toHaveBeenCalledTimes(1); // unchanged — stopPropagation
});
it('closes on the Escape key', () => {
const { onCancel } = renderModal();
act(() => {
fireEvent.keyDown(document, { key: 'Escape' });
});
expect(onCancel).toHaveBeenCalledTimes(1);
});
it('disables both actions and ignores Escape while busy', () => {
const { onCancel } = renderModal({ busy: true });
const confirm = screen.getByRole('button', { name: /deleting…/i });
const cancel = screen.getByRole('button', { name: /cancel/i });
expect(confirm).toBeDisabled();
expect(cancel).toBeDisabled();
expect(confirm).toHaveTextContent(/deleting…/i);
act(() => {
fireEvent.keyDown(document, { key: 'Escape' });
});
fireEvent.click(cancel);
expect(onCancel).not.toHaveBeenCalled();
});
it('renders an error message when provided', () => {
renderModal({ error: 'Deleting the item failed.' });
expect(screen.getByRole('alert')).toHaveTextContent('Deleting the item failed.');
});
});
@@ -0,0 +1,253 @@
/**
* Tests for the EditItemPage (M6): create/edit form validation, prefill
* in edit mode, save flows (success navigation + error display) and the
* load-failure view. The Lexical editor is stubbed; its HTML contract
* is exercised through the `editor-body` textarea.
*/
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { Mock } from 'vitest';
import {
adminCreateItem,
adminGetItem,
adminUpdateItem,
} from '../../api/admin';
import { ApiError, TOKEN_KEY, me as clientMe } from '../../api/client';
import { AuthProvider } from '../../auth';
import { EditItemPage as EditPage } from '../../pages/EditItemPage';
import type { AdminItem } from '../../types/admin';
vi.mock('../../api/admin', () => ({
adminListItems: vi.fn(),
adminGetItem: vi.fn(),
adminCreateItem: vi.fn(),
adminUpdateItem: vi.fn(),
adminDeleteItem: vi.fn(),
}));
vi.mock('../../components/LexicalEditor', () => ({
LexicalEditor: ({
initialHtml,
onChange,
}: {
initialHtml: string;
onChange: (html: string) => void;
placeholder?: string;
}) => (
<div data-testid="lexical-stub">
<textarea
data-testid="editor-body"
defaultValue={initialHtml}
aria-label="Item content"
onChange={(event) => onChange(event.target.value)}
/>
</div>
),
}));
vi.mock('../../api/client', async () => {
const actual = await vi.importActual<typeof import('../../api/client')>(
'../../api/client',
);
return {
...actual,
me: vi.fn(),
login: vi.fn(),
register: vi.fn(),
logout: vi.fn(),
TOKEN_KEY: 'AUTH_TOKEN',
};
});
const ITEM: AdminItem = {
id: 5,
title: 'Original headline',
url: 'https://example.com/original',
points: 11,
username: 'alice',
content: '<p>Original body</p>',
created_at: '2024-05-01T12:00:00Z',
};
function DashboardStub() {
const location = useLocation();
const notice = (location.state as { notice?: string } | null)?.notice ?? '';
return (
<div data-testid="dashboard-stub">
{notice && <p data-testid="dashboard-notice">{notice}</p>}
</div>
);
}
function renderAt(path: string) {
return render(
<MemoryRouter
initialEntries={[path]}
future={{ v7_startTransition: true, v7_relativeSplatPath: true }}
>
<AuthProvider>
<Routes>
<Route path="/admin" element={<DashboardStub />} />
<Route path="/admin/items/new" element={<EditPage />} />
<Route path="/admin/items/:id/edit" element={<EditPage />} />
</Routes>
</AuthProvider>
</MemoryRouter>,
);
}
describe('EditItemPage (create)', () => {
beforeEach(() => {
localStorage.clear();
vi.clearAllMocks();
(clientMe as Mock).mockResolvedValue({ username: 'root', is_admin: true });
localStorage.setItem(TOKEN_KEY, 'token');
vi.mocked(adminCreateItem).mockResolvedValue({ ...ITEM, id: 99 });
vi.mocked(adminUpdateItem).mockResolvedValue(ITEM);
});
it('pre-fills the author with the signed-in admin', async () => {
renderAt('/admin/items/new');
await screen.findByTestId('lexical-stub');
expect(screen.getByLabelText('Author')).toHaveValue('root');
expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent('New item');
});
it('blocks submission with an empty title and does not call the API', async () => {
renderAt('/admin/items/new');
await screen.findByTestId('lexical-stub');
screen.getByRole('button', { name: /create item/i }).click();
// The field error and the form-level error are both alerts.
const alerts = await screen.findAllByRole('alert');
expect(
alerts.some((el) => /title is required/i.test(el.textContent ?? '')),
).toBe(true);
expect(vi.mocked(adminCreateItem)).not.toHaveBeenCalled();
expect(screen.queryByTestId('dashboard-stub')).not.toBeInTheDocument();
});
it('rejects an invalid URL client-side', async () => {
renderAt('/admin/items/new');
await screen.findByTestId('lexical-stub');
fireEvent.change(screen.getByLabelText(/^Title/), { target: { value: 'Has url' } });
fireEvent.change(screen.getByLabelText(/^URL/), {
target: { value: 'not a url' },
});
screen.getByRole('button', { name: /create item/i }).click();
const alerts = await screen.findAllByRole('alert');
expect(
alerts.some((el) => /http:\/\/ or https:\/\//i.test(el.textContent ?? '')),
).toBe(true);
expect(vi.mocked(adminCreateItem)).not.toHaveBeenCalled();
});
it('creates the item with trimmed values and navigates back with a notice', async () => {
renderAt('/admin/items/new');
await screen.findByTestId('lexical-stub');
fireEvent.change(screen.getByLabelText(/^Title/), {
target: { value: ' Fresh story ' },
});
fireEvent.change(screen.getByLabelText(/^URL/), {
target: { value: ' https://example.com/fresh ' },
});
fireEvent.change(screen.getByLabelText('Points'), { target: { value: '7' } });
fireEvent.change(screen.getByTestId('editor-body'), {
target: { value: '<p>Body <strong>here</strong></p>' },
});
screen.getByRole('button', { name: /create item/i }).click();
await waitFor(() =>
expect(vi.mocked(adminCreateItem)).toHaveBeenCalledWith({
title: 'Fresh story',
url: 'https://example.com/fresh',
points: 7,
username: 'root',
content: '<p>Body <strong>here</strong></p>',
}),
);
expect(await screen.findByTestId('dashboard-stub')).toBeInTheDocument();
expect(screen.getByTestId('dashboard-notice')).toHaveTextContent(
'“Fresh story” was saved.',
);
});
it('shows the backend error when the create request fails', async () => {
vi.mocked(adminCreateItem).mockRejectedValue(
new ApiError(422, 'Validation failed', 'validation_error'),
);
renderAt('/admin/items/new');
await screen.findByTestId('lexical-stub');
fireEvent.change(screen.getByLabelText(/^Title/), { target: { value: 'x' } });
screen.getByRole('button', { name: /create item/i }).click();
expect(await screen.findByRole('alert')).toHaveTextContent('Validation failed');
});
});
describe('EditItemPage (edit)', () => {
beforeEach(() => {
localStorage.clear();
vi.clearAllMocks();
(clientMe as Mock).mockResolvedValue({ username: 'root', is_admin: true });
localStorage.setItem(TOKEN_KEY, 'token');
vi.mocked(adminGetItem).mockResolvedValue(ITEM);
vi.mocked(adminUpdateItem).mockResolvedValue(ITEM);
});
it('loads and pre-fills the item, then updates it on save', async () => {
renderAt('/admin/items/5/edit');
// Loading state first.
expect(screen.getByRole('status')).toHaveTextContent(/loading item/i);
await screen.findByTestId('lexical-stub');
expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent(
'Edit item #5',
);
expect(screen.getByLabelText(/^Title/)).toHaveValue('Original headline');
expect(screen.getByLabelText(/^URL/)).toHaveValue('https://example.com/original');
expect(screen.getByLabelText('Points')).toHaveValue(11);
expect(screen.getByLabelText('Author')).toHaveValue('alice');
expect(screen.getByTestId('editor-body')).toHaveValue('<p>Original body</p>');
fireEvent.change(screen.getByLabelText(/^Title/), {
target: { value: 'Retitled' },
});
screen.getByRole('button', { name: /save changes/i }).click();
await waitFor(() =>
expect(vi.mocked(adminUpdateItem)).toHaveBeenCalledWith(5, {
title: 'Retitled',
url: 'https://example.com/original',
points: 11,
username: 'alice',
content: '<p>Original body</p>',
}),
);
expect(await screen.findByTestId('dashboard-stub')).toBeInTheDocument();
});
it('shows the not-found view when the item cannot be loaded', async () => {
vi.mocked(adminGetItem).mockRejectedValue(
Object.assign(new Error('Item not found'), { status: 404 }),
);
renderAt('/admin/items/999/edit');
expect(await screen.findByRole('heading', { level: 1 })).toHaveTextContent(
/item not found/i,
);
expect(screen.getByRole('link', { name: /back to items/i })).toHaveAttribute(
'href',
'/admin',
);
});
});
@@ -0,0 +1,87 @@
/**
* Tests for the RequireAdmin route guard (M6): signed-out users are
* redirected to /login, authenticated non-admins see the 403 page, and
* admins get the protected content.
*/
import { render, screen } from '@testing-library/react';
import { MemoryRouter, Route, Routes } from 'react-router-dom';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { Mock } from 'vitest';
import { TOKEN_KEY, me as clientMe } from '../../api/client';
import { AuthProvider, RequireAdmin } from '../../auth';
vi.mock('../../api/client', () => ({
TOKEN_KEY: 'AUTH_TOKEN',
login: vi.fn(),
register: vi.fn(),
me: vi.fn(),
logout: vi.fn(),
}));
const routes = (
<Routes>
<Route path="/login" element={<div>Login page</div>} />
<Route
path="/admin"
element={
<RequireAdmin>
<div data-testid="admin-content">Admin dashboard</div>
</RequireAdmin>
}
/>
</Routes>
);
function renderAt(path: string) {
return render(
<MemoryRouter
initialEntries={[path]}
future={{ v7_startTransition: true, v7_relativeSplatPath: true }}
>
<AuthProvider>{routes}</AuthProvider>
</MemoryRouter>,
);
}
describe('RequireAdmin', () => {
beforeEach(() => {
localStorage.clear();
vi.clearAllMocks();
});
it('redirects signed-out users to /login', async () => {
renderAt('/admin');
expect(await screen.findByText('Login page')).toBeInTheDocument();
});
it('shows the 403 page for an authenticated non-admin', async () => {
(clientMe as Mock).mockResolvedValue({ username: 'alice', is_admin: false });
localStorage.setItem(TOKEN_KEY, 'token');
renderAt('/admin');
expect(await screen.findByTestId('forbidden-page')).toBeInTheDocument();
expect(screen.getByRole('heading', { level: 1, name: '403' })).toBeInTheDocument();
expect(screen.getByRole('alert')).toHaveTextContent(/admin area/i);
expect(screen.queryByTestId('admin-content')).not.toBeInTheDocument();
});
it('treats a missing is_admin flag as non-admin (defensive)', async () => {
(clientMe as Mock).mockResolvedValue({ username: 'alice' });
localStorage.setItem(TOKEN_KEY, 'token');
renderAt('/admin');
expect(await screen.findByTestId('forbidden-page')).toBeInTheDocument();
});
it('renders the protected content for an admin', async () => {
(clientMe as Mock).mockResolvedValue({ username: 'root', is_admin: true });
localStorage.setItem(TOKEN_KEY, 'token');
renderAt('/admin');
expect(await screen.findByTestId('admin-content')).toBeInTheDocument();
expect(screen.queryByTestId('forbidden-page')).not.toBeInTheDocument();
});
});
+54
View File
@@ -0,0 +1,54 @@
/**
* Admin area types (mirror the backend `schemas.item` payloads).
*
* The backend returns snake_case JSON; these interfaces keep the wire
* shape 1:1 (no remapping) because they are only consumed by the admin
* pages.
*/
/** One news item as managed in the admin area. */
export interface AdminItem {
id: number;
title: string;
url: string;
points: number;
/** Username the item belongs to (denormalized). */
username: string;
/** HTML body produced by the Lexical editor. */
content: string;
/** ISO-8601 timestamp. */
created_at: string;
}
/** Payload of `GET /api/v1/admin/items` (paginated list). */
export interface AdminItemsPage {
items: AdminItem[];
total: number;
page: number;
page_size: number;
total_pages: number;
}
/** Sortable columns of the item list. */
export type AdminSortBy = 'title' | 'created_at' | 'points';
export type AdminSortOrder = 'asc' | 'desc';
/** Query parameters of the item list endpoint. */
export interface AdminListParams {
page: number;
pageSize: number;
/** Case-insensitive match on title OR url. */
search: string;
sortBy: AdminSortBy;
sortOrder: AdminSortOrder;
}
/** Payload of `POST /api/v1/admin/items` and `PUT /api/v1/admin/items/{id}`. */
export interface AdminItemInput {
title: string;
url: string;
points: number;
username: string;
content: string;
}
+4
View File
@@ -7,9 +7,13 @@ export interface TokenResponse {
/** Signed JWT (7-day expiry) — store and send back as `Bearer` token. */
token: string;
username: string;
/** Whether the account may access the admin area (M6). */
is_admin?: boolean;
}
/** Payload of `GET /api/v1/auth/me`. */
export interface MeResponse {
username: string;
/** Whether the account may access the admin area (M6). */
is_admin?: boolean;
}