"use client"; import { forwardRef, useRef, useImperativeHandle, type KeyboardEvent, type ChangeEvent, useCallback, } from "react"; import { cn } from "@/lib/utils"; import { measureCaretRect } from "@/lib/utils/caret-position"; function isSubmitKeyPress( event: KeyboardEvent, submitKey: "enter" | "cmd_enter", ): boolean { if (submitKey === "enter") { return event.key === "Enter" && !event.shiftKey && !event.metaKey && !event.ctrlKey; } return event.key === "Enter" && (event.metaKey || event.ctrlKey); } export type RichTextInputHandle = { focus: () => void; blur: () => void; getSelectionStart: () => number; getSelectionEnd: () => number; setSelectionRange: (start: number, end: number) => void; getCaretRect: () => DOMRect | null; getValue: () => string; setValue: (value: string) => void; insertText: (text: string, from: number, to: number) => void; getTextareaElement: () => HTMLTextAreaElement | null; }; type RichTextInputProps = { value: string; onChange: (value: string) => void; onKeyDown?: (event: KeyboardEvent) => void; onSubmit?: () => void; placeholder?: string; disabled?: boolean; className?: string; planModeEnabled?: boolean; submitKey?: "enter" | "cmd_enter"; onFocus?: () => void; onBlur?: () => void; }; export const RichTextInput = forwardRef( function RichTextInput( { value, onChange, onKeyDown, onSubmit, placeholder, disabled = false, className, planModeEnabled = false, submitKey = "cmd_enter", onFocus, onBlur, }, ref, ) { const textareaRef = useRef(null); const getCaretRect = useCallback((): DOMRect | null => { const textarea = textareaRef.current; if (!textarea) return null; return measureCaretRect(textarea, value); }, [value]); useImperativeHandle( ref, () => ({ focus: () => textareaRef.current?.focus(), blur: () => textareaRef.current?.blur(), getSelectionStart: () => textareaRef.current?.selectionStart ?? 0, getSelectionEnd: () => textareaRef.current?.selectionEnd ?? 0, setSelectionRange: (start: number, end: number) => { textareaRef.current?.setSelectionRange(start, end); }, getCaretRect, getValue: () => textareaRef.current?.value ?? "", setValue: (newValue: string) => onChange(newValue), insertText: (text: string, from: number, to: number) => { const newValue = value.substring(0, from) + text + value.substring(to); onChange(newValue); requestAnimationFrame(() => { textareaRef.current?.setSelectionRange(from + text.length, from + text.length); }); }, getTextareaElement: () => textareaRef.current, }), [getCaretRect, onChange, value], ); const handleChange = (event: ChangeEvent) => { onChange(event.target.value); }; const handleKeyDown = (event: KeyboardEvent) => { if (onKeyDown) { onKeyDown(event); if (event.defaultPrevented) return; } const isSubmitKey = isSubmitKeyPress(event, submitKey); if (disabled) { if (isSubmitKey) event.preventDefault(); return; } if (isSubmitKey) { event.preventDefault(); onSubmit?.(); } }; return (