diff --git a/src/components/kri-editor/KriEditorSms.tsx b/src/components/kri-editor/KriEditorSms.tsx index be0ced7..6688e4a 100644 --- a/src/components/kri-editor/KriEditorSms.tsx +++ b/src/components/kri-editor/KriEditorSms.tsx @@ -8,10 +8,25 @@ import { useTextareaInsert } from './hooks/useTextareaInsert' type SmsEditorProps = Omit & { mode: 'sms' } +type SmsMessageType = 'SMS' | 'LMS' | 'MMS' + function calculateBytes(value: string): number { return new TextEncoder().encode(value).byteLength } +// 첨부파일이 있으면 MMS, 제목이 있거나 smsMaxBytes 이상이면 LMS, 나머지는 SMS로 미리보기 판정한다. +function getSmsMessageType(hasAttachment: boolean, byteSize: number, smsMaxBytes: number, title: string): SmsMessageType { + if (hasAttachment) return 'MMS' + if (byteSize >= smsMaxBytes || Boolean(title)) return 'LMS' + return 'SMS' +} + +function getTextareaMinHeight(hasImages: boolean, hasTitle: boolean): string { + if (hasImages) return '160px' + if (hasTitle) return '320px' + return '360px' +} + export function KriEditorSms({ label, value, @@ -34,12 +49,12 @@ export function KriEditorSms({ const [text, setText] = React.useState(value || '') const textareaRef = React.useRef(null) const latestTextRef = React.useRef(text) - const lastTypeRef = React.useRef<'SMS' | 'LMS' | 'MMS' | null>(null) + const lastTypeRef = React.useRef(null) const { scheduleChange, flushChange } = useDebouncedChange(onChange, debounceMs) const textareaInsert = useTextareaInsert(textareaRef) const previewText = smsPreviewSuffix ? `${text}\n${smsPreviewSuffix}` : text const byteSize = React.useMemo(() => calculateBytes(previewText), [previewText]) - const messageType: 'SMS' | 'LMS' | 'MMS' = smsHasAttachment ? 'MMS' : byteSize >= smsMaxBytes || Boolean(smsTitle) ? 'LMS' : 'SMS' + const messageType = getSmsMessageType(smsHasAttachment, byteSize, smsMaxBytes, smsTitle) const maxBytes = messageType === 'SMS' ? smsMaxBytes : lmsMaxBytes function getBadgeColor(): string { @@ -127,7 +142,7 @@ export function KriEditorSms({ onBlur={() => flushChange(latestTextRef.current)} placeholder={placeholder} readOnly={isSmsReadOnly} - style={{ minHeight: smsImages.length > 0 ? '160px' : smsTitle ? '320px' : '360px' }} + style={{ minHeight: getTextareaMinHeight(smsImages.length > 0, Boolean(smsTitle)) }} {...textareaInsert.bindSelectionHandlers} /> {smsPreviewSuffix ? ( diff --git a/src/components/kri-editor/KriEditorWysiwyg.tsx b/src/components/kri-editor/KriEditorWysiwyg.tsx index 80034ce..33a70a6 100644 --- a/src/components/kri-editor/KriEditorWysiwyg.tsx +++ b/src/components/kri-editor/KriEditorWysiwyg.tsx @@ -39,6 +39,58 @@ import { useImageMapOverlay } from "./hooks/useImageMapOverlay"; type ViewMode = "wysiwyg" | "html"; +type ToolbarEndSlotProps = Pick & { + editor: Editor; + command: KriEditorCommand; + view: ViewMode; +}; + +// command는 ref를 사용하는 함수 묶음이라, 렌더 중 외부 함수에 직접 넘기면 React Compiler가 +// ref 접근으로 판단한다. 별도 컴포넌트의 props로 전달해 렌더 범위를 분리한다(동작 동일). +function ToolbarEndSlot({ renderToolbarEnd, editor, command, view }: Readonly) { + return <>{renderToolbarEnd?.({ editor, command, view })}; +} + +// 주입된 정제 함수가 우선이고, 없으면 sanitizeHtml 옵션에 따라 기본 정제기를 사용한다. +function sanitizeEditorHtml( + html: string, + htmlSanitizer: KriEditorProps["htmlSanitizer"], + sanitizeEnabled: boolean, + allowedCustomHtml: KriEditorProps["allowedCustomHtml"], +): string { + if (htmlSanitizer) return htmlSanitizer(html); + if (sanitizeEnabled) return sanitizeHtml(html, allowedCustomHtml); + return html; +} + +function writeHtmlDraft( + draftRef: { current: string }, + textareaRef: { current: HTMLTextAreaElement | null }, + html: string, +): void { + draftRef.current = html; + if (textareaRef.current) textareaRef.current.value = html; +} + +// 외부에서 본문이 변경된 경우에만 기존 editor 문서를 갱신한다. +function syncEditorContent(editor: Editor, value: string, optimisticHtml: string): void { + // 빈 문자열("")은 ProseMirror 스키마상 유효한 문서가 아니라 setContent가 조용히 실패해 + // 이전 템플릿 본문이 그대로 남는 문제가 있었음 -> 빈 값은 빈 문단으로 정규화해서 비교/설정. + const normalizedValue = value || "

"; + if (normalizedValue === editor.getHTML() || normalizedValue === optimisticHtml) return; + + editor.commands.setContent(normalizedValue, { + emitUpdate: false, + parseOptions: { preserveWhitespace: "full" }, + }); + + // resize가 활성화된 TipTap 이미지 NodeView는 노드의 src 변경을 기존 DOM에 반영하지 않는다. + // editor 전체 대신 NodeView만 다시 생성해 이미지를 갱신하고 편집 포커스는 유지한다. + if (normalizedValue.includes(") { const { label, @@ -134,6 +186,9 @@ export function KriEditorWysiwyg(props: KriEditorProps) { }, [view]); const htmlDraftRef = useRef(value ?? ""); + // HTML textarea는 비제어 컴포넌트다. 렌더 중 ref를 읽지 않도록, HTML 보기로 전환하는 시점의 + // 초안을 state로 보관해 textarea가 마운트될 때의 초기값(defaultValue)으로만 사용한다. + const [htmlTextareaSeed, setHtmlTextareaSeed] = useState(value ?? ""); const canImageUpload = Boolean(onImageUpload); const selectionRef = useRef<{ from: number; to: number } | null>(null); @@ -471,6 +526,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) { if (viewRef.current === "wysiwyg") { const raw = editor.getHTML(); htmlDraftRef.current = raw; + setHtmlTextareaSeed(raw); setView("html"); // WYSIWYG에서 막 넘어온, 사용자가 직접 타이핑하지 않은 HTML이므로 @@ -492,14 +548,12 @@ export function KriEditorWysiwyg(props: KriEditorProps) { toast.message(compatibility.reason ?? "현재 HTML은 WYSIWYG로 전환할 수 없습니다."); return; } - const safe = htmlSanitizer - ? htmlSanitizer(raw) - : sanitizeHtmlOpt ? sanitizeHtml(raw, allowedCustomHtml) : raw; + const safe = sanitizeEditorHtml(raw, htmlSanitizer, sanitizeHtmlOpt, allowedCustomHtml); editor.commands.setContent(safe, { emitUpdate: false, parseOptions: { preserveWhitespace: "full" } }); flushChange(preserveEmptyParagraphs(editor.getHTML())); setView("wysiwyg"); - }, [allowedCustomHtml, editor, flushChange, getCompatibility, htmlSanitizer, sanitizeHtmlOpt]); + }, [allowedCustomHtml, editor, flushChange, getCompatibility, htmlSanitizer, sanitizeHtmlOpt, setView, setPreviewSource, setHtmlTextareaSeed]); const formatHtmlView = useCallback(async () => { try { @@ -512,7 +566,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) { toast.error("HTML 정렬에 실패했습니다."); console.error(err); } - }, [scheduleChange]); + }, [scheduleChange, setPreviewSource]); useEffect(() => { if (!editor) return; @@ -544,46 +598,28 @@ export function KriEditorWysiwyg(props: KriEditorProps) { useEffect(() => { setPreviewSource(value ?? ""); - if (!editor) return; - if (value == null) return; + if (!editor || value == null) return; - const compatibility = getCompatibility(value); - if (showHtmlToggle && !compatibility.compatible) { - htmlDraftRef.current = value; - if (htmlTextareaRef.current) htmlTextareaRef.current.value = value; + // WYSIWYG로 손실 없이 편집할 수 없는 값은 HTML 보기로 전환해 원문을 유지한다. + if (showHtmlToggle && !getCompatibility(value).compatible) { + writeHtmlDraft(htmlDraftRef, htmlTextareaRef, value); if (viewRef.current !== "html") { viewRef.current = "html"; + setHtmlTextareaSeed(value); setView("html"); } return; } if (viewRef.current === "html") { - if (getWysiwygCompatibility && value !== optimisticHtmlRef.current && value !== htmlDraftRef.current) { - htmlDraftRef.current = value; - if (htmlTextareaRef.current) htmlTextareaRef.current.value = value; + const isExternalChange = value !== optimisticHtmlRef.current && value !== htmlDraftRef.current; + if (getWysiwygCompatibility && isExternalChange) { + writeHtmlDraft(htmlDraftRef, htmlTextareaRef, value); } return; } - // 빈 문자열("")은 ProseMirror 스키마상 유효한 문서가 아니라 setContent가 조용히 실패해 - // 이전 템플릿 본문이 그대로 남는 문제가 있었음 -> 빈 값은 빈 문단으로 정규화해서 비교/설정. - const normalizedValue = value || "

"; - const current = editor.getHTML(); - - if (normalizedValue !== current && normalizedValue !== optimisticHtmlRef.current) { - // 외부에서 본문이 변경된 경우에만 기존 editor 문서를 갱신한다. - editor.commands.setContent(normalizedValue, { - emitUpdate: false, - parseOptions: {preserveWhitespace: "full"}, - }); - - // resize가 활성화된 TipTap 이미지 NodeView는 노드의 src 변경을 기존 DOM에 반영하지 않는다. - // editor 전체 대신 NodeView만 다시 생성해 이미지를 갱신하고 편집 포커스는 유지한다. - if (normalizedValue.includes(" { @@ -648,14 +684,13 @@ export function KriEditorWysiwyg(props: KriEditorProps) { const previewHtml = useMemo(() => { const preserved = preserveEmptyParagraphs(previewSource); - const sanitized = htmlSanitizer - ? htmlSanitizer(preserved) - : sanitizeHtmlOpt ? sanitizeHtml(preserved, allowedCustomHtml) : preserved; + const sanitized = sanitizeEditorHtml(preserved, htmlSanitizer, sanitizeHtmlOpt, allowedCustomHtml); const withLinkStyle = applyLinkPreviewClass(sanitized); return transformPreviewHtml ? transformPreviewHtml(withLinkStyle) : withLinkStyle; }, [allowedCustomHtml, htmlSanitizer, previewSource, sanitizeHtmlOpt, transformPreviewHtml]); - const imageMapOverlayBoxes = useImageMapOverlay(previewContainerRef, previewHtml); + // 이미지맵을 사용할 때만 미리보기에 영역을 표시한다. + const imageMapOverlayBoxes = useImageMapOverlay(previewContainerRef, previewHtml, enableImageMap && showPreview); const wysiwygCompatibility = useMemo( () => getCompatibility(view === "html" ? previewSource : (editor?.getHTML() ?? previewSource)), @@ -704,7 +739,11 @@ export function KriEditorWysiwyg(props: KriEditorProps) { onAddRow={addRow} onAddColumn={addColumn} onDeleteTable={deleteTable} - customContent={props.renderToolbarEnd?.({ editor, command, view })} + customContent={ + props.renderToolbarEnd ? ( + + ) : undefined + } /> ) : null} @@ -718,7 +757,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {