import React, { useState, useEffect, useRef } from 'react'; import Icon from './Icon'; import Button from './Button'; import UploadButton from './UploadButton'; /** * StackOverflow-driven development: https://stackoverflow.com/a/10158364/1097384 * @param {HTMLTextAreaElement} el */ function moveCaretToEnd(el) { if (typeof el.selectionStart == 'number') { el.selectionStart = el.selectionEnd = el.value.length; // @ts-ignore } else if (typeof el.createTextRange != 'undefined') { el.focus(); // @ts-ignore var range = el.createTextRange(); range.collapse(false); range.select(); } } /** * @typedef {Object} MessageInputProps * @property {string} text * @property {import('../api').Message=} data * @property {function} onSend * @property {number=} rows * @property {string} children */ /** * MessageInput * @param {React.ReactNode & MessageInputProps} props */ export default function MessageInput({ text, data, rows, children, onSend }) { /** * @type {React.MutableRefObject} */ let textareaRef = useRef(); /** * @type {React.MutableRefObject} */ let fileinput = useRef(); let updateFocus = () => { const isDesktop = window.matchMedia('(min-width: 62.5rem)'); if (isDesktop.matches) { textareaRef.current.focus(); moveCaretToEnd(textareaRef.current); } }; useEffect(() => { textChanged({ target: { value: text } }); updateFocus(); }, [text]); let [body, setBody] = useState(text); let handleCtrlEnter = (event) => { if (event.ctrlKey && (event.charCode == 10 || event.charCode == 13)) { onSubmit({}); } }; const textChanged = (event) => { setBody(event.target.value); const el = textareaRef.current; const offset = el.offsetHeight - el.clientHeight; const height = el.scrollHeight + offset; el.style.height = `${height + offset}px`; }; const [attach, setAttach] = useState(''); let uploadValueChanged = (attach) => { setAttach(attach); }; let onSubmit = (event) => { if (event.preventDefault) { event.preventDefault(); } const input = fileinput.current; onSend({ mid: data.mid, rid: data.rid || 0, body: body, attach: attach ? input.files[0] : '', to: data.to || {} }); setAttach(''); setBody(''); textareaRef.current.style.height = ''; updateFocus(); }; return (