import React, { useState, useEffect, useRef } from 'react'; import PropTypes from 'prop-types'; import { MessageType } from './Types'; import Icon from './Icon'; import Button from './Button'; import UploadButton from './UploadButton'; // StackOverflow-driven development: https://stackoverflow.com/a/10158364/1097384 function moveCaretToEnd(el) { if (typeof el.selectionStart == 'number') { el.selectionStart = el.selectionEnd = el.value.length; } else if (typeof el.createTextRange != 'undefined') { el.focus(); var range = el.createTextRange(); range.collapse(false); range.select(); } } export default function MessageInput({ text, data, rows, children, onSend }) { let textareaRef = useRef(); 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 (