'use client' import * as React from 'react' import { cn } from '@/lib/utils' import type { KriEditorProps } from './types' import { useDebouncedChange } from './hooks/useDebouncedChange' import { useTextareaInsert } from './hooks/useTextareaInsert' type SmsEditorProps = Omit & { mode: 'sms' } function calculateBytes(value: string): number { return new TextEncoder().encode(value).byteLength } export function KriEditorSms({ label, value, onChange, placeholder = '문자 내용을 입력하세요...', className, debounceMs = 350, smsTitle = '', changeSmsType, onEditorReady, onCommandReady, isSmsReadOnly = false, smsMaxBytes = 90, lmsMaxBytes = 2000, smsPreviewSuffix = '', smsHasAttachment = false, smsImages = [], smsFrameClassName, }: SmsEditorProps) { 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 { 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 maxBytes = messageType === 'SMS' ? smsMaxBytes : lmsMaxBytes function getBadgeColor(): string { switch (messageType) { case 'SMS': return 'bg-red-500' case 'LMS': return 'bg-blue-500' case 'MMS': return 'bg-green-500' } } const commitText = React.useCallback((next: string, immediate = false) => { setText(next) latestTextRef.current = next if (immediate) flushChange(next) else scheduleChange(next) }, [flushChange, scheduleChange]) React.useEffect(() => { if ((value || '') !== latestTextRef.current) { setText(value || '') latestTextRef.current = value || '' } }, [value]) React.useEffect(() => { if (lastTypeRef.current === messageType) return lastTypeRef.current = messageType changeSmsType?.(messageType) }, [changeSmsType, messageType]) React.useEffect(() => { onEditorReady?.(textareaRef.current) }, [onEditorReady]) React.useEffect(() => { if (!onCommandReady) return onCommandReady({ focus: () => textareaRef.current?.focus(), insertText: (insertedText) => { textareaInsert.insertText( insertedText, latestTextRef.current, (next) => commitText(next), (next) => commitText(next, true), ) }, }) return () => onCommandReady(null) }, [commitText, onCommandReady, textareaInsert]) return (
{label ?
{label}
: null}
{byteSize}/{maxBytes}byte {messageType}
0 ? 'overflow-y-auto' : 'overflow-hidden')}> {smsTitle ?
{smsTitle}
: null} {smsImages.length > 0 ? (
{smsImages.map((image) => ( // eslint-disable-next-line @next/next/no-img-element -- data/Object URL 미리보기라 next/image 최적화 대상이 아님 {image.fileName} ))}
) : null}