import * as React from "react"; type Selection = { start: number; end: number }; export function useTextareaInsert(textareaRef: React.RefObject) { const selectionRef = React.useRef({start: 0, end: 0}); const saveSelection = React.useCallback(() => { const el = textareaRef.current; if (!el) return; selectionRef.current = { start: el.selectionStart ?? 0, end: el.selectionEnd ?? 0, }; }, [textareaRef]); const bindSelectionHandlers = React.useMemo( () => ({ onSelect: saveSelection, onKeyUp: saveSelection, onMouseUp: saveSelection, onClick: saveSelection, onFocus: saveSelection, }), [saveSelection], ); /** * 실제 삽입/치환 로직 (컴포넌트에서 currentText를 제공해야 함) * - apply(nextText): 로컬 state 반영 + latestRef 반영 * - commit(nextText): 부모 onChange 즉시 반영(가능하면 flushChange 사용 권장) */ const insertText = React.useCallback( (placeholder: string, currentText: string, apply: (next: string) => void, commit?: (next: string) => void) => { const {start, end} = selectionRef.current; const next = currentText.slice(0, start) + placeholder + currentText.slice(end); const nextPos = start + placeholder.length; apply(next); commit?.(next); // 렌더 반영 후 커서 복원 requestAnimationFrame(() => { const el = textareaRef.current; if (!el) return; el.focus(); el.setSelectionRange(nextPos, nextPos); selectionRef.current = {start: nextPos, end: nextPos}; }); }, [textareaRef], ); return { selectionRef, saveSelection, bindSelectionHandlers, insertText, }; }