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

+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>
);
}