'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 Array.from(value).reduce((total, character) => total + (character.charCodeAt(0) > 127 ? 2 : 1), 0) } export function KriEditorSms({ label, value, onChange, placeholder = '문자 내용을 입력하세요...', className, debounceMs = 350, smsTitle = '', changeSmsType, onEditorReady, onCommandReady, smsMaxBytes = 90, lmsMaxBytes = 2000, }: SmsEditorProps) { const [text, setText] = React.useState(value || '') 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 textareaInsert = useTextareaInsert(textareaRef) const byteSize = React.useMemo(() => calculateBytes(text), [text]) const messageType: 'SMS' | 'LMS' = byteSize > smsMaxBytes || Boolean(smsTitle) ? 'LMS' : 'SMS' const maxBytes = messageType === 'SMS' ? smsMaxBytes : lmsMaxBytes 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}
{smsTitle ?
{smsTitle}
: null}