Files
epolicy-dash-front/src/components/kri-editor/KriEditorHtmlOnly.tsx

198 lines
6.8 KiB
TypeScript

'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<KriEditorProps, 'mode'> & { 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<HTMLTextAreaElement | null>(null)
const fileRef = React.useRef<HTMLInputElement | null>(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가 처리한다.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
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<HTMLInputElement>) => {
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 = `<img src="${url}" alt="" />`
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 (
<div className={cn('rounded-md border bg-background', className)}>
{label ? <div className="border-b px-3 py-2 text-sm font-semibold">{label}</div> : null}
<div className="flex flex-col gap-2 px-3 py-2">
<div className="text-muted-foreground flex items-center justify-between text-xs">
<span>HTML 모드</span>
<div className="flex items-center gap-2">
<button type="button" onClick={handleFormatHtml} className="rounded border px-2 py-1 hover:bg-muted">
정렬
</button>
{onImageUpload ? (
<button type="button" onClick={() => fileRef.current?.click()} className="rounded border px-2 py-1 hover:bg-muted">
이미지 업로드
</button>
) : null}
</div>
</div>
<textarea
ref={textareaRef}
className="min-h-[200px] w-full resize-y rounded-md border bg-background p-2 font-mono text-sm outline-none"
value={html}
onChange={(event) => commitHtml(event.target.value)}
onBlur={() => flushChange(latestHtmlRef.current)}
placeholder={placeholder}
rows={rows}
{...textareaInsert.bindSelectionHandlers}
/>
<input ref={fileRef} type="file" accept="image/*" className="hidden" onChange={handleFile} />
</div>
{showPreview ? (
<div className={cn('border-t p-3', previewClassName)}>
<div className="mb-2 text-sm font-semibold">미리보기</div>
<div className="rounded-md border bg-muted/30 p-3 text-sm leading-relaxed" dangerouslySetInnerHTML={{ __html: previewHtml }} />
</div>
) : null}
</div>
)
}