/** * 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; 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 ( { console.error('Lexical editor error:', error); }, }} > ); } 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 (
} ErrorBoundary={LexicalErrorBoundary} /> {placeholder && } { editorState.read(() => { onChange.current($generateHtmlFromNodes(editor)); }); }} />
); } 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 ( {text} ); } /* --- Toolbar ---------------------------------------------------------------- */ function Toolbar() { const [editor] = useLexicalComposerContext(); const [state, setState] = useState(DEFAULT_TOOLBAR); const [linkInputOpen, setLinkInputOpen] = useState(false); const [linkUrl, setLinkUrl] = useState(''); const linkInputRef = useRef(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) => 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, ) => ( ); return (
{button('Undo', false, () => editor.dispatchCommand(UNDO_COMMAND, undefined), , !state.canUndo)} {button('Redo', false, () => editor.dispatchCommand(REDO_COMMAND, undefined), , !state.canRedo)}
); }