Files
wiki/src/shared/LexicalEditor.tsx
T
2025-11-07 02:50:20 +09:00

725 lines
24 KiB
TypeScript

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 type { EditorState } from 'lexical';
import { $getRoot, $createParagraphNode, $createTextNode, FORMAT_TEXT_COMMAND, FORMAT_ELEMENT_COMMAND, $getSelection, $isRangeSelection, TextNode } from 'lexical';
import { INSERT_TABLE_COMMAND } 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: 'bg-[#1e1e1e] p-4 rounded font-mono text-sm text-[#e4e4e4] mb-2 block overflow-x-auto',
link: 'text-[#4db8ff] hover:text-[#8cd7ff] underline cursor-pointer',
table: 'border-collapse table-auto w-full my-4',
tableCell: 'border border-[#3e3e42] px-3 py-2 text-[#e4e4e4] min-w-[100px]',
tableCellHeader: 'border border-[#3e3e42] px-3 py-2 text-[#e4e4e4] font-bold bg-[#2d2d30]',
};
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' },
];
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 <OnChangePlugin onChange={handleChange} />;
}
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 handleFontChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
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<HTMLSelectElement>) => {
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 });
};
return (
<div className="flex flex-wrap gap-1 p-2 bg-[#252526] border border-[#3e3e42] rounded-t mb-[-1px] relative z-10">
{/* Font Family */}
<select
value={fontFamily}
onChange={handleFontChange}
className="px-3 py-1.5 text-sm bg-[#2d2d30] hover:bg-[#3e3e42] text-[#e4e4e4] rounded transition-colors border border-[#3e3e42] focus:outline-none focus:border-[#0078d4] cursor-pointer"
title="텍스트를 선택한 후 글꼴을 변경하세요"
>
{FONT_FAMILIES.map((font) => (
<option key={font.value} value={font.value} style={{ fontFamily: font.value }}>
{font.name}
</option>
))}
</select>
{/* Font Size */}
<select
value={fontSize}
onChange={handleFontSizeChange}
className="w-20 px-2 py-1.5 text-sm bg-[#2d2d30] hover:bg-[#3e3e42] text-[#e4e4e4] rounded transition-colors border border-[#3e3e42] focus:outline-none focus:border-[#0078d4] cursor-pointer"
title="텍스트를 선택한 후 크기를 변경하세요"
>
{FONT_SIZES.map((size) => (
<option key={size.value} value={size.value}>
{size.name}
</option>
))}
</select>
<button
onClick={decreaseFontSize}
className="px-2 py-1.5 text-sm bg-[#2d2d30] hover:bg-[#3e3e42] text-[#e4e4e4] rounded transition-colors"
title="글씨 크기 감소"
type="button"
>
가-
</button>
<button
onClick={increaseFontSize}
className="px-2 py-1.5 text-sm bg-[#2d2d30] hover:bg-[#3e3e42] text-[#e4e4e4] rounded transition-colors"
title="글씨 크기 증가"
type="button"
>
가+
</button>
<div className="w-px h-6 bg-[#3e3e42] mx-1 self-center"></div>
{/* Text Formatting */}
<button
onClick={formatBold}
className="px-3 py-1.5 text-sm font-bold bg-[#2d2d30] hover:bg-[#3e3e42] text-[#e4e4e4] rounded transition-colors"
title="Bold (Ctrl+B)"
type="button"
>
B
</button>
<button
onClick={formatItalic}
className="px-3 py-1.5 text-sm italic bg-[#2d2d30] hover:bg-[#3e3e42] text-[#e4e4e4] rounded transition-colors"
title="Italic (Ctrl+I)"
type="button"
>
I
</button>
<button
onClick={formatUnderline}
className="px-3 py-1.5 text-sm underline bg-[#2d2d30] hover:bg-[#3e3e42] text-[#e4e4e4] rounded transition-colors"
title="Underline (Ctrl+U)"
type="button"
>
U
</button>
<button
onClick={formatCode}
className="px-3 py-1.5 text-sm font-mono bg-[#2d2d30] hover:bg-[#3e3e42] text-[#4db8ff] rounded transition-colors"
title="Inline Code"
type="button"
>
&lt;/&gt;
</button>
<div className="w-px h-6 bg-[#3e3e42] mx-1 self-center"></div>
{/* Headings */}
<button
onClick={() => insertHeading('h1')}
className="px-3 py-1.5 text-sm font-bold bg-[#2d2d30] hover:bg-[#3e3e42] text-[#e4e4e4] rounded transition-colors"
title="Heading 1"
type="button"
>
H1
</button>
<button
onClick={() => insertHeading('h2')}
className="px-3 py-1.5 text-sm font-bold bg-[#2d2d30] hover:bg-[#3e3e42] text-[#e4e4e4] rounded transition-colors"
title="Heading 2"
type="button"
>
H2
</button>
<button
onClick={() => insertHeading('h3')}
className="px-3 py-1.5 text-sm font-semibold bg-[#2d2d30] hover:bg-[#3e3e42] text-[#e4e4e4] rounded transition-colors"
title="Heading 3"
type="button"
>
H3
</button>
<div className="w-px h-6 bg-[#3e3e42] mx-1 self-center"></div>
{/* Lists */}
<button
onClick={insertBulletList}
className="px-3 py-1.5 text-sm bg-[#2d2d30] hover:bg-[#3e3e42] text-[#e4e4e4] rounded transition-colors"
title="Bullet List"
type="button"
>
• List
</button>
<button
onClick={insertNumberedList}
className="px-3 py-1.5 text-sm bg-[#2d2d30] hover:bg-[#3e3e42] text-[#e4e4e4] rounded transition-colors"
title="Numbered List"
type="button"
>
1. List
</button>
<button
onClick={insertCodeBlock}
className="px-3 py-1.5 text-sm font-mono bg-[#2d2d30] hover:bg-[#3e3e42] text-[#4db8ff] rounded transition-colors"
title="Code Block"
type="button"
>
{'{ }'}
</button>
<div className="w-px h-6 bg-[#3e3e42] mx-1 self-center"></div>
{/* Table */}
<div className="relative">
<button
onClick={() => setShowTablePicker(!showTablePicker)}
className="px-3 py-1.5 text-sm bg-[#2d2d30] hover:bg-[#3e3e42] text-[#e4e4e4] rounded transition-colors"
title="표 삽입"
type="button"
>
⊞
</button>
{showTablePicker && (
<div className="absolute top-full left-0 mt-1 p-2 bg-[#252526] border border-[#3e3e42] rounded shadow-lg z-20">
<div className="text-xs text-[#9d9d9d] mb-2 text-center">
{tableSize.rows > 0 && tableSize.cols > 0
? `${tableSize.rows} x ${tableSize.cols} 표 삽입`
: '표 삽입'}
</div>
<div className="grid gap-0.5">
{Array.from({ length: 8 }, (_, row) => (
<div key={row} className="flex gap-0.5">
{Array.from({ length: 10 }, (_, col) => (
<div
key={col}
className={`w-5 h-5 border border-[#3e3e42] cursor-pointer transition-colors ${
row < tableSize.rows && col < tableSize.cols
? 'bg-[#0078d4]'
: 'bg-[#2d2d30] hover:bg-[#3e3e42]'
}`}
onMouseEnter={() => setTableSize({ rows: row + 1, cols: col + 1 })}
onClick={() => insertTable(row + 1, col + 1)}
/>
))}
</div>
))}
</div>
</div>
)}
</div>
<div className="w-px h-6 bg-[#3e3e42] mx-1 self-center"></div>
{/* Alignment */}
<button
onClick={formatAlignLeft}
className="px-3 py-1.5 text-sm bg-[#2d2d30] hover:bg-[#3e3e42] text-[#e4e4e4] rounded transition-colors"
title="Align Left"
type="button"
>
≡
</button>
<button
onClick={formatAlignCenter}
className="px-3 py-1.5 text-sm bg-[#2d2d30] hover:bg-[#3e3e42] text-[#e4e4e4] rounded transition-colors"
title="Align Center"
type="button"
>
≣
</button>
<button
onClick={formatAlignRight}
className="px-3 py-1.5 text-sm bg-[#2d2d30] hover:bg-[#3e3e42] text-[#e4e4e4] rounded transition-colors"
title="Align Right"
type="button"
>
≡
</button>
</div>
);
}
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 (
<div className="relative">
<LexicalComposer initialConfig={initialConfig}>
<div className="relative">
<ToolbarPlugin
fontFamily={fontFamily}
setFontFamily={setFontFamily}
fontSize={fontSize}
setFontSize={setFontSize}
/>
<RichTextPlugin
contentEditable={
<ContentEditable
className="min-h-[400px] w-full px-4 py-2.5 bg-[#2d2d30] border border-[#3e3e42] rounded rounded-t-none text-[#e4e4e4] focus:outline-none focus:border-[#0078d4] focus:ring-1 focus:ring-[#0078d4] text-sm overflow-y-auto"
/>
}
placeholder={
<div className="absolute top-2.5 left-4 text-[#9d9d9d] pointer-events-none text-sm">
{placeholder}
</div>
}
ErrorBoundary={LexicalErrorBoundary}
/>
<HistoryPlugin />
<ListPlugin />
<LinkPlugin />
<TablePlugin />
<OnChangePluginWrapper onChange={onChange} />
<InitialContentPlugin content={initialContent} />
<HeadingIdPlugin />
<AutoFocusPlugin />
</div>
</LexicalComposer>
</div>
);
}