import React, { useEffect, useState } from 'react'; import { MessageFormProps } from './props'; import { styles } from './styles'; import { AttachmentInput } from './AttachmentInput'; import { File } from '../../../Components/File'; import { Image } from '../../../Components/Image'; import { isImage } from '../../../util/file'; import { MessageObject, AttachmentObject } from '../../../../interfaces'; export const MessageForm: React.FC = ( props: MessageFormProps ) => { const { label = '' } = props; const [iter, setIter] = useState(0); // Forces attachments update const [value, setValue] = useState(''); const [height, setHeight] = useState(0); const [buttonHover, setButtonHover] = useState(false); const [attachments, setAttachments] = useState>([]); useEffect(() => resize(), []); const resize = () => { var textarea = document.getElementById('msg-textarea'); if (textarea !== null) { textarea.style.height = ''; textarea.style.height = Math.min(textarea.scrollHeight, 150) + 'px'; setHeight(Math.min(textarea.scrollHeight, 150)); } }; const onChange = (e: React.ChangeEvent) => { setValue(e.target.value); props.onChange && props.onChange(e); resize(); }; const onSubmit = () => { const created = new Date() .toISOString() .replace('T', ' ') .replace('Z', `${Math.floor(Math.random() * 1000)}+00:00`); const localAttachments: AttachmentObject[] = attachments.map( (attachment) => { return { id: -1, created: new Date().toString(), file: attachment.name, blob: attachment, }; } ); const message: MessageObject = { attachments: localAttachments, text: value, sender_username: props.username ? props.username : '', custom_json: {}, created, }; props.onSubmit && props.onSubmit(message); setValue(''); setAttachments([]); resize(); }; const onKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Enter') { e.preventDefault(); if (value.length > 0) { onSubmit(); } } }; const onRemove = (index: number) => { if (attachments && attachments !== null) { const newAttachments = attachments; newAttachments.splice(index, 1); setAttachments(newAttachments); setIter(iter + 1); } }; const renderAttachments = (renderImage: boolean) => { if (!attachments || attachments === null) return
; return Array.from(attachments).map((attachment, index) => { const url = URL.createObjectURL(attachment); return ( {renderImage && isImage(attachment.name) && ( )} {!renderImage && !isImage(attachment.name) && ( )} {((!renderImage && !isImage(attachment.name)) || (renderImage && isImage(attachment.name))) && ( )} ); }); }; if (props.renderMessageForm) { return <>{props.renderMessageForm(props)}; } return (
{renderAttachments(true)}
{renderAttachments(false)}