element-web/src/components/views/rooms/MessageComposer.tsx

459 lines
17 KiB
TypeScript
Raw Normal View History

/*
2021-04-06 14:26:50 +03:00
Copyright 2015-2021 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
2021-04-06 14:26:50 +03:00
import React from 'react';
2020-07-28 15:19:11 +03:00
import classNames from 'classnames';
import { _t } from '../../../languageHandler';
import { MatrixClientPeg } from '../../../MatrixClientPeg';
import { MatrixEvent } from "matrix-js-sdk/src/models/event";
import { Room } from "matrix-js-sdk/src/models/room";
import { RoomMember } from "matrix-js-sdk/src/models/room-member";
import dis from '../../../dispatcher/dispatcher';
import { ActionPayload } from "../../../dispatcher/payloads";
2018-02-26 01:10:38 +03:00
import Stickerpicker from './Stickerpicker';
import { makeRoomPermalink, RoomPermalinkCreator } from '../../../utils/permalinks/Permalinks';
import ContentMessages from '../../../ContentMessages';
import E2EIcon from './E2EIcon';
import SettingsStore from "../../../settings/SettingsStore";
import { aboveLeftOf, ContextMenu, ContextMenuTooltipButton, useContextMenu } from "../../structures/ContextMenu";
import AccessibleTooltipButton from "../elements/AccessibleTooltipButton";
import ReplyPreview from "./ReplyPreview";
import { UIFeature } from "../../../settings/UIFeature";
import { UPDATE_EVENT } from "../../../stores/AsyncStore";
import { replaceableComponent } from "../../../utils/replaceableComponent";
2021-03-16 07:16:58 +03:00
import VoiceRecordComposerTile from "./VoiceRecordComposerTile";
import { VoiceRecordingStore } from "../../../stores/VoiceRecordingStore";
import { RecordingState } from "../../../voice/VoiceRecording";
import Tooltip, { Alignment } from "../elements/Tooltip";
2021-04-06 14:26:50 +03:00
import ResizeNotifier from "../../../utils/ResizeNotifier";
import { E2EStatus } from '../../../utils/ShieldUtils';
2021-04-06 14:26:50 +03:00
import SendMessageComposer from "./SendMessageComposer";
import { ComposerInsertPayload } from "../../../dispatcher/payloads/ComposerInsertPayload";
import { Action } from "../../../dispatcher/actions";
import EditorModel from "../../../editor/model";
import EmojiPicker from '../emojipicker/EmojiPicker';
import MemberStatusMessageAvatar from "../avatars/MemberStatusMessageAvatar";
2021-04-06 14:26:50 +03:00
interface IComposerAvatarProps {
me: object;
}
2021-04-06 14:26:50 +03:00
function ComposerAvatar(props: IComposerAvatarProps) {
return <div className="mx_MessageComposer_avatar">
<MemberStatusMessageAvatar member={props.me} width={24} height={24} />
</div>;
}
2021-04-06 14:26:50 +03:00
interface ISendButtonProps {
onClick: () => void;
}
2021-04-06 14:26:50 +03:00
function SendButton(props: ISendButtonProps) {
return (
<AccessibleTooltipButton
className="mx_MessageComposer_sendMessage"
onClick={props.onClick}
title={_t('Send message')}
/>
);
}
2021-06-29 15:11:58 +03:00
const EmojiButton = ({ addEmoji }) => {
const [menuDisplayed, button, openMenu, closeMenu] = useContextMenu();
let contextMenu;
if (menuDisplayed) {
const buttonRect = button.current.getBoundingClientRect();
contextMenu = <ContextMenu {...aboveLeftOf(buttonRect)} onFinished={closeMenu} managed={false}>
<EmojiPicker onChoose={addEmoji} showQuickReactions={true} />
</ContextMenu>;
}
2020-07-28 15:19:11 +03:00
const className = classNames(
"mx_MessageComposer_button",
"mx_MessageComposer_emoji",
{
2020-07-28 19:13:58 +03:00
"mx_MessageComposer_button_highlight": menuDisplayed,
2020-07-28 15:19:11 +03:00
},
);
2020-07-28 19:13:58 +03:00
// TODO: replace ContextMenuTooltipButton with a unified representation of
// the header buttons and the right panel buttons
return <React.Fragment>
<ContextMenuTooltipButton
2020-07-28 15:19:11 +03:00
className={className}
onClick={openMenu}
isExpanded={menuDisplayed}
title={_t('Emoji picker')}
inputRef={button}
>
</ContextMenuTooltipButton>
{ contextMenu }
</React.Fragment>;
};
2021-04-06 14:26:50 +03:00
interface IUploadButtonProps {
roomId: string;
}
class UploadButton extends React.Component<IUploadButtonProps> {
private uploadInput = React.createRef<HTMLInputElement>();
private dispatcherRef: string;
constructor(props) {
super(props);
this.dispatcherRef = dis.register(this.onAction);
}
componentWillUnmount() {
dis.unregister(this.dispatcherRef);
}
2021-04-26 17:21:49 +03:00
private onAction = (payload: ActionPayload) => {
if (payload.action === "upload_file") {
this.onUploadClick();
}
};
2021-04-06 14:26:50 +03:00
private onUploadClick = () => {
if (MatrixClientPeg.get().isGuest()) {
2021-06-29 15:11:58 +03:00
dis.dispatch({ action: 'require_registration' });
return;
}
this.uploadInput.current.click();
2021-06-29 15:11:58 +03:00
};
2021-04-26 17:27:30 +03:00
private onUploadFileInputChange = (ev: React.ChangeEvent<HTMLInputElement>) => {
if (ev.target.files.length === 0) return;
// take a copy so we can safely reset the value of the form control
// (Note it is a FileList: we can't use slice or sensible iteration).
const tfiles = [];
for (let i = 0; i < ev.target.files.length; ++i) {
tfiles.push(ev.target.files[i]);
}
ContentMessages.sharedInstance().sendContentListToRoom(
tfiles, this.props.roomId, MatrixClientPeg.get(),
);
// This is the onChange handler for a file form control, but we're
// not keeping any state, so reset the value of the form control
// to empty.
// NB. we need to set 'value': the 'files' property is immutable.
ev.target.value = '';
2021-06-29 15:11:58 +03:00
};
render() {
2021-06-29 15:11:58 +03:00
const uploadInputStyle = { display: 'none' };
return (
<AccessibleTooltipButton
className="mx_MessageComposer_button mx_MessageComposer_upload"
onClick={this.onUploadClick}
title={_t('Upload file')}
>
<input
ref={this.uploadInput}
type="file"
style={uploadInputStyle}
multiple
onChange={this.onUploadFileInputChange}
/>
</AccessibleTooltipButton>
);
}
}
2021-04-06 14:26:50 +03:00
interface IProps {
room: Room;
resizeNotifier: ResizeNotifier;
permalinkCreator: RoomPermalinkCreator;
replyToEvent?: MatrixEvent;
e2eStatus?: E2EStatus;
}
interface IState {
tombstone: MatrixEvent;
canSendMessages: boolean;
isComposerEmpty: boolean;
haveRecording: boolean;
recordingTimeLeftSeconds?: number;
me?: RoomMember;
}
@replaceableComponent("views.rooms.MessageComposer")
2021-04-06 14:26:50 +03:00
export default class MessageComposer extends React.Component<IProps, IState> {
private dispatcherRef: string;
private messageComposerInput: SendMessageComposer;
private voiceRecordingButton: VoiceRecordComposerTile;
2021-04-06 14:26:50 +03:00
constructor(props) {
super(props);
VoiceRecordingStore.instance.on(UPDATE_EVENT, this.onVoiceStoreUpdate);
this.state = {
2021-04-06 14:26:50 +03:00
tombstone: this.getRoomTombstone(),
canSendMessages: this.props.room.maySendMessage(),
isComposerEmpty: true,
2021-03-16 07:16:58 +03:00
haveRecording: false,
recordingTimeLeftSeconds: null, // when set to a number, shows a toast
2016-06-01 14:24:21 +03:00
};
}
2016-06-01 14:24:21 +03:00
2021-04-06 14:26:50 +03:00
componentDidMount() {
this.dispatcherRef = dis.register(this.onAction);
MatrixClientPeg.get().on("RoomState.events", this.onRoomStateEvents);
this.waitForOwnMember();
}
2021-04-26 17:21:49 +03:00
private onAction = (payload: ActionPayload) => {
if (payload.action === 'reply_to_event') {
// add a timeout for the reply preview to be rendered, so
// that the ScrollPanel listening to the resizeNotifier can
// correctly measure it's new height and scroll down to keep
// at the bottom if it already is
setTimeout(() => {
this.props.resizeNotifier.notifyTimelineHeightChanged();
}, 100);
}
};
2021-04-06 14:26:50 +03:00
private waitForOwnMember() {
// if we have the member already, do that
const me = this.props.room.getMember(MatrixClientPeg.get().getUserId());
if (me) {
2021-06-29 15:11:58 +03:00
this.setState({ me });
return;
}
// Otherwise, wait for member loading to finish and then update the member for the avatar.
// The members should already be loading, and loadMembersIfNeeded
// will return the promise for the existing operation
this.props.room.loadMembersIfNeeded().then(() => {
const me = this.props.room.getMember(MatrixClientPeg.get().getUserId());
2021-06-29 15:11:58 +03:00
this.setState({ me });
});
}
componentWillUnmount() {
if (MatrixClientPeg.get()) {
2021-04-06 14:26:50 +03:00
MatrixClientPeg.get().removeListener("RoomState.events", this.onRoomStateEvents);
}
VoiceRecordingStore.instance.off(UPDATE_EVENT, this.onVoiceStoreUpdate);
2020-08-18 13:34:43 +03:00
dis.unregister(this.dispatcherRef);
}
2021-04-06 14:26:50 +03:00
private onRoomStateEvents = (ev, state) => {
if (ev.getRoomId() !== this.props.room.roomId) return;
if (ev.getType() === 'm.room.tombstone') {
2021-06-29 15:11:58 +03:00
this.setState({ tombstone: this.getRoomTombstone() });
}
if (ev.getType() === 'm.room.power_levels') {
2021-06-29 15:11:58 +03:00
this.setState({ canSendMessages: this.props.room.maySendMessage() });
}
2021-06-29 15:11:58 +03:00
};
2021-04-06 14:26:50 +03:00
private getRoomTombstone() {
return this.props.room.currentState.getStateEvents('m.room.tombstone', '');
}
2021-04-06 14:26:50 +03:00
private onTombstoneClick = (ev) => {
ev.preventDefault();
const replacementRoomId = this.state.tombstone.getContent()['replacement_room'];
const replacementRoom = MatrixClientPeg.get().getRoom(replacementRoomId);
let createEventId = null;
if (replacementRoom) {
const createEvent = replacementRoom.currentState.getStateEvents('m.room.create', '');
if (createEvent && createEvent.getId()) createEventId = createEvent.getId();
}
const viaServers = [this.state.tombstone.getSender().split(':').splice(1).join(':')];
dis.dispatch({
action: 'view_room',
highlighted: true,
event_id: createEventId,
room_id: replacementRoomId,
auto_join: true,
2020-10-29 18:53:14 +03:00
_type: "tombstone", // instrumentation
// Try to join via the server that sent the event. This converts @something:example.org
// into a server domain by splitting on colons and ignoring the first entry ("@something").
via_servers: viaServers,
opts: {
// These are passed down to the js-sdk's /join call
viaServers: viaServers,
},
});
2021-06-29 15:11:58 +03:00
};
2021-04-06 14:26:50 +03:00
private renderPlaceholderText = () => {
if (this.props.replyToEvent) {
if (this.props.e2eStatus) {
return _t('Send an encrypted reply…');
} else {
return _t('Send a reply…');
}
} else {
if (this.props.e2eStatus) {
return _t('Send an encrypted message…');
} else {
return _t('Send a message…');
}
}
2021-06-29 15:11:58 +03:00
};
private addEmoji(emoji: string) {
2021-05-25 00:02:50 +03:00
dis.dispatch<ComposerInsertPayload>({
action: Action.ComposerInsert,
text: emoji,
});
}
private sendMessage = async () => {
if (this.state.haveRecording && this.voiceRecordingButton) {
// There shouldn't be any text message to send when a voice recording is active, so
// just send out the voice recording.
await this.voiceRecordingButton.send();
return;
}
this.messageComposerInput.sendMessage();
2021-06-29 15:11:58 +03:00
};
private onChange = (model: EditorModel) => {
this.setState({
isComposerEmpty: model.isEmpty,
});
2021-06-29 15:11:58 +03:00
};
private onVoiceStoreUpdate = () => {
const recording = VoiceRecordingStore.instance.activeRecording;
2021-06-29 15:11:58 +03:00
this.setState({ haveRecording: !!recording });
if (recording) {
2021-04-16 19:11:04 +03:00
// We show a little heads up that the recording is about to automatically end soon. The 3s
// display time is completely arbitrary. Note that we don't need to deregister the listener
// because the recording instance will clean that up for us.
2021-06-29 15:11:58 +03:00
recording.on(RecordingState.EndingSoon, ({ secondsLeft }) => {
this.setState({ recordingTimeLeftSeconds: secondsLeft });
setTimeout(() => this.setState({ recordingTimeLeftSeconds: null }), 3000);
});
}
2021-03-16 07:16:58 +03:00
};
render() {
const controls = [
this.state.me ? <ComposerAvatar key="controls_avatar" me={this.state.me} /> : null,
2019-08-05 16:50:16 +03:00
this.props.e2eStatus ?
<E2EIcon key="e2eIcon" status={this.props.e2eStatus} className="mx_MessageComposer_e2eIcon" /> :
null,
];
2016-09-12 03:37:51 +03:00
if (!this.state.tombstone && this.state.canSendMessages) {
controls.push(
<SendMessageComposer
2017-05-17 13:31:01 +03:00
ref={(c) => this.messageComposerInput = c}
2016-06-21 16:03:39 +03:00
key="controls_input"
room={this.props.room}
placeholder={this.renderPlaceholderText()}
permalinkCreator={this.props.permalinkCreator}
replyToEvent={this.props.replyToEvent}
onChange={this.onChange}
2021-03-16 07:16:58 +03:00
disabled={this.state.haveRecording}
2021-03-17 08:57:27 +03:00
/>,
);
2021-03-16 07:16:58 +03:00
if (!this.state.haveRecording) {
controls.push(
<UploadButton key="controls_upload" roomId={this.props.room.roomId} />,
<EmojiButton key="emoji_button" addEmoji={this.addEmoji} />,
);
}
if (SettingsStore.getValue(UIFeature.Widgets) &&
2021-03-16 07:16:58 +03:00
SettingsStore.getValue("MessageComposerInput.showStickersButton") &&
!this.state.haveRecording) {
controls.push(<Stickerpicker key="stickerpicker_controls_button" room={this.props.room} />);
}
2021-03-16 07:16:58 +03:00
if (SettingsStore.getValue("feature_voice_messages")) {
controls.push(<VoiceRecordComposerTile
key="controls_voice_record"
ref={c => this.voiceRecordingButton = c}
room={this.props.room} />);
2021-03-16 07:16:58 +03:00
}
if (!this.state.isComposerEmpty || this.state.haveRecording) {
controls.push(
<SendButton key="controls_send" onClick={this.sendMessage} />,
);
}
} else if (this.state.tombstone) {
const replacementRoomId = this.state.tombstone.getContent()['replacement_room'];
const continuesLink = replacementRoomId ? (
<a href={makeRoomPermalink(replacementRoomId)}
className="mx_MessageComposer_roomReplaced_link"
2021-04-06 14:26:50 +03:00
onClick={this.onTombstoneClick}
>
{ _t("The conversation continues here.") }
</a>
) : '';
controls.push(<div className="mx_MessageComposer_replaced_wrapper" key="room_replaced">
<div className="mx_MessageComposer_replaced_valign">
2021-04-01 16:15:21 +03:00
<img className="mx_MessageComposer_roomReplaced_icon"
src={require("../../../../res/img/room_replaced.svg")}
/>
<span className="mx_MessageComposer_roomReplaced_header">
{ _t("This room has been replaced and is no longer active.") }
</span><br />
{ continuesLink }
</div>
</div>);
} else {
controls.push(
<div key="controls_error" className="mx_MessageComposer_noperm_error">
{ _t('You do not have permission to post to this room') }
2017-06-12 16:52:41 +03:00
</div>,
);
}
let recordingTooltip;
const secondsLeft = Math.round(this.state.recordingTimeLeftSeconds);
if (secondsLeft) {
recordingTooltip = <Tooltip
2021-06-29 15:11:58 +03:00
label={_t("%(seconds)ss left", { seconds: secondsLeft })}
alignment={Alignment.Top} yOffset={-50}
/>;
}
return (
<div className="mx_MessageComposer mx_GroupLayout">
{ recordingTooltip }
<div className="mx_MessageComposer_wrapper">
<ReplyPreview permalinkCreator={this.props.permalinkCreator} />
<div className="mx_MessageComposer_row">
{ controls }
</div>
</div>
2015-11-26 20:31:10 +03:00
</div>
);
}
}