You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
session-desktop/ts/components/session/conversation/SessionCompositionBox.tsx

419 lines
11 KiB
TypeScript

5 years ago
import React from 'react';
5 years ago
import { debounce } from 'lodash';
5 years ago
import { Attachment } from '../../../types/Attachment';
import * as MIME from '../../../types/MIME';
5 years ago
import TextareaAutosize from 'react-autosize-textarea';
5 years ago
import { SessionIconButton, SessionIconSize, SessionIconType } from '../icon';
import { SessionEmojiPanel } from './SessionEmojiPanel';
import { SessionRecording } from './SessionRecording';
import { SignalService } from '../../../../ts/protobuf';
5 years ago
import { Constants } from '../../../session';
5 years ago
interface Props {
placeholder?: string;
5 years ago
5 years ago
sendMessage: any;
5 years ago
onMessageSending: any;
onMessageSuccess: any;
onMessageFailure: any;
onLoadVoiceNoteView: any;
onExitVoiceNoteView: any;
dropZoneFiles: FileList;
5 years ago
}
interface State {
message: string;
showRecordingView: boolean;
mediaSetting: boolean | null;
5 years ago
showEmojiPanel: boolean;
attachments: Array<Attachment>;
voiceRecording?: Blob;
5 years ago
}
export class SessionCompositionBox extends React.Component<Props, State> {
private readonly textarea: React.RefObject<HTMLTextAreaElement>;
private readonly fileInput: React.RefObject<HTMLInputElement>;
5 years ago
private emojiPanel: any;
5 years ago
constructor(props: any) {
super(props);
this.state = {
message: '',
attachments: [],
voiceRecording: undefined,
showRecordingView: false,
mediaSetting: null,
5 years ago
showEmojiPanel: false,
};
this.textarea = React.createRef();
this.fileInput = React.createRef();
5 years ago
// Emojis
this.emojiPanel = null;
this.toggleEmojiPanel = debounce(this.toggleEmojiPanel.bind(this), 100);
this.hideEmojiPanel = this.hideEmojiPanel.bind(this);
this.onEmojiClick = this.onEmojiClick.bind(this);
this.handleClick = this.handleClick.bind(this);
5 years ago
this.renderRecordingView = this.renderRecordingView.bind(this);
this.renderCompositionView = this.renderCompositionView.bind(this);
// Recording view functions
this.sendVoiceMessage = this.sendVoiceMessage.bind(this);
this.onLoadVoiceNoteView = this.onLoadVoiceNoteView.bind(this);
this.onExitVoiceNoteView = this.onExitVoiceNoteView.bind(this);
// Attachments
this.onChoseAttachment = this.onChoseAttachment.bind(this);
5 years ago
this.onChooseAttachment = this.onChooseAttachment.bind(this);
5 years ago
// On Sending
this.onSendMessage = this.onSendMessage.bind(this);
// Events
this.onKeyDown = this.onKeyDown.bind(this);
5 years ago
this.onChange = this.onChange.bind(this);
this.focusCompositionBox = this.focusCompositionBox.bind(this);
5 years ago
}
public async componentWillMount() {
const mediaSetting = await window.getSettingValue('media-permissions');
this.setState({ mediaSetting });
}
public componentDidMount() {
setTimeout(this.focusCompositionBox, 100);
}
5 years ago
public render() {
const { showRecordingView } = this.state;
5 years ago
return (
<div className="composition-container">
{showRecordingView ? (
<>{this.renderRecordingView()}</>
5 years ago
) : (
<>{this.renderCompositionView()}</>
5 years ago
)}
</div>
);
}
5 years ago
private handleClick(e: any) {
if (this.emojiPanel && this.emojiPanel.contains(e.target)) {
return;
}
this.toggleEmojiPanel();
}
5 years ago
private showEmojiPanel() {
document.addEventListener('mousedown', this.handleClick, false);
this.setState({
showEmojiPanel: true,
});
}
private hideEmojiPanel() {
document.removeEventListener('mousedown', this.handleClick, false);
5 years ago
this.setState({
5 years ago
showEmojiPanel: false,
5 years ago
});
}
5 years ago
private toggleEmojiPanel() {
5 years ago
if (this.state.showEmojiPanel) {
this.hideEmojiPanel();
} else {
this.showEmojiPanel();
}
}
private renderRecordingView() {
return (
<SessionRecording
sendVoiceMessage={this.sendVoiceMessage}
onLoadVoiceNoteView={this.onLoadVoiceNoteView}
onExitVoiceNoteView={this.onExitVoiceNoteView}
/>
);
}
private renderCompositionView() {
const { placeholder } = this.props;
5 years ago
const { showEmojiPanel, message } = this.state;
return (
<>
<SessionIconButton
iconType={SessionIconType.CirclePlus}
iconSize={SessionIconSize.Large}
onClick={this.onChooseAttachment}
/>
<input
className="hidden"
5 years ago
placeholder="Attachment"
multiple={true}
ref={this.fileInput}
5 years ago
type="file"
onChange={this.onChoseAttachment}
/>
<SessionIconButton
iconType={SessionIconType.Microphone}
iconSize={SessionIconSize.Huge}
onClick={this.onLoadVoiceNoteView}
/>
<div className="send-message-input" role="main" onClick={this.focusCompositionBox}>
<TextareaAutosize
rows={1}
maxRows={3}
5 years ago
ref={this.textarea}
spellCheck={false}
placeholder={placeholder}
5 years ago
maxLength={Constants.CONVERSATION.MAX_MESSAGE_BODY_LENGTH}
onKeyDown={this.onKeyDown}
5 years ago
value={message}
onChange={this.onChange}
/>
</div>
<SessionIconButton
iconType={SessionIconType.Emoji}
iconSize={SessionIconSize.Large}
onClick={this.toggleEmojiPanel}
/>
<div className="send-message-button">
<SessionIconButton
iconType={SessionIconType.Send}
iconSize={SessionIconSize.Large}
iconColor={'#FFFFFF'}
iconRotation={90}
onClick={this.onSendMessage}
/>
</div>
5 years ago
5 years ago
<div
ref={ref => (this.emojiPanel = ref)}
onKeyDown={this.onKeyDown}
role="button"
>
<SessionEmojiPanel
onEmojiClicked={this.onEmojiClick}
show={showEmojiPanel}
/>
5 years ago
</div>
</>
);
}
5 years ago
5 years ago
private onChooseAttachment() {
5 years ago
this.fileInput.current?.click();
5 years ago
}
private onChoseAttachment() {
// Build attachments list
const attachmentsFileList = this.fileInput.current?.files;
5 years ago
if (!attachmentsFileList) {
return;
}
5 years ago
const attachments: Array<Attachment> = [];
Array.from(attachmentsFileList).forEach(async (file: File) => {
const fileBlob = new Blob([file]);
const fileBuffer = await new Response(fileBlob).arrayBuffer();
const attachment = {
fileName: file.name,
flags: undefined,
// FIXME VINCE: Set appropriate type
5 years ago
contentType: MIME.AUDIO_WEBM,
size: file.size,
data: fileBuffer,
};
// Push if size is nonzero
if (attachment.data.byteLength) {
attachments.push(attachment);
}
});
this.setState({ attachments });
5 years ago
}
private onKeyDown(event: any) {
5 years ago
if (event.key === 'Enter' && !event.shiftKey) {
// If shift, newline. Else send message.
event.preventDefault();
this.onSendMessage();
5 years ago
} else if (event.key === 'Escape' && this.state.showEmojiPanel) {
this.hideEmojiPanel();
5 years ago
}
}
private onSendMessage() {
const messageInput = this.textarea.current;
if (!messageInput) {
return;
}
5 years ago
// Verify message length
const messagePlaintext = messageInput.value;
5 years ago
const msgLen = messagePlaintext.length;
if (msgLen === 0 || msgLen > window.CONSTANTS.MAX_MESSAGE_BODY_LENGTH) {
return;
}
5 years ago
// handle Attachments
const { attachments } = this.state;
5 years ago
// Handle emojis
5 years ago
// Send message
5 years ago
this.props.onMessageSending();
this.props
.sendMessage(
messagePlaintext,
attachments,
undefined,
undefined,
null,
{}
)
.then(() => {
// Message sending sucess
this.props.onMessageSuccess();
// Empty attachments
// Empty composition box
this.setState({
message: '',
attachments: [],
});
})
.catch(() => {
// Message sending failed
this.props.onMessageFailure();
5 years ago
});
5 years ago
}
private async sendVoiceMessage(audioBlob: Blob) {
if (!this.state.showRecordingView) {
return;
}
const fileBuffer = await new Response(audioBlob).arrayBuffer();
const audioAttachment: Attachment = {
data: fileBuffer,
flags: SignalService.AttachmentPointer.Flags.VOICE_MESSAGE,
5 years ago
contentType: MIME.AUDIO_MP3,
};
const messageSuccess = this.props.sendMessage(
'',
[audioAttachment],
undefined,
undefined,
null,
{}
);
if (messageSuccess) {
// success!
}
console.log(`[compositionbox] Sending voice message:`, audioBlob);
this.onExitVoiceNoteView();
}
private onLoadVoiceNoteView() {
5 years ago
// Do stuff for component, then run callback to SessionConversation
const { mediaSetting } = this.state;
5 years ago
if (mediaSetting) {
this.setState({
showRecordingView: true,
showEmojiPanel: false,
});
this.props.onLoadVoiceNoteView();
return;
}
window.pushToast({
5 years ago
id: 'audioPermissionNeeded',
title: window.i18n('audioPermissionNeededTitle'),
description: window.i18n('audioPermissionNeededDescription'),
type: 'info',
});
5 years ago
}
private onExitVoiceNoteView() {
5 years ago
// Do stuff for component, then run callback to SessionConversation
this.setState({ showRecordingView: false });
this.props.onExitVoiceNoteView();
5 years ago
}
private onDrop() {
5 years ago
// On drop attachments!
// this.textarea.current?.ondrop;
// Look into react-dropzone
5 years ago
// DROP AREA COMES FROM SessionConversation NOT HERE
5 years ago
}
private onChange(event: any) {
this.setState({ message: event.target.value });
5 years ago
}
private onEmojiClick({ native }: any) {
5 years ago
const messageBox = this.textarea.current;
if (!messageBox) {
return;
}
5 years ago
const { message } = this.state;
const currentSelectionStart = Number(messageBox.selectionStart);
const currentSelectionEnd = Number(messageBox.selectionEnd);
const before = message.slice(0, currentSelectionStart);
const end = message.slice(currentSelectionEnd);
const newMessage = `${before}${native}${end}`;
this.setState({ message: newMessage }, () => {
// update our selection because updating text programmatically
// will put the selection at the end of the textarea
const selectionStart = currentSelectionStart + Number(native.length);
messageBox.selectionStart = selectionStart;
messageBox.selectionEnd = selectionStart;
5 years ago
// Sometimes, we have to repeat the set of the selection position with a timeout to be effective
setTimeout(() => {
messageBox.selectionStart = selectionStart;
messageBox.selectionEnd = selectionStart;
}, 20);
});
}
private focusCompositionBox() {
5 years ago
// Focus the textarea when user clicks anywhere in the composition box
this.textarea.current?.focus();
}
5 years ago
5 years ago
}