Files
newz-qwen-27b/frontend/src/components/LexicalEditor.tsx
T
Daniel Samson e62fad4a10 fix: append parsed nodes when loading initial HTML into the Lexical editor
EditorShell's ingest called $generateNodesFromDOM but discarded the
returned nodes, so stored content never appeared in the WYSIWYG editor
in edit mode (the E2E edit test only checked title/points and missed it).
The parsed nodes are now appended to the root (kept empty-paragraph
default when nothing parses).

Hardening tests added while auditing the M6 test checklist:
- E2E: edit view asserts the stored body renders in the editor; new
  hostile-HTML test loads <script> tags, onerror/onload handlers and
  javascript: links through the real editor and asserts none survive
  into the contenteditable and nothing executes.
- E2E/unit: create button is disabled while the request is in flight.
- Backend: SQL metacharacters in the search term behave as literal
  text and leave the table intact.

Milestone doc updated: QA checklist items now cite their tests, plus a
QA-findings note for the ingest bug.
2026-10-30 21:58:23 +00:00

400 lines
13 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 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).
// $generateNodesFromDOM returns the parsed nodes without attaching them,
// so they must be appended to the root manually. Non-whitelisted markup
// (scripts, event handlers, unknown elements) is dropped by the parser,
// which also acts as the XSS boundary for stored content.
useEffect(() => {
if (!initialHtml) return;
const doc = document.implementation.createHTMLDocument('');
doc.body.innerHTML = initialHtml;
editor.update(
() => {
const nodes = $generateNodesFromDOM(editor, doc);
if (nodes.length === 0) return; // keep the default empty paragraph
const root = $getRoot();
root.clear();
root.append(...nodes);
},
{ 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>
);
}