import { useEffect, useRef, useState } from 'react'; import { LexicalComposer } from '@lexical/react/LexicalComposer'; import { RichTextPlugin } from '@lexical/react/LexicalRichTextPlugin'; import { ContentEditable } from '@lexical/react/LexicalContentEditable'; import { HistoryPlugin } from '@lexical/react/LexicalHistoryPlugin'; import { OnChangePlugin } from '@lexical/react/LexicalOnChangePlugin'; import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'; import { LexicalErrorBoundary } from '@lexical/react/LexicalErrorBoundary'; import { ListPlugin } from '@lexical/react/LexicalListPlugin'; import { LinkPlugin } from '@lexical/react/LexicalLinkPlugin'; import { HeadingNode, QuoteNode } from '@lexical/rich-text'; import { ListNode, ListItemNode } from '@lexical/list'; import { CodeNode, CodeHighlightNode } from '@lexical/code'; import { LinkNode, AutoLinkNode } from '@lexical/link'; import { TableNode, TableCellNode, TableRowNode } from '@lexical/table'; import { TablePlugin } from '@lexical/react/LexicalTablePlugin'; import { TableResizerPlugin } from './TableResizerPlugin'; import { CodeHighlightPlugin } from './CodeHighlightPlugin'; import { CodeActionMenuPlugin } from './CodeActionMenuPlugin'; import { CodeLanguagePlugin } from './CodeLanguagePlugin'; import type { EditorState } from 'lexical'; import { $getRoot, $createParagraphNode, $createTextNode, FORMAT_TEXT_COMMAND, FORMAT_ELEMENT_COMMAND, $getSelection, $isRangeSelection, TextNode, type LexicalNode } from 'lexical'; import { INSERT_TABLE_COMMAND, $isTableCellNode } from '@lexical/table'; import { $createHeadingNode } from '@lexical/rich-text'; import { INSERT_UNORDERED_LIST_COMMAND, INSERT_ORDERED_LIST_COMMAND } from '@lexical/list'; import { $createCodeNode } from '@lexical/code'; import { $setBlocksType } from '@lexical/selection'; const editorTheme = { paragraph: 'mb-2 text-[#e4e4e4]', heading: { h1: 'text-3xl font-bold mb-4 text-[#e4e4e4] scroll-mt-20', h2: 'text-2xl font-bold mb-3 text-[#e4e4e4] scroll-mt-20', h3: 'text-xl font-semibold mb-2 text-[#e4e4e4] scroll-mt-20', }, list: { ul: 'list-disc list-inside mb-2 text-[#e4e4e4]', ol: 'list-decimal list-inside mb-2 text-[#e4e4e4]', listitem: 'ml-4', }, text: { bold: 'font-bold', italic: 'italic', underline: 'underline', code: 'bg-[#1e1e1e] px-1.5 py-0.5 rounded font-mono text-sm text-[#4db8ff]', }, code: 'relative bg-[#1e1e1e] border border-[#3e3e42] rounded-md font-mono text-sm mb-2 block', codeHighlight: { atrule: 'token atrule', attr: 'token attr', boolean: 'token boolean', builtin: 'token builtin', cdata: 'token cdata', char: 'token char', class: 'token class-name', 'class-name': 'token class-name', comment: 'token comment', constant: 'token constant', deleted: 'token deleted', doctype: 'token doctype', entity: 'token entity', function: 'token function', important: 'token important', inserted: 'token inserted', keyword: 'token keyword', namespace: 'token namespace', number: 'token number', operator: 'token operator', prolog: 'token prolog', property: 'token property', punctuation: 'token punctuation', regex: 'token regex', selector: 'token selector', string: 'token string', symbol: 'token symbol', tag: 'token tag', url: 'token url', variable: 'token variable', }, link: 'text-[#4db8ff] hover:text-[#8cd7ff] underline cursor-pointer', table: 'border-collapse w-full my-4', tableCell: 'border border-[#3e3e42] px-3 py-2 text-[#e4e4e4] relative', tableCellHeader: 'border border-[#3e3e42] px-3 py-2 text-[#e4e4e4] font-bold bg-[#2d2d30] relative', tableRow: '', tableSelection: 'table-cell-selected', tableCellSelected: 'table-cell-selected', }; interface LexicalEditorProps { initialContent?: string; onChange: (content: string) => void; placeholder?: string; } const FONT_FAMILIES = [ { name: 'Noto Sans KR', value: '"Noto Sans KR", sans-serif' }, { name: 'Noto Serif KR', value: '"Noto Serif KR", serif' }, { name: 'Gothic A1', value: '"Gothic A1", sans-serif' }, { name: 'Gowun Batang', value: '"Gowun Batang", serif' }, { name: 'Gowun Dodum', value: '"Gowun Dodum", sans-serif' }, { name: 'Asta Sans', value: '"Asta Sans", sans-serif' }, { name: 'Chiron GoRound TC', value: '"Chiron GoRound TC", sans-serif' }, ]; const FONT_SIZES = [ { name: '10px', value: '10px' }, { name: '12px', value: '12px' }, { name: '14px', value: '14px' }, { name: '16px', value: '16px' }, { name: '18px', value: '18px' }, { name: '20px', value: '20px' }, { name: '24px', value: '24px' }, { name: '28px', value: '28px' }, { name: '32px', value: '32px' }, { name: '36px', value: '36px' }, { name: '48px', value: '48px' }, ]; const CELL_COLORS = [ { name: '없음', value: 'transparent' }, { name: '빨강', value: '#ffebee' }, { name: '주황', value: '#fff3e0' }, { name: '노랑', value: '#fffde7' }, { name: '초록', value: '#e8f5e9' }, { name: '파랑', value: '#e3f2fd' }, { name: '보라', value: '#f3e5f5' }, { name: '회색', value: '#f5f5f5' }, { name: '진한 빨강', value: '#ef5350' }, { name: '진한 주황', value: '#ff9800' }, { name: '진한 노랑', value: '#fdd835' }, { name: '진한 초록', value: '#66bb6a' }, { name: '진한 파랑', value: '#42a5f5' }, { name: '진한 보라', value: '#ab47bc' }, ]; function OnChangePluginWrapper({ onChange }: { onChange: (content: string) => void }) { const handleChange = (editorState: EditorState) => { // Serialize the entire editor state as JSON to preserve formatting const json = JSON.stringify(editorState.toJSON()); onChange(json); }; return ; } function InitialContentPlugin({ content }: { content?: string }) { const [editor] = useLexicalComposerContext(); const isInitialized = useRef(false); useEffect(() => { // Only set initial content once, on mount if (content && !isInitialized.current) { isInitialized.current = true; try { // Try to parse as JSON first (new format) const editorState = editor.parseEditorState(content); editor.setEditorState(editorState); } catch { // Fallback to plain text (legacy format) editor.update(() => { const root = $getRoot(); root.clear(); const lines = content.split('\n'); lines.forEach((line) => { const paragraph = $createParagraphNode(); const text = $createTextNode(line); paragraph.append(text); root.append(paragraph); }); }); } } }, [editor, content]); return null; } function AutoFocusPlugin() { const [editor] = useLexicalComposerContext(); useEffect(() => { editor.focus(); }, [editor]); return null; } function HeadingIdPlugin() { const [editor] = useLexicalComposerContext(); useEffect(() => { // Add data attribute and ID to heading elements for TOC const updateHeadings = () => { const headings = document.querySelectorAll('h1, h2, h3'); headings.forEach((heading, index) => { if (heading instanceof HTMLElement) { if (!heading.hasAttribute('data-lexical-heading')) { heading.setAttribute('data-lexical-heading', 'true'); } if (!heading.id) { const text = heading.textContent || ''; heading.id = `heading-${index}-${text.toLowerCase().replace(/\s+/g, '-').slice(0, 30)}`; } } }); }; // Initial update updateHeadings(); // Also register mutation listener const unregister = editor.registerMutationListener(HeadingNode, () => { setTimeout(updateHeadings, 50); }); // Update periodically as backup const interval = setInterval(updateHeadings, 1000); return () => { unregister(); clearInterval(interval); }; }, [editor]); return null; } interface ToolbarPluginProps { fontFamily: string; setFontFamily: (font: string) => void; fontSize: string; setFontSize: (size: string) => void; } function ToolbarPlugin({ fontFamily, setFontFamily, fontSize, setFontSize }: ToolbarPluginProps) { const [editor] = useLexicalComposerContext(); const [showTablePicker, setShowTablePicker] = useState(false); const [tableSize, setTableSize] = useState({ rows: 0, cols: 0 }); const [showColorPicker, setShowColorPicker] = useState(false); const handleFontChange = (e: React.ChangeEvent) => { const newFont = e.target.value; setFontFamily(newFont); // Apply font to selected text only editor.update(() => { const selection = $getSelection(); if ($isRangeSelection(selection)) { // Check if there's actually a selection if (selection.isCollapsed()) { return; } const nodes = selection.getNodes(); if (nodes.length === 0) { return; } const anchor = selection.anchor; const focus = selection.focus; const [start, end] = anchor.isBefore(focus) ? [anchor, focus] : [focus, anchor]; nodes.forEach((node, idx) => { if (node instanceof TextNode) { const isFirst = idx === 0; const isLast = idx === nodes.length - 1; const isOnlyNode = nodes.length === 1; let startOffset = 0; let endOffset = node.getTextContentSize(); // Determine start offset for the first node if (isFirst && start.getNode() === node) { startOffset = start.offset; } // Determine end offset for the last node if (isLast && end.getNode() === node) { endOffset = end.offset; } // Skip if no actual text is selected in this node if (startOffset >= endOffset) { return; } // Handle the text splitting if (isOnlyNode || (isFirst && isLast)) { // Single node selection if (startOffset === 0 && endOffset === node.getTextContentSize()) { // Entire node is selected applyFontToNode(node, newFont); } else if (startOffset === 0) { // Selection starts at beginning const [leftNode] = node.splitText(endOffset); applyFontToNode(leftNode, newFont); } else if (endOffset === node.getTextContentSize()) { // Selection ends at end const [, rightNode] = node.splitText(startOffset); applyFontToNode(rightNode, newFont); } else { // Selection is in the middle const [, middleNode] = node.splitText(startOffset); const [selectedNode] = middleNode.splitText(endOffset - startOffset); applyFontToNode(selectedNode, newFont); } } else if (isFirst) { // First node of multi-node selection if (startOffset === 0) { applyFontToNode(node, newFont); } else { const [, rightNode] = node.splitText(startOffset); applyFontToNode(rightNode, newFont); } } else if (isLast) { // Last node of multi-node selection if (endOffset === node.getTextContentSize()) { applyFontToNode(node, newFont); } else { const [leftNode] = node.splitText(endOffset); applyFontToNode(leftNode, newFont); } } else { // Middle nodes are fully selected applyFontToNode(node, newFont); } } }); } }); }; const applyFontToNode = (node: TextNode, fontFamily: string) => { applyStyleToNode(node, 'font-family', fontFamily); }; const applyStyleToNode = (node: TextNode, property: string, value: string) => { const currentStyle = node.getStyle(); const regex = new RegExp(`${property}:[^;]+;?`, 'g'); const styleWithoutProperty = currentStyle.replace(regex, '').trim(); const newStyle = styleWithoutProperty ? `${styleWithoutProperty}; ${property}: ${value}` : `${property}: ${value}`; node.setStyle(newStyle); }; const handleFontSizeChange = (e: React.ChangeEvent) => { const newSize = e.target.value; setFontSize(newSize); applyFontSizeToSelection(newSize); }; const increaseFontSize = () => { const currentIdx = FONT_SIZES.findIndex(f => f.value === fontSize); const nextIdx = Math.min(currentIdx + 1, FONT_SIZES.length - 1); const newSize = FONT_SIZES[nextIdx].value; setFontSize(newSize); applyFontSizeToSelection(newSize); }; const decreaseFontSize = () => { const currentIdx = FONT_SIZES.findIndex(f => f.value === fontSize); const prevIdx = Math.max(currentIdx - 1, 0); const newSize = FONT_SIZES[prevIdx].value; setFontSize(newSize); applyFontSizeToSelection(newSize); }; const applyFontSizeToSelection = (size: string) => { editor.update(() => { const selection = $getSelection(); if ($isRangeSelection(selection)) { if (selection.isCollapsed()) { return; } const nodes = selection.getNodes(); if (nodes.length === 0) { return; } const anchor = selection.anchor; const focus = selection.focus; const [start, end] = anchor.isBefore(focus) ? [anchor, focus] : [focus, anchor]; nodes.forEach((node, idx) => { if (node instanceof TextNode) { const isFirst = idx === 0; const isLast = idx === nodes.length - 1; const isOnlyNode = nodes.length === 1; let startOffset = 0; let endOffset = node.getTextContentSize(); if (isFirst && start.getNode() === node) { startOffset = start.offset; } if (isLast && end.getNode() === node) { endOffset = end.offset; } if (startOffset >= endOffset) { return; } if (isOnlyNode || (isFirst && isLast)) { if (startOffset === 0 && endOffset === node.getTextContentSize()) { applyStyleToNode(node, 'font-size', size); } else if (startOffset === 0) { const [leftNode] = node.splitText(endOffset); applyStyleToNode(leftNode, 'font-size', size); } else if (endOffset === node.getTextContentSize()) { const [, rightNode] = node.splitText(startOffset); applyStyleToNode(rightNode, 'font-size', size); } else { const [, middleNode] = node.splitText(startOffset); const [selectedNode] = middleNode.splitText(endOffset - startOffset); applyStyleToNode(selectedNode, 'font-size', size); } } else if (isFirst) { if (startOffset === 0) { applyStyleToNode(node, 'font-size', size); } else { const [, rightNode] = node.splitText(startOffset); applyStyleToNode(rightNode, 'font-size', size); } } else if (isLast) { if (endOffset === node.getTextContentSize()) { applyStyleToNode(node, 'font-size', size); } else { const [leftNode] = node.splitText(endOffset); applyStyleToNode(leftNode, 'font-size', size); } } else { applyStyleToNode(node, 'font-size', size); } } }); } }); }; const formatBold = () => { editor.dispatchCommand(FORMAT_TEXT_COMMAND, 'bold'); }; const formatItalic = () => { editor.dispatchCommand(FORMAT_TEXT_COMMAND, 'italic'); }; const formatUnderline = () => { editor.dispatchCommand(FORMAT_TEXT_COMMAND, 'underline'); }; const formatCode = () => { editor.dispatchCommand(FORMAT_TEXT_COMMAND, 'code'); }; const insertHeading = (level: 'h1' | 'h2' | 'h3') => { editor.update(() => { const selection = $getSelection(); if ($isRangeSelection(selection)) { $setBlocksType(selection, () => $createHeadingNode(level)); } }); }; const insertBulletList = () => { editor.dispatchCommand(INSERT_UNORDERED_LIST_COMMAND, undefined); }; const insertNumberedList = () => { editor.dispatchCommand(INSERT_ORDERED_LIST_COMMAND, undefined); }; const insertCodeBlock = () => { editor.update(() => { const selection = $getSelection(); if ($isRangeSelection(selection)) { $setBlocksType(selection, () => $createCodeNode()); } }); }; const formatAlignLeft = () => { editor.dispatchCommand(FORMAT_ELEMENT_COMMAND, 'left'); }; const formatAlignCenter = () => { editor.dispatchCommand(FORMAT_ELEMENT_COMMAND, 'center'); }; const formatAlignRight = () => { editor.dispatchCommand(FORMAT_ELEMENT_COMMAND, 'right'); }; const insertTable = (rows: number, cols: number) => { editor.dispatchCommand(INSERT_TABLE_COMMAND, { rows: String(rows), columns: String(cols) }); setShowTablePicker(false); setTableSize({ rows: 0, cols: 0 }); }; const setCellBackgroundColor = (color: string) => { editor.update(() => { const selection = $getSelection(); if (!selection) return; const nodes = selection.getNodes(); nodes.forEach(node => { // 선택된 노드의 부모를 찾아서 TableCellNode인지 확인 let currentNode: LexicalNode | null = node; while (currentNode) { if ($isTableCellNode(currentNode)) { currentNode.setBackgroundColor(color); break; } currentNode = currentNode.getParent(); } }); }); setShowColorPicker(false); }; return (
{/* Font Family */} {/* Font Size */}
{/* Text Formatting */}
{/* Headings */}
{/* Lists */}
{/* Table */}
{showTablePicker && (
{tableSize.rows > 0 && tableSize.cols > 0 ? `${tableSize.rows} x ${tableSize.cols} 표 삽입` : '표 삽입'}
{Array.from({ length: 8 }, (_, row) => (
{Array.from({ length: 10 }, (_, col) => (
setTableSize({ rows: row + 1, cols: col + 1 })} onClick={() => insertTable(row + 1, col + 1)} /> ))}
))}
)}
{/* Cell Background Color */}
{showColorPicker && (
셀 배경색
{CELL_COLORS.map((color) => ( ))}
)}
{/* Alignment */}
); } function onError(error: Error) { console.error('Lexical Error:', error); } export function LexicalEditor({ initialContent, onChange, placeholder = '내용을 입력하세요...' }: LexicalEditorProps) { const [fontFamily, setFontFamily] = useState(FONT_FAMILIES[0].value); const [fontSize, setFontSize] = useState(FONT_SIZES[3].value); // Default: 16px const initialConfig = { namespace: 'WikiEditor', theme: editorTheme, onError, nodes: [ HeadingNode, ListNode, ListItemNode, QuoteNode, CodeNode, CodeHighlightNode, LinkNode, AutoLinkNode, TableNode, TableCellNode, TableRowNode, ], }; return (
} placeholder={
{placeholder}
} ErrorBoundary={LexicalErrorBoundary} />
); }