import { useEffect, useRef, useState } from 'react' import TextareaAutosize from 'react-textarea-autosize' import { useAuthentication } from 'utils/authentication' import { IconButton } from 'components/design/IconButton' import { MessageData } from 'contexts/Messages' import { EmojiPicker, EmojiPickerOnClick } from 'components/Emoji' const defaultMessageData: MessageData = { type: 'text', value: '' } export interface SendMessageProps { channelId: string } export const SendMessage: React.FC = (props) => { const { authentication } = useAuthentication() const [messageData, setMessageData] = useState( defaultMessageData ) const [isVisibleEmojiPicker, setIsVisibleEmojiPicker] = useState(false) const inputFile = useRef(null) useEffect(() => { window.scrollTo(0, document.body.scrollHeight) }, [isVisibleEmojiPicker]) const handleKeyDown: React.KeyboardEventHandler = async ( event ) => { if (event.key === 'Enter' && !event.shiftKey) { event.preventDefault() await sendMessage(messageData) } } const handleSubmit: React.FormEventHandler = async ( event ) => { event.preventDefault() await sendMessage(messageData) } const handleChange: React.ChangeEventHandler = ( event ) => { setMessageData({ value: event.target.value, type: 'text' }) } const handleVisibleEmojiPicker = (): void => { setIsVisibleEmojiPicker((isVisible) => !isVisible) } const handleEmojiPicker: EmojiPickerOnClick = (emoji) => { const emojiColons = emoji.colons ?? '' setMessageData((message) => { return { value: message.value + emojiColons, type: 'text' } }) handleVisibleEmojiPicker() } const handleUploadFile = (): void => { inputFile.current?.click() } const handleSubmitFile = async (): Promise => { if ( inputFile.current?.files != null && inputFile.current?.files?.length > 0 ) { const file = inputFile.current.files[0] const formData = new FormData() formData.append('type', 'file') formData.append('file', file) await authentication.api.post( `/channels/${props.channelId}/messages`, formData ) setMessageData(defaultMessageData) } } const sendMessage = async (messageData: MessageData): Promise => { const isEmptyMessage = messageData.value.length <= 0 if (!isEmptyMessage) { await authentication.api.post(`/channels/${props.channelId}/messages`, { value: messageData.value, type: messageData.type }) setMessageData(defaultMessageData) } } return ( <> {isVisibleEmojiPicker && }
) }