This commit is contained in:
dahyeon committed 2025-11-07 09:16:21 +09:00
1 parent 120f150ee3
commit b0140fbafb
9 files changed
+742 -8

No files matched your search

+8
View File
@@ -21,7 +21,9 @@
"@radix-ui/react-icons": "^1.3.2", "@radix-ui/react-icons": "^1.3.2",
"@radix-ui/react-label": "^2.1.8", "@radix-ui/react-label": "^2.1.8",
"@tanstack/react-query": "^5.90.7", "@tanstack/react-query": "^5.90.7",
"@types/prismjs": "^1.26.5",
"lexical": "^0.38.2", "lexical": "^0.38.2",
"prismjs": "^1.30.0",
"react": "^19.1.1", "react": "^19.1.1",
"react-dom": "^19.1.1", "react-dom": "^19.1.1",
"react-router-dom": "^7.9.5" "react-router-dom": "^7.9.5"
@@ -2542,6 +2544,12 @@
"undici-types": "~7.16.0" "undici-types": "~7.16.0"
} }
}, },
"node_modules/@types/prismjs": {
"version": "1.26.5",
"resolved": "https://registry.npmjs.org/@types/prismjs/-/prismjs-1.26.5.tgz",
"integrity": "sha512-AUZTa7hQ2KY5L7AmtSiqxlhWxb4ina0yd8hNbl4TWuqnv/pFP0nDMb3YrfSBf4hJVGLh2YEIBfKaBW/9UEl6IQ==",
"license": "MIT"
},
"node_modules/@types/react": { "node_modules/@types/react": {
"version": "19.2.2", "version": "19.2.2",
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.2.tgz", "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.2.tgz",
+2
View File
@@ -23,7 +23,9 @@
"@radix-ui/react-icons": "^1.3.2", "@radix-ui/react-icons": "^1.3.2",
"@radix-ui/react-label": "^2.1.8", "@radix-ui/react-label": "^2.1.8",
"@tanstack/react-query": "^5.90.7", "@tanstack/react-query": "^5.90.7",
"@types/prismjs": "^1.26.5",
"lexical": "^0.38.2", "lexical": "^0.38.2",
"prismjs": "^1.30.0",
"react": "^19.1.1", "react": "^19.1.1",
"react-dom": "^19.1.1", "react-dom": "^19.1.1",
"react-router-dom": "^7.9.5" "react-router-dom": "^7.9.5"
+280
View File
@@ -1,4 +1,5 @@
@import "tailwindcss"; @import "tailwindcss";
@import "prismjs/themes/prism-tomorrow.css";
@layer base { @layer base {
:root { :root {
@@ -23,6 +24,285 @@
font-family: inherit; font-family: inherit;
} }
/* 테이블 스타일 */
[contenteditable="true"] table {
table-layout: auto;
width: 100%;
border-collapse: collapse;
margin: 1rem auto;
}
/* 테이블 셀 리사이즈 가능하게 */
[contenteditable="true"] table td,
[contenteditable="true"] table th {
position: relative;
overflow: visible;
-webkit-user-select: text;
user-select: text;
}
/* 셀 선택 시 부드러운 전환 */
[contenteditable="true"] table td,
[contenteditable="true"] table th {
transition: background-color 0.15s ease, outline 0.15s ease;
}
/* 테이블 열 리사이저 (경계선) */
[contenteditable="true"] table td:not(:last-child),
[contenteditable="true"] table th:not(:last-child) {
border-right: 2px solid #3e3e42;
transition: border-color 0.2s;
}
[contenteditable="true"] table td:not(:last-child):hover,
[contenteditable="true"] table th:not(:last-child):hover {
border-right: 3px solid #0078d4;
cursor: col-resize;
}
/* 마지막 셀: 표 전체 크기 조정 (왼쪽으로만) */
[contenteditable="true"] table td:last-child,
[contenteditable="true"] table th:last-child {
border-right: 2px solid #3e3e42;
transition: border-color 0.2s;
}
[contenteditable="true"] table td:last-child:hover,
[contenteditable="true"] table th:last-child:hover {
border-right: 4px solid #ff9800;
cursor: ew-resize;
}
/* 열 크기 조정 핸들 추가 */
[contenteditable="true"] table td::after,
[contenteditable="true"] table th::after {
content: '';
position: absolute;
right: -3px;
top: 0;
bottom: 0;
width: 6px;
cursor: col-resize;
z-index: 5;
pointer-events: all;
}
[contenteditable="true"] table td:not(:last-child):hover::after,
[contenteditable="true"] table th:not(:last-child):hover::after {
background-color: rgba(0, 120, 212, 0.3);
z-index: 15;
}
/* 마지막 셀 핸들은 주황색 */
[contenteditable="true"] table td:last-child:hover::after,
[contenteditable="true"] table th:last-child:hover::after {
background-color: rgba(255, 152, 0, 0.4);
cursor: ew-resize;
z-index: 15;
}
/* Lexical 선택된 셀 - 클래스 기반 */
[contenteditable="true"] table td.table-cell-selected,
[contenteditable="true"] table th.table-cell-selected,
[contenteditable="true"] table td.selected,
[contenteditable="true"] table th.selected,
[contenteditable="true"] table td[class*="selected"],
[contenteditable="true"] table th[class*="selected"] {
background-color: rgba(0, 120, 212, 0.3) !important;
position: relative;
z-index: 10;
}
/* Lexical 포커스된 셀 */
[contenteditable="true"] table td:focus-within,
[contenteditable="true"] table th:focus-within {
outline: 2px solid #0078d4;
outline-offset: -1px;
position: relative;
z-index: 10;
}
/* 셀 내부 콘텐츠가 선택된 경우 */
[contenteditable="true"] table td:has(:focus),
[contenteditable="true"] table th:has(:focus) {
background-color: rgba(0, 120, 212, 0.1);
}
/* 셀 내부 콘텐츠 영역 */
[contenteditable="true"] table td,
[contenteditable="true"] table th {
box-sizing: border-box;
}
/* 텍스트 드래그 선택 시 하이라이트 (기본 브라우저 선택) */
[contenteditable="true"] table ::selection {
background-color: rgba(0, 120, 212, 0.6) !important;
color: #fff !important;
}
[contenteditable="true"] table::-moz-selection {
background-color: rgba(0, 120, 212, 0.6) !important;
color: #fff !important;
}
/* Lexical 테이블 셀 선택 오버레이 제거 (기본 스타일과 충돌 방지) */
[contenteditable="true"] table td .TableCellResizer,
[contenteditable="true"] table th .TableCellResizer {
display: none;
}
/* 테이블 전체 선택 스타일 */
[contenteditable="true"] table[data-table-selected] td,
[contenteditable="true"] table[data-table-selected] th {
background-color: rgba(0, 120, 212, 0.15);
}
/* Lexical 기본 선택 하이라이트 오버라이드 */
[contenteditable="true"] .PlaygroundEditorTheme__tableCellSelected {
background-color: rgba(0, 120, 212, 0.25) !important;
}
/* 셀 배경색이 설정된 경우 텍스트 색상 보정 */
[contenteditable="true"] table td[style*="background-color"],
[contenteditable="true"] table th[style*="background-color"],
.lexical-viewer table td[style*="background-color"],
.lexical-viewer table th[style*="background-color"] {
color: #1e1e1e;
}
/* 투명 배경색은 원래 텍스트 색상 유지 */
[contenteditable="true"] table td[style*="transparent"],
[contenteditable="true"] table th[style*="transparent"],
.lexical-viewer table td[style*="transparent"],
.lexical-viewer table th[style*="transparent"] {
color: #e4e4e4;
}
/* 뷰어의 테이블 */
.lexical-viewer table {
table-layout: auto;
width: 100%;
margin: 1rem auto;
}
/* 코드 블록 스타일 */
code[data-language] {
display: block !important;
position: relative;
background-color: #1e1e1e;
border: 1px solid #3e3e42;
border-radius: 6px;
padding: 3.5rem 1rem 1rem 1rem;
margin: 1rem 0;
overflow-x: auto;
font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
font-size: 13px;
line-height: 1.5;
color: #e4e4e4;
}
/* CSS로 헤더 배경 생성 */
code[data-language]::before {
content: attr(data-language-label);
position: absolute;
top: 0;
left: 0;
right: 0;
background-color: #2d2d30;
border-bottom: 1px solid #3e3e42;
border-radius: 6px 6px 0 0;
padding: 0.5rem 1rem;
font-size: 12px;
font-weight: 600;
color: #e4e4e4;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
line-height: 1;
}
/* 플로팅 복사 버튼 */
.floating-copy-btn {
position: absolute;
top: 0.5rem;
right: 1rem;
padding: 0.25rem 0.5rem;
background: #3e3e42;
color: #e4e4e4;
border: 1px solid #4e4e52;
border-radius: 4px;
font-size: 16px;
cursor: pointer;
transition: all 0.2s;
z-index: 200;
line-height: 1;
}
.floating-copy-btn:hover {
background: #4e4e52;
border-color: #5e5e62;
}
/* Prism 토큰 색상 커스터마이징 (다크 테마) */
.token.comment,
.token.prolog,
.token.doctype,
.token.cdata {
color: #6a9955;
}
.token.punctuation {
color: #d4d4d4;
}
.token.property,
.token.tag,
.token.boolean,
.token.number,
.token.constant,
.token.symbol,
.token.deleted {
color: #b5cea8;
}
.token.selector,
.token.attr-name,
.token.string,
.token.char,
.token.builtin,
.token.inserted {
color: #ce9178;
}
.token.operator,
.token.entity,
.token.url,
.language-css .token.string,
.style .token.string {
color: #d4d4d4;
}
.token.atrule,
.token.attr-value,
.token.keyword {
color: #569cd6;
}
.token.function,
.token.class-name {
color: #dcdcaa;
}
.token.regex,
.token.important,
.token.variable {
color: #d16969;
}
/* 코드 블록 선택 스타일 */
[contenteditable="true"] pre::selection,
[contenteditable="true"] pre code::selection {
background-color: rgba(0, 120, 212, 0.3);
}
* { * {
@apply border-[#3e3e42]; @apply border-[#3e3e42];
} }
+105
View File
@@ -0,0 +1,105 @@
import { useEffect } from 'react';
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
const LANGUAGE_LABELS: { [key: string]: string } = {
csharp: 'C#',
javascript: 'JavaScript',
typescript: 'TypeScript',
python: 'Python',
java: 'Java',
cpp: 'C++',
c: 'C',
html: 'HTML',
css: 'CSS',
sql: 'SQL',
json: 'JSON',
markdown: 'Markdown',
bash: 'Bash',
plain: 'Plain Text',
};
export function CodeActionMenuPlugin() {
const [editor] = useLexicalComposerContext();
useEffect(() => {
const updateCodeBlocks = () => {
// 현재 포커스 저장
const activeElement = document.activeElement;
// 모든 code 요소에 data-language-label 추가
const codeBlocks = document.querySelectorAll('code[data-language]');
codeBlocks.forEach((codeBlock) => {
if (!(codeBlock instanceof HTMLElement)) return;
const style = window.getComputedStyle(codeBlock);
if (style.display !== 'block') return;
const language = codeBlock.dataset.language || 'plain';
const languageLabel = LANGUAGE_LABELS[language] || language;
// data 속성에 언어 라벨 저장 (CSS에서 사용)
codeBlock.dataset.languageLabel = languageLabel;
// 복사 버튼이 이미 있는지 확인
// const existingBtn = codeBlock.parentElement?.querySelector('.floating-copy-btn');
// if (existingBtn) return;
// // 복사 버튼 생성 (code 요소 다음에 배치)
// const copyBtn = document.createElement('button');
// copyBtn.className = 'floating-copy-btn';
// copyBtn.type = 'button';
// copyBtn.innerHTML = '📋';
// copyBtn.title = '복사';
// copyBtn.contentEditable = 'false';
// copyBtn.onclick = (e) => {
// e.preventDefault();
// e.stopPropagation();
// const code = codeBlock.textContent || '';
// navigator.clipboard.writeText(code).then(() => {
// copyBtn.innerHTML = '✓';
// copyBtn.title = '복사됨!';
// setTimeout(() => {
// copyBtn.innerHTML = '📋';
// copyBtn.title = '복사';
// }, 2000);
// }).catch(() => {
// alert('복사에 실패했습니다.');
// });
// };
// code 요소 바로 다음에 삽입
// if (codeBlock.nextSibling) {
// codeBlock.parentNode?.insertBefore(copyBtn, codeBlock.nextSibling);
// } else {
// codeBlock.parentNode?.appendChild(copyBtn);
// }
});
// 포커스 복원
if (activeElement && activeElement !== document.activeElement && activeElement instanceof HTMLElement) {
setTimeout(() => {
activeElement.focus();
}, 0);
}
};
// 초기 실행
updateCodeBlocks();
setTimeout(updateCodeBlocks, 500);
const unregister = editor.registerUpdateListener(() => {
setTimeout(updateCodeBlocks, 2000);
});
// 주기적 실행 간격을 길게 (포커스 문제 방지)
const interval = setInterval(updateCodeBlocks, 10000);
return () => {
unregister();
clearInterval(interval);
};
}, [editor]);
return null;
}
+13
View File
@@ -0,0 +1,13 @@
import { useEffect } from 'react';
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
import { registerCodeHighlighting } from '@lexical/code';
export function CodeHighlightPlugin() {
const [editor] = useLexicalComposerContext();
useEffect(() => {
return registerCodeHighlighting(editor);
}, [editor]);
return null;
}
+44
View File
@@ -0,0 +1,44 @@
import { useEffect } from 'react';
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
export function CodeLanguagePlugin() {
const [editor] = useLexicalComposerContext();
useEffect(() => {
// Update data-language attribute on code blocks
const updateCodeLanguages = () => {
editor.getEditorState().read(() => {
const codeBlocks = document.querySelectorAll('[contenteditable="true"] pre, .lexical-viewer pre');
codeBlocks.forEach((block) => {
if (block instanceof HTMLElement) {
// Get the language from the CodeNode if available
const codeElement = block.querySelector('code');
if (codeElement && codeElement.classList.length > 0) {
const languageClass = Array.from(codeElement.classList).find(cls => cls.startsWith('language-'));
if (languageClass) {
const language = languageClass.replace('language-', '');
block.setAttribute('data-language', language);
} else if (!block.hasAttribute('data-language')) {
block.setAttribute('data-language', 'plain text');
}
} else if (!block.hasAttribute('data-language')) {
block.setAttribute('data-language', 'plain text');
}
}
});
});
};
// Initial update
setTimeout(updateCodeLanguages, 100);
// Update on editor changes
const unregister = editor.registerUpdateListener(() => {
setTimeout(updateCodeLanguages, 50);
});
return unregister;
}, [editor]);
return null;
}
+124 -7
View File
@@ -14,9 +14,13 @@ import { CodeNode, CodeHighlightNode } from '@lexical/code';
import { LinkNode, AutoLinkNode } from '@lexical/link'; import { LinkNode, AutoLinkNode } from '@lexical/link';
import { TableNode, TableCellNode, TableRowNode } from '@lexical/table'; import { TableNode, TableCellNode, TableRowNode } from '@lexical/table';
import { TablePlugin } from '@lexical/react/LexicalTablePlugin'; 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 type { EditorState } from 'lexical';
import { $getRoot, $createParagraphNode, $createTextNode, FORMAT_TEXT_COMMAND, FORMAT_ELEMENT_COMMAND, $getSelection, $isRangeSelection, TextNode } from 'lexical'; import { $getRoot, $createParagraphNode, $createTextNode, FORMAT_TEXT_COMMAND, FORMAT_ELEMENT_COMMAND, $getSelection, $isRangeSelection, TextNode, type LexicalNode } from 'lexical';
import { INSERT_TABLE_COMMAND } from '@lexical/table'; import { INSERT_TABLE_COMMAND, $isTableCellNode } from '@lexical/table';
import { $createHeadingNode } from '@lexical/rich-text'; import { $createHeadingNode } from '@lexical/rich-text';
import { INSERT_UNORDERED_LIST_COMMAND, INSERT_ORDERED_LIST_COMMAND } from '@lexical/list'; import { INSERT_UNORDERED_LIST_COMMAND, INSERT_ORDERED_LIST_COMMAND } from '@lexical/list';
import { $createCodeNode } from '@lexical/code'; import { $createCodeNode } from '@lexical/code';
@@ -40,11 +44,46 @@ const editorTheme = {
underline: 'underline', underline: 'underline',
code: 'bg-[#1e1e1e] px-1.5 py-0.5 rounded font-mono text-sm text-[#4db8ff]', 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', 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', link: 'text-[#4db8ff] hover:text-[#8cd7ff] underline cursor-pointer',
table: 'border-collapse table-auto w-full my-4', table: 'border-collapse w-full my-4',
tableCell: 'border border-[#3e3e42] px-3 py-2 text-[#e4e4e4] min-w-[100px]', 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]', 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 { interface LexicalEditorProps {
@@ -77,6 +116,23 @@ const FONT_SIZES = [
{ name: '48px', value: '48px' }, { 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 }) { function OnChangePluginWrapper({ onChange }: { onChange: (content: string) => void }) {
const handleChange = (editorState: EditorState) => { const handleChange = (editorState: EditorState) => {
// Serialize the entire editor state as JSON to preserve formatting // Serialize the entire editor state as JSON to preserve formatting
@@ -182,6 +238,7 @@ function ToolbarPlugin({ fontFamily, setFontFamily, fontSize, setFontSize }: Too
const [editor] = useLexicalComposerContext(); const [editor] = useLexicalComposerContext();
const [showTablePicker, setShowTablePicker] = useState(false); const [showTablePicker, setShowTablePicker] = useState(false);
const [tableSize, setTableSize] = useState({ rows: 0, cols: 0 }); const [tableSize, setTableSize] = useState({ rows: 0, cols: 0 });
const [showColorPicker, setShowColorPicker] = useState(false);
const handleFontChange = (e: React.ChangeEvent<HTMLSelectElement>) => { const handleFontChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
const newFont = e.target.value; const newFont = e.target.value;
@@ -446,6 +503,28 @@ function ToolbarPlugin({ fontFamily, setFontFamily, fontSize, setFontSize }: Too
setTableSize({ rows: 0, cols: 0 }); 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 ( return (
<div className="flex flex-wrap gap-1 p-2 bg-[#252526] border border-[#3e3e42] rounded-t mb-[-1px] relative z-10"> <div className="flex flex-wrap gap-1 p-2 bg-[#252526] border border-[#3e3e42] rounded-t mb-[-1px] relative z-10">
{/* Font Family */} {/* Font Family */}
@@ -628,6 +707,40 @@ function ToolbarPlugin({ fontFamily, setFontFamily, fontSize, setFontSize }: Too
)} )}
</div> </div>
{/* Cell Background Color */}
<div className="relative">
<button
onClick={() => setShowColorPicker(!showColorPicker)}
className="px-3 py-1.5 text-sm bg-[#2d2d30] hover:bg-[#3e3e42] text-[#e4e4e4] rounded transition-colors"
title="셀 배경색 (셀을 선택하세요)"
type="button"
>
🎨
</button>
{showColorPicker && (
<div className="absolute top-full left-0 mt-1 p-3 bg-[#252526] border border-[#3e3e42] rounded shadow-lg z-20 min-w-[200px]">
<div className="text-xs text-[#9d9d9d] mb-2">셀 배경색</div>
<div className="grid grid-cols-3 gap-2">
{CELL_COLORS.map((color) => (
<button
key={color.value}
onClick={() => setCellBackgroundColor(color.value)}
className="px-2 py-1.5 text-xs rounded hover:bg-[#3e3e42] transition-colors text-left"
style={{ backgroundColor: color.value === 'transparent' ? '#2d2d30' : color.value }}
title={color.name}
type="button"
>
<span className={color.value === 'transparent' ? 'text-[#e4e4e4]' : 'text-[#1e1e1e]'}>
{color.name}
</span>
</button>
))}
</div>
</div>
)}
</div>
<div className="w-px h-6 bg-[#3e3e42] mx-1 self-center"></div> <div className="w-px h-6 bg-[#3e3e42] mx-1 self-center"></div>
{/* Alignment */} {/* Alignment */}
@@ -712,7 +825,11 @@ export function LexicalEditor({ initialContent, onChange, placeholder = '내용
<HistoryPlugin /> <HistoryPlugin />
<ListPlugin /> <ListPlugin />
<LinkPlugin /> <LinkPlugin />
<TablePlugin /> <TablePlugin hasCellMerge={true} hasCellBackgroundColor={true} />
<TableResizerPlugin />
<CodeHighlightPlugin />
<CodeActionMenuPlugin />
<CodeLanguagePlugin />
<OnChangePluginWrapper onChange={onChange} /> <OnChangePluginWrapper onChange={onChange} />
<InitialContentPlugin content={initialContent} /> <InitialContentPlugin content={initialContent} />
<HeadingIdPlugin /> <HeadingIdPlugin />
+43 -1
View File
@@ -7,6 +7,9 @@ import { LexicalErrorBoundary } from '@lexical/react/LexicalErrorBoundary';
import { HeadingNode, QuoteNode } from '@lexical/rich-text'; import { HeadingNode, QuoteNode } from '@lexical/rich-text';
import { ListNode, ListItemNode } from '@lexical/list'; import { ListNode, ListItemNode } from '@lexical/list';
import { CodeNode, CodeHighlightNode } from '@lexical/code'; import { CodeNode, CodeHighlightNode } from '@lexical/code';
import { registerCodeHighlighting } from '@lexical/code';
import { CodeLanguagePlugin } from './CodeLanguagePlugin';
import { CodeActionMenuPlugin } from './CodeActionMenuPlugin';
import { LinkNode, AutoLinkNode } from '@lexical/link'; import { LinkNode, AutoLinkNode } from '@lexical/link';
import { TableNode, TableCellNode, TableRowNode } from '@lexical/table'; import { TableNode, TableCellNode, TableRowNode } from '@lexical/table';
import { $getRoot, $createParagraphNode, $createTextNode } from 'lexical'; import { $getRoot, $createParagraphNode, $createTextNode } from 'lexical';
@@ -29,7 +32,39 @@ const viewerTheme = {
underline: 'underline', underline: 'underline',
code: 'bg-[#1e1e1e] px-1.5 py-0.5 rounded font-mono text-sm text-[#4db8ff]', 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-4 block overflow-x-auto', code: 'relative bg-[#1e1e1e] border border-[#3e3e42] rounded-md font-mono text-sm mb-4 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', link: 'text-[#4db8ff] hover:text-[#8cd7ff] underline cursor-pointer',
table: 'border-collapse table-auto w-full my-4', table: 'border-collapse table-auto w-full my-4',
tableCell: 'border border-[#3e3e42] px-3 py-2 text-[#e4e4e4] min-w-[100px]', tableCell: 'border border-[#3e3e42] px-3 py-2 text-[#e4e4e4] min-w-[100px]',
@@ -81,6 +116,11 @@ function HeadingIdPlugin() {
function ContentPlugin({ content }: { content: string }) { function ContentPlugin({ content }: { content: string }) {
const [editor] = useLexicalComposerContext(); const [editor] = useLexicalComposerContext();
useEffect(() => {
// Register code highlighting
return registerCodeHighlighting(editor);
}, [editor]);
useEffect(() => { useEffect(() => {
try { try {
// Try to parse as JSON first (new format with formatting) // Try to parse as JSON first (new format with formatting)
@@ -153,6 +193,8 @@ export function LexicalViewer({ content }: LexicalViewerProps) {
/> />
<ContentPlugin content={content} /> <ContentPlugin content={content} />
<HeadingIdPlugin /> <HeadingIdPlugin />
<CodeLanguagePlugin />
<CodeActionMenuPlugin />
</LexicalComposer> </LexicalComposer>
</div> </div>
); );
+123
View File
@@ -0,0 +1,123 @@
import { useEffect, useRef } from 'react';
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
export function TableResizerPlugin() {
const [editor] = useLexicalComposerContext();
const isResizingCell = useRef(false);
const isResizingTable = useRef(false);
const currentCell = useRef<HTMLTableCellElement | null>(null);
const currentTable = useRef<HTMLTableElement | null>(null);
const startX = useRef(0);
const startWidth = useRef(0);
const originalWidths = useRef<number[]>([]);
useEffect(() => {
const editorElement = editor.getRootElement();
if (!editorElement) return;
const handleMouseDown = (e: MouseEvent) => {
const target = e.target as HTMLElement;
const cell = target.closest('td, th') as HTMLTableCellElement;
if (!cell) return;
const table = cell.closest('table') as HTMLTableElement;
if (!table) return;
const rect = cell.getBoundingClientRect();
const isNearRightEdge = e.clientX > rect.right - 6;
if (!isNearRightEdge) return;
// 현재 행의 모든 셀 가져오기
const row = cell.parentElement as HTMLTableRowElement;
const cells = Array.from(row.cells);
const cellIndex = cells.indexOf(cell);
const isLastCell = cellIndex === cells.length - 1;
if (isLastCell) {
// 마지막 셀: 표 전체 크기 조정 (왼쪽으로만)
e.preventDefault();
isResizingTable.current = true;
currentTable.current = table;
startX.current = e.clientX;
startWidth.current = table.offsetWidth;
// 모든 열의 현재 너비 저장 (비율 유지용)
const firstRow = table.rows[0];
originalWidths.current = Array.from(firstRow.cells).map(c => c.offsetWidth);
document.body.style.cursor = 'col-resize';
document.body.style.userSelect = 'none';
} else {
// 일반 셀: 개별 열 크기 조정
e.preventDefault();
isResizingCell.current = true;
currentCell.current = cell;
startX.current = e.clientX;
startWidth.current = cell.offsetWidth;
document.body.style.cursor = 'col-resize';
document.body.style.userSelect = 'none';
}
};
const handleMouseMove = (e: MouseEvent) => {
if (isResizingTable.current && currentTable.current) {
// 표 전체 크기 조정 (왼쪽으로만)
const diff = e.clientX - startX.current;
// 오른쪽으로 늘리기 방지 (diff > 0이면 오른쪽)
if (diff > 0) return;
const newTableWidth = Math.max(300, startWidth.current + diff); // 최소 300px
const scale = newTableWidth / startWidth.current;
// 표 너비 설정
currentTable.current.style.width = `${newTableWidth}px`;
currentTable.current.style.margin = '0 auto'; // 가운데 정렬
// 모든 행의 셀 너비를 비율에 맞게 조정
Array.from(currentTable.current.rows).forEach(row => {
Array.from(row.cells).forEach((cell, idx) => {
const originalWidth = originalWidths.current[idx];
const newWidth = originalWidth * scale;
cell.style.width = `${newWidth}px`;
cell.style.minWidth = `${newWidth}px`;
});
});
} else if (isResizingCell.current && currentCell.current) {
// 개별 셀 크기 조정
const diff = e.clientX - startX.current;
const newWidth = Math.max(50, startWidth.current + diff);
currentCell.current.style.width = `${newWidth}px`;
currentCell.current.style.minWidth = `${newWidth}px`;
}
};
const handleMouseUp = () => {
if (isResizingCell.current || isResizingTable.current) {
isResizingCell.current = false;
isResizingTable.current = false;
currentCell.current = null;
currentTable.current = null;
originalWidths.current = [];
document.body.style.cursor = '';
document.body.style.userSelect = '';
}
};
editorElement.addEventListener('mousedown', handleMouseDown);
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mouseup', handleMouseUp);
return () => {
editorElement.removeEventListener('mousedown', handleMouseDown);
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mouseup', handleMouseUp);
};
}, [editor]);
return null;
}