bigbuffet-rw/app/soapbox/features/chats/components/chat.tsx

200 lines
5.7 KiB
TypeScript
Raw Normal View History

2022-11-14 08:22:45 -08:00
import { AxiosError } from 'axios';
2022-09-12 13:46:19 -07:00
import classNames from 'clsx';
import React, { MutableRefObject, useEffect, useState } from 'react';
2022-11-14 08:22:45 -08:00
import { defineMessages, useIntl } from 'react-intl';
import { uploadMedia } from 'soapbox/actions/media';
import { Stack } from 'soapbox/components/ui';
import Upload from 'soapbox/components/upload';
import UploadProgress from 'soapbox/components/upload-progress';
import { useAppDispatch } from 'soapbox/hooks';
import { normalizeAttachment } from 'soapbox/normalizers';
2022-11-09 09:24:44 -08:00
import { IChat, useChatActions } from 'soapbox/queries/chats';
import ChatComposer from './chat-composer';
2022-09-12 13:46:19 -07:00
import ChatMessageList from './chat-message-list';
const fileKeyGen = (): number => Math.floor((Math.random() * 0x10000));
2022-09-12 13:46:19 -07:00
2022-11-14 08:22:45 -08:00
const messages = defineMessages({
failedToSend: { id: 'chat.failed_to_send', defaultMessage: 'Message failed to send.' },
});
2022-09-12 13:46:19 -07:00
interface ChatInterface {
2022-08-18 09:52:04 -07:00
chat: IChat,
inputRef?: MutableRefObject<HTMLTextAreaElement | null>,
2022-09-12 13:46:19 -07:00
className?: string,
}
2022-11-14 08:22:45 -08:00
/**
* Clears the value of the input while dispatching the `onChange` function
* which allows the <Textarea> to resize itself (this is important)
* because we autoGrow the element as the user inputs text that spans
* beyond one line
*/
const clearNativeInputValue = (element: HTMLTextAreaElement) => {
const nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, 'value')?.set;
if (nativeInputValueSetter) {
nativeInputValueSetter.call(element, '');
const ev2 = new Event('input', { bubbles: true });
element.dispatchEvent(ev2);
}
};
2022-09-12 13:46:19 -07:00
/**
* Chat UI with just the messages and textarea.
* Reused between floating desktop chats and fullscreen/mobile chats.
*/
2022-11-03 10:55:33 -07:00
const Chat: React.FC<ChatInterface> = ({ chat, inputRef, className }) => {
2022-11-14 08:22:45 -08:00
const intl = useIntl();
const dispatch = useAppDispatch();
2022-11-14 08:22:45 -08:00
2022-09-28 13:20:59 -07:00
const { createChatMessage, acceptChat } = useChatActions(chat.id);
2022-09-12 13:46:19 -07:00
const [content, setContent] = useState<string>('');
const [attachment, setAttachment] = useState<any>(undefined);
const [isUploading, setIsUploading] = useState(false);
const [uploadProgress, setUploadProgress] = useState(0);
const [resetFileKey, setResetFileKey] = useState<number>(fileKeyGen());
2022-11-14 08:22:45 -08:00
const [errorMessage, setErrorMessage] = useState<string>();
2022-09-12 13:46:19 -07:00
const isSubmitDisabled = content.length === 0 && !attachment;
2022-11-09 09:24:44 -08:00
const submitMessage = () => {
2022-12-06 14:27:07 -08:00
createChatMessage.mutate({ chatId: chat.id, content, mediaId: attachment?.id }, {
2022-11-09 09:24:44 -08:00
onSuccess: () => {
2022-11-14 08:22:45 -08:00
setErrorMessage(undefined);
2022-11-09 09:24:44 -08:00
},
2022-11-14 08:22:45 -08:00
onError: (error: AxiosError<{ error: string }>, _variables, context) => {
const message = error.response?.data?.error;
setErrorMessage(message || intl.formatMessage(messages.failedToSend));
2022-11-11 05:01:17 -08:00
setContent(context.prevContent as string);
},
2022-11-09 09:24:44 -08:00
});
clearState();
};
2022-09-12 13:46:19 -07:00
const clearState = () => {
2022-11-14 08:22:45 -08:00
if (inputRef?.current) {
clearNativeInputValue(inputRef.current);
}
2022-09-12 13:46:19 -07:00
setContent('');
setAttachment(undefined);
setIsUploading(false);
setUploadProgress(0);
setResetFileKey(fileKeyGen());
2022-09-12 13:46:19 -07:00
};
const sendMessage = () => {
2022-11-09 09:24:44 -08:00
if (!isSubmitDisabled && !createChatMessage.isLoading) {
submitMessage();
2022-10-17 09:23:03 -07:00
2022-09-12 13:46:19 -07:00
if (!chat.accepted) {
acceptChat.mutate();
}
}
};
const insertLine = () => setContent(content + '\n');
const handleKeyDown: React.KeyboardEventHandler = (event) => {
markRead();
if (event.key === 'Enter' && event.shiftKey) {
event.preventDefault();
insertLine();
} else if (event.key === 'Enter') {
event.preventDefault();
sendMessage();
}
};
const handleContentChange: React.ChangeEventHandler<HTMLTextAreaElement> = (event) => {
setContent(event.target.value);
};
const handlePaste: React.ClipboardEventHandler<HTMLTextAreaElement> = (e) => {
if (isSubmitDisabled && e.clipboardData && e.clipboardData.files.length === 1) {
handleFiles(e.clipboardData.files);
}
};
2022-09-12 13:46:19 -07:00
const markRead = () => {
// markAsRead.mutate();
// dispatch(markChatRead(chatId));
};
const handleMouseOver = () => markRead();
const handleRemoveFile = () => {
setAttachment(undefined);
setResetFileKey(fileKeyGen());
};
const onUploadProgress = (e: ProgressEvent) => {
const { loaded, total } = e;
setUploadProgress(loaded / total);
};
const handleFiles = (files: FileList) => {
setIsUploading(true);
const data = new FormData();
data.append('file', files[0]);
dispatch(uploadMedia(data, onUploadProgress)).then((response: any) => {
setAttachment(normalizeAttachment(response.data));
setIsUploading(false);
}).catch(() => {
setIsUploading(false);
});
};
useEffect(() => {
if (inputRef?.current) {
inputRef.current.focus();
}
}, [chat.id, inputRef?.current]);
return (
2022-09-12 13:46:19 -07:00
<Stack className={classNames('overflow-hidden flex flex-grow', className)} onMouseOver={handleMouseOver}>
<div className='flex-grow h-full overflow-hidden flex justify-center'>
2022-11-03 10:55:33 -07:00
<ChatMessageList chat={chat} />
2022-09-12 13:46:19 -07:00
</div>
{attachment && (
<div className='relative h-48'>
<Upload
media={attachment}
onDelete={handleRemoveFile}
withPreview
/>
</div>
)}
{isUploading && (
<div className='p-4'>
<UploadProgress progress={uploadProgress * 100} />
</div>
)}
<ChatComposer
ref={inputRef}
onKeyDown={handleKeyDown}
value={content}
onChange={handleContentChange}
onSubmit={sendMessage}
2022-11-14 08:22:45 -08:00
errorMessage={errorMessage}
onSelectFile={handleFiles}
resetFileKey={resetFileKey}
onPaste={handlePaste}
2022-12-06 14:27:07 -08:00
hasAttachment={!!attachment}
/>
2022-09-12 13:46:19 -07:00
</Stack>
);
};
export default Chat;