From b0140fbafbe6428301c230c5362f9cc55336c57d Mon Sep 17 00:00:00 2001 From: Dahyeon Park Date: Fri, 7 Nov 2025 09:16:21 +0900 Subject: [PATCH] . --- package-lock.json | 8 + package.json | 2 + src/index.css | 280 ++++++++++++++++++++++++++++ src/shared/CodeActionMenuPlugin.tsx | 105 +++++++++++ src/shared/CodeHighlightPlugin.tsx | 13 ++ src/shared/CodeLanguagePlugin.tsx | 44 +++++ src/shared/LexicalEditor.tsx | 131 ++++++++++++- src/shared/LexicalViewer.tsx | 44 ++++- src/shared/TableResizerPlugin.tsx | 123 ++++++++++++ 9 files changed, 742 insertions(+), 8 deletions(-) create mode 100644 src/shared/CodeActionMenuPlugin.tsx create mode 100644 src/shared/CodeHighlightPlugin.tsx create mode 100644 src/shared/CodeLanguagePlugin.tsx create mode 100644 src/shared/TableResizerPlugin.tsx diff --git a/package-lock.json b/package-lock.json index 30e5eba..a71ea9a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -21,7 +21,9 @@ "@radix-ui/react-icons": "^1.3.2", "@radix-ui/react-label": "^2.1.8", "@tanstack/react-query": "^5.90.7", + "@types/prismjs": "^1.26.5", "lexical": "^0.38.2", + "prismjs": "^1.30.0", "react": "^19.1.1", "react-dom": "^19.1.1", "react-router-dom": "^7.9.5" @@ -2542,6 +2544,12 @@ "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": { "version": "19.2.2", "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.2.tgz", diff --git a/package.json b/package.json index 21663e1..617de79 100644 --- a/package.json +++ b/package.json @@ -23,7 +23,9 @@ "@radix-ui/react-icons": "^1.3.2", "@radix-ui/react-label": "^2.1.8", "@tanstack/react-query": "^5.90.7", + "@types/prismjs": "^1.26.5", "lexical": "^0.38.2", + "prismjs": "^1.30.0", "react": "^19.1.1", "react-dom": "^19.1.1", "react-router-dom": "^7.9.5" diff --git a/src/index.css b/src/index.css index 7d36615..b1c8236 100644 --- a/src/index.css +++ b/src/index.css @@ -1,4 +1,5 @@ @import "tailwindcss"; +@import "prismjs/themes/prism-tomorrow.css"; @layer base { :root { @@ -23,6 +24,285 @@ 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]; } diff --git a/src/shared/CodeActionMenuPlugin.tsx b/src/shared/CodeActionMenuPlugin.tsx new file mode 100644 index 0000000..63a49ae --- /dev/null +++ b/src/shared/CodeActionMenuPlugin.tsx @@ -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; +} diff --git a/src/shared/CodeHighlightPlugin.tsx b/src/shared/CodeHighlightPlugin.tsx new file mode 100644 index 0000000..b739337 --- /dev/null +++ b/src/shared/CodeHighlightPlugin.tsx @@ -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; +} diff --git a/src/shared/CodeLanguagePlugin.tsx b/src/shared/CodeLanguagePlugin.tsx new file mode 100644 index 0000000..61120a2 --- /dev/null +++ b/src/shared/CodeLanguagePlugin.tsx @@ -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; +} diff --git a/src/shared/LexicalEditor.tsx b/src/shared/LexicalEditor.tsx index 68b255c..cdd62cc 100644 --- a/src/shared/LexicalEditor.tsx +++ b/src/shared/LexicalEditor.tsx @@ -14,9 +14,13 @@ 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 } from 'lexical'; -import { INSERT_TABLE_COMMAND } from '@lexical/table'; +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'; @@ -40,11 +44,46 @@ const editorTheme = { 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', + 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 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]', + 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 { @@ -77,6 +116,23 @@ const FONT_SIZES = [ { 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 @@ -182,6 +238,7 @@ function ToolbarPlugin({ fontFamily, setFontFamily, fontSize, setFontSize }: Too 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; @@ -446,6 +503,28 @@ function ToolbarPlugin({ fontFamily, setFontFamily, fontSize, setFontSize }: Too 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 */} @@ -628,6 +707,40 @@ function ToolbarPlugin({ fontFamily, setFontFamily, fontSize, setFontSize }: Too )}
+ {/* Cell Background Color */} +
+ + + {showColorPicker && ( +
+
셀 배경색
+
+ {CELL_COLORS.map((color) => ( + + ))} +
+
+ )} +
+
{/* Alignment */} @@ -712,7 +825,11 @@ export function LexicalEditor({ initialContent, onChange, placeholder = '내용 - + + + + + diff --git a/src/shared/LexicalViewer.tsx b/src/shared/LexicalViewer.tsx index 916d84c..3e12184 100644 --- a/src/shared/LexicalViewer.tsx +++ b/src/shared/LexicalViewer.tsx @@ -7,6 +7,9 @@ import { LexicalErrorBoundary } from '@lexical/react/LexicalErrorBoundary'; import { HeadingNode, QuoteNode } from '@lexical/rich-text'; import { ListNode, ListItemNode } from '@lexical/list'; 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 { TableNode, TableCellNode, TableRowNode } from '@lexical/table'; import { $getRoot, $createParagraphNode, $createTextNode } from 'lexical'; @@ -29,7 +32,39 @@ const viewerTheme = { 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-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', table: 'border-collapse table-auto w-full my-4', tableCell: 'border border-[#3e3e42] px-3 py-2 text-[#e4e4e4] min-w-[100px]', @@ -81,6 +116,11 @@ function HeadingIdPlugin() { function ContentPlugin({ content }: { content: string }) { const [editor] = useLexicalComposerContext(); + useEffect(() => { + // Register code highlighting + return registerCodeHighlighting(editor); + }, [editor]); + useEffect(() => { try { // Try to parse as JSON first (new format with formatting) @@ -153,6 +193,8 @@ export function LexicalViewer({ content }: LexicalViewerProps) { /> + + ); diff --git a/src/shared/TableResizerPlugin.tsx b/src/shared/TableResizerPlugin.tsx new file mode 100644 index 0000000..f9a0d79 --- /dev/null +++ b/src/shared/TableResizerPlugin.tsx @@ -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(null); + const currentTable = useRef(null); + const startX = useRef(0); + const startWidth = useRef(0); + const originalWidths = useRef([]); + + 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; +}