'use client' import * as React from 'react' import { toast } from 'sonner' import { cn } from '@/lib/utils' import type { KriEditorProps } from './types' import { resolveUploadUrl } from './types' import { compressImage } from './utils/imageCompression' import { useDebouncedChange } from './hooks/useDebouncedChange' import { sanitizeHtmlForPreview } from './utils/sanitizeHtml' import { preserveEmptyParagraphs } from './utils/emptyParagraph' import { formatHtmlSource } from './utils/formatHtml' import { useTextareaInsert } from './hooks/useTextareaInsert' type HtmlOnlyProps = Omit & { mode: 'html' } export function KriEditorHtmlOnly({ label, value, onChange, placeholder = 'HTML을 입력하세요...', className, showPreview, previewClassName, rows = 14, debounceMs = 350, onImageUpload, onImageUploadError, maxImageBytes = 5 * 1024 * 1024, imageMaxWidth = 1600, imageMaxHeight = 1600, imageQuality = 0.82, imageMimeType = 'image/webp', onEditorReady, onCommandReady, }: HtmlOnlyProps) { const [html, setHtml] = React.useState(value || '') const textareaRef = React.useRef(null) const fileRef = React.useRef(null) const latestHtmlRef = React.useRef(html) const { scheduleChange, flushChange } = useDebouncedChange(onChange, debounceMs) const textareaInsert = useTextareaInsert(textareaRef) const commitHtml = React.useCallback((next: string, immediate = false) => { setHtml(next) latestHtmlRef.current = next if (immediate) flushChange(next) else scheduleChange(next) }, [flushChange, scheduleChange]) // 사용자가 타이핑한 값이 아니라 외부에서 새로 세팅된 데이터일 때만(최초 마운트 포함) // prettier로 포맷팅해서 반영한다 — 편집 중(commitHtml 경로)에는 절대 재포맷하지 않는다. const applyExternalValue = React.useCallback((next: string) => { setHtml(next) latestHtmlRef.current = next formatHtmlSource(next) .then((formatted) => { if (latestHtmlRef.current !== next) return // 그 사이 값이 또 바뀌었으면 건너뜀 setHtml(formatted) latestHtmlRef.current = formatted }) .catch(() => {}) }, []) React.useEffect(() => { applyExternalValue(value || '') // 최초 마운트 시 1회만 실행 — 이후 value 변경은 아래 effect가 처리한다. }, []) React.useEffect(() => { if ((value || '') !== latestHtmlRef.current) { applyExternalValue(value || '') } }, [value, applyExternalValue]) React.useEffect(() => { onEditorReady?.(textareaRef.current) }, [onEditorReady]) React.useEffect(() => { if (!onCommandReady) return onCommandReady({ focus: () => textareaRef.current?.focus(), insertText: (text) => { textareaInsert.insertText( text, latestHtmlRef.current, (next) => commitHtml(next), (next) => commitHtml(next, true), ) }, }) return () => onCommandReady(null) }, [commitHtml, onCommandReady, textareaInsert]) const handleFile = async (event: React.ChangeEvent) => { try { const file = event.target.files?.[0] event.target.value = '' if (!file || !onImageUpload) return if (!file.type.startsWith('image/')) { toast.error('이미지 파일만 업로드할 수 있습니다.') return } const compressed = await compressImage(file, { maxBytes: maxImageBytes, maxWidth: imageMaxWidth, maxHeight: imageMaxHeight, mimeType: imageMimeType, quality: imageQuality, }) if (compressed.size > maxImageBytes) { toast.error('이미지 용량이 제한을 초과합니다.') return } const url = resolveUploadUrl(await onImageUpload(compressed)) if (!url) { toast.error('이미지 업로드 응답이 올바르지 않습니다.') return } const current = latestHtmlRef.current const textarea = textareaRef.current const imageTag = `` const start = textarea?.selectionStart ?? current.length const end = textarea?.selectionEnd ?? current.length const next = `${current.slice(0, start)}${imageTag}${current.slice(end)}` commitHtml(next) requestAnimationFrame(() => { const position = start + imageTag.length textarea?.focus() textarea?.setSelectionRange(position, position) }) } catch (error) { if (onImageUploadError) onImageUploadError(error) else toast.error('이미지 업로드에 실패했습니다.') } } const handleFormatHtml = React.useCallback(async () => { try { const formatted = await formatHtmlSource(latestHtmlRef.current) commitHtml(formatted) } catch (error) { toast.error('HTML 정렬에 실패했습니다.') console.error(error) } }, [commitHtml]) const previewHtml = React.useMemo( () => sanitizeHtmlForPreview(preserveEmptyParagraphs(html)), [html], ) return (
{label ?
{label}
: null}
HTML 모드
{onImageUpload ? ( ) : null}