diff --git a/src/components/kri-editor/KriEditor.tsx b/src/components/kri-editor/KriEditor.tsx index 70cd21b..5c90c0a 100644 --- a/src/components/kri-editor/KriEditor.tsx +++ b/src/components/kri-editor/KriEditor.tsx @@ -3,6 +3,7 @@ import type { KriEditorProps, KriEditorMode } from "./types"; import { KriEditorHtmlOnly } from "./KriEditorHtmlOnly"; import { KriEditorWysiwyg } from "./KriEditorWysiwyg"; +import {KriEditorSms} from "./KriEditorSms"; function resolveMode(mode?: KriEditorMode, editorMode?: KriEditorMode): KriEditorMode { return mode ?? editorMode ?? "wysiwyg"; @@ -15,5 +16,9 @@ export function KriEditor(props: KriEditorProps) { return ; } + if(mode === "sms") { + return + } + return ; } diff --git a/src/components/kri-editor/KriEditorHtmlOnly.tsx b/src/components/kri-editor/KriEditorHtmlOnly.tsx index 64f77cc..21f4785 100644 --- a/src/components/kri-editor/KriEditorHtmlOnly.tsx +++ b/src/components/kri-editor/KriEditorHtmlOnly.tsx @@ -1,13 +1,15 @@ "use client"; import * as React from "react"; -import { cn } from "@/lib/utils"; +import { toast } from "sonner"; + import type { KriEditorProps } from "./types"; +import { cn } from "./utils/cn"; +import { compressImage } from "./utils/imageCompression"; import { useDebouncedChange } from "./hooks/useDebouncedChange"; import { sanitizeHtmlForPreview } from "./utils/sanitizeHtml"; import {useCallback} from "react"; -import {toast} from "sonner"; -import {compressImage} from "@/components/kri-editor/utils/imageCompression"; +import { useTextareaInsert } from "./hooks/useTextareaInsert"; type HtmlOnlyProps = Omit & { mode: "html"; @@ -38,19 +40,11 @@ export function KriEditorHtmlOnly(props: HtmlOnlyProps) { const textareaRef = React.useRef(null); const fileRef = React.useRef(null); const latestHtmlRef = React.useRef(html); - latestHtmlRef.current = html; const canImageUpload = Boolean(onImageUpload); const { scheduleChange, flushChange } = useDebouncedChange(onChange, debounceMs); - - // 외부 value 변경 시 동기화 - React.useEffect(() => { - if ((value || "") !== latestHtmlRef.current) { - setHtml(value || ""); - latestHtmlRef.current = value || ""; - } - }, [value]); + const ti = useTextareaInsert(textareaRef); const handleTextChange = (e: React.ChangeEvent) => { const next = e.target.value; @@ -156,6 +150,46 @@ export function KriEditorHtmlOnly(props: HtmlOnlyProps) { [html], ); + // 외부 value 변경 시 동기화 + React.useEffect(() => { + if ((value || "") !== latestHtmlRef.current) { + setHtml(value || ""); + latestHtmlRef.current = value || ""; + } + }, [value]); + + React.useEffect(() => { + if (textareaRef.current && props.onEditorReady) { + props.onEditorReady(textareaRef.current); + } + },[props.onEditorReady]) + + React.useEffect(() => { + if (!props.onCommandReady) return; + + props.onCommandReady({ + focus: () => textareaRef.current?.focus(), + insertText: (placeholder: string) => { + const current = latestHtmlRef.current ?? ""; + + ti.insertText( + placeholder, + current, + (next) => { + setHtml(next); + latestHtmlRef.current = next; + }, + (next) => { + // html 모드도 debounce 쓰면 flush 권장 + flushChange(next); + }, + ); + }, + }); + + return () => props.onCommandReady?.(null); + }, [props.onCommandReady, ti, flushChange]); + return ( {label && ( @@ -186,6 +220,7 @@ export function KriEditorHtmlOnly(props: HtmlOnlyProps) { onBlur={handleBlur} placeholder={placeholder} rows={rows} + {...ti.bindSelectionHandlers} /> & { + mode: "sms"; +}; + +export function KriEditorSms(props: SmsEditorProps) { + const { + label, + value, + onChange, + placeholder = "문자 내용을 입력하세요...", + className, + debounceMs = 350, + smsTitle = "", + changeSmsType, + onEditorReady, + } = props; + + const [text, setText] = React.useState(value || ""); + const [byteSize, setByteSize] = React.useState(0); + const textareaRef = React.useRef(null); + const latestTextRef = React.useRef(text); + const lastTypeRef = React.useRef<"SMS" | "LMS" | null>(null); + + const { scheduleChange, flushChange } = useDebouncedChange(onChange, debounceMs); + const ti = useTextareaInsert(textareaRef); + + // 한글은 2byte, 영문/숫자/특수문자는 1byte로 계산 + const calculateBytes = React.useCallback((str: string): number => { + let bytes = 0; + for (let i = 0; i < str.length; i++) { + const char = str.charAt(i); + if (escape(char).length > 4) { + bytes += 2; + } else { + bytes += 1; + } + } + return bytes; + }, []); + + const hasTitle = (smsTitle?.length ?? 0) > 0; + const messageType: "SMS" | "LMS" = (byteSize > 90 || hasTitle) ? "LMS" : "SMS"; + const maxBytes = messageType === "LMS" ? 2000 : 90; + const messageTypeColor = messageType === "LMS" ? 'bg-blue-500' : 'bg-red-500'; + + const handleTextChange = (e: React.ChangeEvent) => { + const next = e.target.value; + const bytes = calculateBytes(next); + + // 최대 바이트 초과 방지 + if (bytes > 2000) { + return; + } + + setText(next); + setByteSize(bytes); + latestTextRef.current = next; + scheduleChange(next); + }; + + const handleBlur = () => { + flushChange(latestTextRef.current); + }; + + // 외부 value 변경 시 동기화 + React.useEffect(() => { + if ((value || "") !== latestTextRef.current) { + const newText = value || ""; + setText(newText); + setByteSize(calculateBytes(newText)); + latestTextRef.current = newText; + } + }, [value, calculateBytes]); + + // 바이트 계산 초기화 + React.useEffect(() => { + setByteSize(calculateBytes(text)); + }, [text, calculateBytes]); + + React.useEffect(() => { + if (!changeSmsType) return; + if (lastTypeRef.current === messageType) return; + + lastTypeRef.current = messageType; + changeSmsType(messageType); + }, [messageType, changeSmsType]); + + // onEditorReady 콜백 + React.useEffect(() => { + if (textareaRef.current && onEditorReady) { + onEditorReady(textareaRef.current); + } + }, [onEditorReady]); + + React.useEffect(() => { + if (!props.onCommandReady) return; + + props.onCommandReady({ + focus: () => textareaRef.current?.focus(), + insertText: (placeholder: string) => { + const current = latestTextRef.current ?? ""; + + ti.insertText( + placeholder, + current, + (next) => { + // 로컬 반영 + setText(next); + setByteSize(calculateBytes(next)); + latestTextRef.current = next; + }, + (next) => { + // 부모 반영(즉시) - debounce를 이기기 위해 flush 권장 + flushChange(next); + }, + ); + }, + }); + + return () => props.onCommandReady?.(null); + }, [props.onCommandReady, ti, calculateBytes, flushChange]); + + return ( + + {label && ( + + {label} + + )} + + {/* 휴대전화 디자인 */} + + {/* 상단 노치 */} + + + {/* 스크린 영역 */} + + {/* 헤더 - 바이트 및 타입 표시 */} + + + {byteSize}/{maxBytes}byte + + + {messageType} + + + + {/* 메시지 본문 (textarea) */} + + {/* LMS 제목 */} + {smsTitle && ( + + + {smsTitle} + + + )} + + {/* Textarea - 에디터 */} + + + + {/* 바이트 초과 경고 */} + {byteSize > maxBytes && ( + + + ⚠️ 최대 용량 초과 ({byteSize - maxBytes}byte) + + + )} + + + {/* 하단 홈 버튼 */} + + + + ); +}; \ No newline at end of file diff --git a/src/components/kri-editor/KriEditorWysiwyg.tsx b/src/components/kri-editor/KriEditorWysiwyg.tsx index 4183ffb..968dd22 100644 --- a/src/components/kri-editor/KriEditorWysiwyg.tsx +++ b/src/components/kri-editor/KriEditorWysiwyg.tsx @@ -18,15 +18,16 @@ import TableHeader from "@tiptap/extension-table-header"; import TableCell from "@tiptap/extension-table-cell"; import { toast } from "sonner"; -import { cn } from "@/lib/utils"; import type { KriEditorProps, KriEditorMode, ToolbarState } from "./types"; import { FontSize } from "./extensions/font-size"; import { Div } from "./extensions/div"; +import { cn } from "./utils/cn"; import { compressImage } from "./utils/imageCompression"; import { sanitizeHtml } from "./utils/sanitizeHtml"; import { Toolbar } from "./toolbar/Toolbar"; import { useDebouncedChange } from "./hooks/useDebouncedChange"; +import { useTextareaInsert } from "./hooks/useTextareaInsert"; type ViewMode = "wysiwyg" | "html"; @@ -65,6 +66,7 @@ function getToolbarState(editor: Editor): ToolbarState { export function KriEditorWysiwyg(props: KriEditorProps) { const { + label, value, onChange, @@ -91,7 +93,6 @@ export function KriEditorWysiwyg(props: KriEditorProps) { } = props; const mode = resolveMode(modeProp, editorMode); - const isLmsMode = mode === "lms"; const showHtmlToggle = mode === "both"; const LINK_HTML_ATTRS = { @@ -102,9 +103,13 @@ export function KriEditorWysiwyg(props: KriEditorProps) { const { scheduleChange, flushChange, optimisticHtmlRef } = useDebouncedChange(onChange, debounceMs); const fileRef = useRef(null); + const htmlTextareaRef = useRef(null); + const htmlTi = useTextareaInsert(htmlTextareaRef); const [view, setView] = useState("wysiwyg"); + const [wysiwygKey, setWysiwygKey] = useState(0); const viewRef = useRef("wysiwyg"); + useEffect(() => { viewRef.current = view; }, [view]); @@ -133,26 +138,12 @@ export function KriEditorWysiwyg(props: KriEditorProps) { immediatelyRender: false, extensions: [ - isLmsMode - ? StarterKit.configure({ - heading: false, - bulletList: false, - orderedList: false, - listItem: false, - blockquote: false, - codeBlock: false, - code: false, - strike: false, - bold: false, - italic: false, - horizontalRule: false, - }) - : StarterKit.configure({ - heading: false, - blockquote: false, - codeBlock: false, - code: false, - }), + StarterKit.configure({ + heading: false, + blockquote: false, + codeBlock: false, + code: false, + }), Underline, TextStyle, @@ -183,6 +174,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) { allowBase64, HTMLAttributes: { class: "max-w-full h-auto", + "data-kri-image": "true", }, resize: { enabled: true, @@ -259,52 +251,11 @@ export function KriEditorWysiwyg(props: KriEditorProps) { }, }, }, - }); + },[wysiwygKey]); useEffect(() => { - if (!editor) return; - - const sync = () => { - selectionRef.current = { from: editor.state.selection.from, to: editor.state.selection.to }; - setTb(getToolbarState(editor)); - }; - - sync(); - editor.on("selectionUpdate", sync); - editor.on("transaction", sync); - - return () => { - editor.off("selectionUpdate", sync); - editor.off("transaction", sync); - }; - }, [editor]); - - useEffect(() => { - if (!editor) return; - if (viewRef.current === "html") return; - - const current = editor.getHTML(); - if (value != null && value !== current && value !== optimisticHtmlRef.current) { - editor.commands.setContent(value, { - emitUpdate: false, - parseOptions: { preserveWhitespace: "full" }, - }); - } - }, [value, editor, optimisticHtmlRef]); - - useEffect(() => { - if (!editor) return; - - const onBlur = () => { - if (viewRef.current === "html") flushChange(htmlDraftRef.current); - else flushChange(editor.getHTML()); - }; - - editor.on("blur", onBlur); - return () => { - editor.off("blur", onBlur); - }; - }, [editor, flushChange]); + console.log(wysiwygKey) + }, [wysiwygKey]); const restoreSelection = useCallback(() => { if (!editor) return; @@ -504,6 +455,118 @@ const normalizeLinkUrl = (raw: string): string => { setView("wysiwyg"); }, [editor, flushChange, sanitizeHtmlOpt]); + useEffect(() => { + if (!editor) return; + + const sync = () => { + selectionRef.current = { from: editor.state.selection.from, to: editor.state.selection.to }; + setTb(getToolbarState(editor)); + }; + + sync(); + editor.on("selectionUpdate", sync); + editor.on("transaction", sync); + + return () => { + editor.off("selectionUpdate", sync); + editor.off("transaction", sync); + }; + }, [editor]); + + useEffect(() => { + if (!props.onEditorReady || !editor) return; + + if (viewRef.current === "html") { + props.onEditorReady(htmlTextareaRef.current); + } else { + props.onEditorReady(editor); + } + }, [editor, view, props.onEditorReady]); + + useEffect(() => { + if (!editor) return; + if (viewRef.current === "html") return; + if (value == null) return; + + const current = editor.getHTML(); + + if (value !== current && value !== optimisticHtmlRef.current) { + // 이미지가 포함된 HTML 업데이트면, 아예 editor를 새로 생성 + editor.commands.setContent(value, { + emitUpdate: false, + parseOptions: {preserveWhitespace: "full"}, + }); + } + }, [value, editor, view]); + + useEffect(() => { + if (value.includes(" k + 1); + return; + } + }, [value]); + + useEffect(() => { + if (!editor) return; + + const onBlur = () => { + if (viewRef.current === "html") flushChange(htmlDraftRef.current); + else flushChange(editor.getHTML()); + }; + + editor.on("blur", onBlur); + return () => { + editor.off("blur", onBlur); + }; + }, [editor, flushChange]); + + useEffect(() => { + if (!props.onCommandReady) return; + + // editor가 아직 없으면 null 전달 + if (!editor) { + props.onCommandReady(null); + return; + } + + props.onCommandReady({ + focus: () => { + if (viewRef.current === "html") htmlTextareaRef.current?.focus(); + else editor.chain().focus().run(); + }, + + insertText: (placeholder: string) => { + // 1) HTML textarea 모드 + if (viewRef.current === "html") { + const current = htmlDraftRef.current ?? ""; + + htmlTi.insertText( + placeholder, + current, + (next) => { + htmlDraftRef.current = next; + // uncontrolled textarea이므로 DOM value를 직접 갱신 + if (htmlTextareaRef.current) htmlTextareaRef.current.value = next; + }, + (next) => { + // 삽입은 즉시 커밋(저장 버튼 클릭 직후 반영 누락 방지) + flushChange(next); + } + ); + + return; + } + + // 2) WYSIWYG(tiptap) 모드 + restoreSelection(); + editor.chain().focus().insertContent(placeholder).run(); + flushChange(editor.getHTML()); + }, + }); + + return () => props.onCommandReady?.(null); + }, [editor, props.onCommandReady, restoreSelection, flushChange, htmlTi]); + const previewHtml = useMemo(() => { const raw = optimisticHtmlRef.current || ""; return sanitizeHtmlOpt ? sanitizeHtml(raw) : raw; @@ -532,7 +595,6 @@ const normalizeLinkUrl = (raw: string): string => { showHtmlToggle={showHtmlToggle} isHtmlView={view === "html"} onToggleHtmlView={onToggleHtmlView} - isLmsMode={isLmsMode} onSetFontSize={setFontSize} onSetTextColor={setTextColor} onUnsetTextColor={unsetTextColor} @@ -553,6 +615,7 @@ const normalizeLinkUrl = (raw: string): string => { ) : ( e.stopPropagation()} @@ -562,6 +625,7 @@ const normalizeLinkUrl = (raw: string): string => { }} onBlur={() => flushChange(htmlDraftRef.current)} placeholder={placeholder} + {...htmlTi.bindSelectionHandlers} /> )} diff --git a/src/components/kri-editor/hooks/useTextareaInsert.ts b/src/components/kri-editor/hooks/useTextareaInsert.ts new file mode 100644 index 0000000..a203c86 --- /dev/null +++ b/src/components/kri-editor/hooks/useTextareaInsert.ts @@ -0,0 +1,61 @@ +import * as React from "react"; + +type Selection = { start: number; end: number }; + +export function useTextareaInsert(textareaRef: React.RefObject) { + const selectionRef = React.useRef({start: 0, end: 0}); + + const saveSelection = React.useCallback(() => { + const el = textareaRef.current; + if (!el) return; + selectionRef.current = { + start: el.selectionStart ?? 0, + end: el.selectionEnd ?? 0, + }; + }, [textareaRef]); + + const bindSelectionHandlers = React.useMemo( + () => ({ + onSelect: saveSelection, + onKeyUp: saveSelection, + onMouseUp: saveSelection, + onClick: saveSelection, + onFocus: saveSelection, + }), + [saveSelection], + ); + + /** + * 실제 삽입/치환 로직 (컴포넌트에서 currentText를 제공해야 함) + * - apply(nextText): 로컬 state 반영 + latestRef 반영 + * - commit(nextText): 부모 onChange 즉시 반영(가능하면 flushChange 사용 권장) + */ + const insertText = React.useCallback( + (placeholder: string, currentText: string, apply: (next: string) => void, commit?: (next: string) => void) => { + const {start, end} = selectionRef.current; + + const next = currentText.slice(0, start) + placeholder + currentText.slice(end); + const nextPos = start + placeholder.length; + + apply(next); + commit?.(next); + + // 렌더 반영 후 커서 복원 + requestAnimationFrame(() => { + const el = textareaRef.current; + if (!el) return; + el.focus(); + el.setSelectionRange(nextPos, nextPos); + selectionRef.current = {start: nextPos, end: nextPos}; + }); + }, + [textareaRef], + ); + + return { + selectionRef, + saveSelection, + bindSelectionHandlers, + insertText, + }; +} \ No newline at end of file diff --git a/src/components/kri-editor/index.ts b/src/components/kri-editor/index.ts index 3f8a4c7..bf328f3 100644 --- a/src/components/kri-editor/index.ts +++ b/src/components/kri-editor/index.ts @@ -1,2 +1,2 @@ export { KriEditor } from "./KriEditor"; -export type { KriEditorProps, KriEditorMode, UploadResult, ToolbarState } from "./types"; +export type { KriEditorProps, KriEditorMode, UploadResult, ToolbarState, KriEditorCommand } from "./types"; diff --git a/src/components/kri-editor/toolbar/Toolbar.tsx b/src/components/kri-editor/toolbar/Toolbar.tsx index 2314c78..11774b2 100644 --- a/src/components/kri-editor/toolbar/Toolbar.tsx +++ b/src/components/kri-editor/toolbar/Toolbar.tsx @@ -10,7 +10,7 @@ import { DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; import { Separator } from "@/components/ui/separator"; -import { cn } from "@/lib/utils"; +import { cn } from "../utils/cn"; import { AlignCenter, AlignLeft, @@ -43,8 +43,6 @@ type Props = { isHtmlView: boolean; onToggleHtmlView: () => void; - isLmsMode: boolean; - onSetFontSize: (px: string) => void; onSetTextColor: (hex: string) => void; @@ -97,7 +95,6 @@ export function Toolbar({ showHtmlToggle, isHtmlView, onToggleHtmlView, - isLmsMode, onSetFontSize, onSetTextColor, onUnsetTextColor, @@ -109,16 +106,6 @@ export function Toolbar({ onAddColumn, onDeleteTable, }: Props) { - if (isLmsMode) { - return ( - - - - - - ); - } - return ( void; + insertText: (text: string) => void; // placeholder/merge-field 삽입 +}; export type KriEditorProps = { + onEditorReady?: (editor: Editor | HTMLTextAreaElement | null) => void; + + onCommandReady?: (cmd: KriEditorCommand | null) => void; + label?: string; value: string; @@ -19,7 +30,7 @@ export type KriEditorProps = { * - "wysiwyg": WYSIWYG 전용 * - "html": HTML 전용 * - "both": 툴바에서 WYSIWYG / HTML 전환 가능 - * - "lms": LMS 문자 전용 (링크만) + * - "sms": SMS 문자 전용 (링크만) * * props.mode 가 없으면 editorMode 를 참고하고, * 둘 다 없으면 "wysiwyg" 으로 동작. @@ -51,6 +62,10 @@ export type KriEditorProps = { // onChange 디바운스 시간 (ms) debounceMs?: number; + + // SMS 모드 전용 props + smsTitle?: string; // LMS 제목용 + changeSmsType?: (type: "SMS" | "LMS") => void; }; export type ToolbarState = { diff --git a/src/components/kri-editor/utils/cn.ts b/src/components/kri-editor/utils/cn.ts new file mode 100644 index 0000000..8843ac4 --- /dev/null +++ b/src/components/kri-editor/utils/cn.ts @@ -0,0 +1,3 @@ +export function cn(...inputs: Array) { + return inputs.filter(Boolean).join(" "); +} \ No newline at end of file diff --git a/src/components/kri-editor/utils/editorTypeGuards.ts b/src/components/kri-editor/utils/editorTypeGuards.ts new file mode 100644 index 0000000..cbff821 --- /dev/null +++ b/src/components/kri-editor/utils/editorTypeGuards.ts @@ -0,0 +1,9 @@ +import type { Editor } from '@tiptap/react'; + +export function isTipTapEditor(editor: any): editor is Editor { + return editor && typeof editor.chain === 'function'; +} + +export function isTextAreaElement(element: any): element is HTMLTextAreaElement { + return element instanceof HTMLTextAreaElement; +} \ No newline at end of file
+ ⚠️ 최대 용량 초과 ({byteSize - maxBytes}byte) +