Skip to content

Jitsi Meet - Secure, Simple and Scalable Video Conferences that you use as a standalone app or embed in your web application.

feat(chat): add message editing for group and private chat (#17451)

Alok-work23d1153f58e899
diff --git a/lang/main.json b/lang/main.json
index cfef35b466..f83bf02512 100644
--- a/lang/main.json
+++ b/lang/main.json
@@ -116,6 +116,8 @@
},
"chat": {
"disabled": "Sending chat messages is disabled.",
+ "edited": "(edited)",
+ "editingMessage": "Editing",
"enter": "Enter room",
"error": "Error: your message was not sent. Reason: {{error}}",
"everyone": "Everyone",
diff --git a/react/features/chat/actionTypes.ts b/react/features/chat/actionTypes.ts
index 6876976740..12d2bcce5c 100644
--- a/react/features/chat/actionTypes.ts
+++ b/react/features/chat/actionTypes.ts
@@ -83,6 +83,17 @@ export const OPEN_CHAT = 'OPEN_CHAT';
*/
export const SEND_MESSAGE = 'SEND_MESSAGE';
+/**
+ * The type of the action which signals sending an edit for an existing chat message.
+ *
+ * {
+ * type: SEND_MESSAGE_EDIT,
+ * messageId: string,
+ * message: string
+ * }
+ */
+export const SEND_MESSAGE_EDIT = 'SEND_MESSAGE_EDIT';
+
/**
* The type of the action which signals a reaction to a message.
*
diff --git a/react/features/chat/actions.any.ts b/react/features/chat/actions.any.ts
index dfc5be5e93..f323e29d6e 100644
--- a/react/features/chat/actions.any.ts
+++ b/react/features/chat/actions.any.ts
@@ -15,6 +15,7 @@ import {
OPEN_CHAT,
REMOVE_LOBBY_CHAT_PARTICIPANT,
SEND_MESSAGE,
+ SEND_MESSAGE_EDIT,
SEND_REACTION,
SET_CHAT_SEARCH_MATCH_INDEX,
SET_CHAT_SEARCH_QUERY,
@@ -172,6 +173,25 @@ export function sendReaction(reaction: string, messageId: string, receiverId?: s
}
/**
+ * Sends an edit for an existing chat message to everyone in the conference.
+ *
+ * @param {string} messageId - The ID of the message being edited.
+ * @param {string} message - The updated chat message.
+ * @returns {{
+ * type: SEND_MESSAGE_EDIT,
+ * messageId: string,
+ * message: string
+ * }}
+ */
+export function sendMessageEdit(messageId: string, message: string) {
+ return {
+ type: SEND_MESSAGE_EDIT,
+ messageId,
+ message
+ };
+}
+
+/*
* Sets the chat search query and resets the match index back to the first result.
*
* @param {string} query - The search text.
diff --git a/react/features/chat/components/web/Chat.tsx b/react/features/chat/components/web/Chat.tsx
index fca18631d0..1715eab59a 100644
--- a/react/features/chat/components/web/Chat.tsx
+++ b/react/features/chat/components/web/Chat.tsx
@@ -17,6 +17,7 @@ import PollsPane from '../../../polls/components/web/PollsPane';
import { isCCTabEnabled } from '../../../subtitles/functions.any';
import {
sendMessage,
+ sendMessageEdit,
setChatIsResizing,
setFocusedTab,
setPrivateMessageRecipient,
@@ -35,7 +36,7 @@ import {
SMALL_WIDTH_THRESHOLD
} from '../../constants';
import { getChatMaxSize, getFocusedTab, isChatDisabled } from '../../functions';
-import { IChatProps as AbstractProps } from '../../types';
+import { IChatProps as AbstractProps, IMessage } from '../../types';
import ChatHeader from './ChatHeader';
import ChatInput from './ChatInput';
@@ -288,6 +289,7 @@ const Chat = ({
const [ isMouseDown, setIsMouseDown ] = useState(false);
const [ mousePosition, setMousePosition ] = useState<number | null>(null);
const [ dragChatWidth, setDragChatWidth ] = useState<number | null>(null);
+ const [ editingMessage, setEditingMessage ] = useState<IMessage | undefined>();
const maxChatWidth = useSelector(getChatMaxSize);
const notifyTimestamp = useSelector((state: IReduxState) =>
state['features/chat'].notifyPrivateRecipientsChangedTimestamp
@@ -366,6 +368,10 @@ const Chat = ({
}
}, [ isMouseDown, dispatch ]);
+ const onCancelEdit = useCallback(() => {
+ setEditingMessage(undefined);
+ }, []);
+
/**
* Handles drag handle pointer move.
* Supports both mouse and touch events via Pointer Events API.
@@ -415,8 +421,14 @@ const Chat = ({
* @type {Function}
*/
const onSendMessage = useCallback((text: string) => {
+ if (editingMessage) {
+ dispatch(sendMessageEdit(editingMessage.messageId, text));
+ setEditingMessage(undefined);
+
+ return;
+ }
dispatch(sendMessage(text));
- }, []);
+ }, [ dispatch, editingMessage ]);
/**
* Toggles the chat window.
@@ -487,8 +499,11 @@ const Chat = ({
role = 'tabpanel'
tabIndex = { 0 }>
<MessageContainer
+ editingMessage = { editingMessage }
isVisible = { _focusedTab === ChatTabs.CHAT }
- messages = { _messages } />
+ messages = { _messages }
+ onCancelEdit = { onCancelEdit }
+ onEditMessage = { setEditingMessage } />
<MessageRecipient />
{isPrivateChatAllowed && (
<Select
@@ -499,6 +514,8 @@ const Chat = ({
value = { privateMessageRecipient?.id || OPTION_GROUPCHAT } />
)}
<ChatInput
+ editingMessage = { editingMessage }
+ onCancelEdit = { onCancelEdit }
onSend = { onSendMessage } />
</div>) }
{ _isPollsEnabled && (
diff --git a/react/features/chat/components/web/ChatInput.tsx b/react/features/chat/components/web/ChatInput.tsx
index 6fe2568b61..2ecde32e6b 100644
--- a/react/features/chat/components/web/ChatInput.tsx
+++ b/react/features/chat/components/web/ChatInput.tsx
@@ -10,8 +10,9 @@ import { translate } from '../../../base/i18n/functions';
import { IconFaceSmile, IconSend } from '../../../base/icons/svg';
import Button from '../../../base/ui/components/web/Button';
import Input from '../../../base/ui/components/web/Input';
-import { CHAT_SIZE } from '../../constants';
+import { CHAR_LIMIT, CHAT_SIZE } from '../../constants';
import { areSmileysDisabled, isSendGroupChatDisabled } from '../../functions';
+import { IMessage } from '../../types';
import SmileysPanel from './SmileysPanel';
@@ -78,6 +79,16 @@ interface IProps extends WithTranslation {
*/
dispatch: IStore['dispatch'];
+ /**
+ * The message currently being edited, if any.
+ */
+ editingMessage?: IMessage;
+
+ /**
+ * Callback invoked to cancel message editing.
+ */
+ onCancelEdit?: () => void;
+
/**
* Callback to invoke on message send.
*/
@@ -155,6 +166,12 @@ class ChatInput extends Component<IProps, IState> {
if (prevProps._privateMessageRecipientId !== this.props._privateMessageRecipientId) {
this._textArea?.current?.focus();
}
+ if (prevProps.editingMessage?.messageId !== this.props.editingMessage?.messageId) {
+ this.setState({
+ message: this.props.editingMessage?.message ?? ''
+ });
+ this._focus();
+ }
}
/**
@@ -237,7 +254,7 @@ class ChatInput extends Component<IProps, IState> {
return;
}
- const trimmed = this.state.message.trim();
+ const trimmed = this.state.message.trim().slice(0, CHAR_LIMIT);
if (trimmed) {
onSend(trimmed);
@@ -274,6 +291,16 @@ class ChatInput extends Component<IProps, IState> {
return;
}
+ if (event.key === 'Escape' && this.props.editingMessage) {
+ event.preventDefault();
+ event.stopPropagation();
+
+ this.props.onCancelEdit?.();
+ this.setState({ message: '' });
+
+ return;
+ }
+
if (event.key === 'Enter'
&& event.shiftKey === false
&& event.ctrlKey === false) {
@@ -292,7 +319,7 @@ class ChatInput extends Component<IProps, IState> {
* @returns {void}
*/
_onMessageChange(value: string) {
- this.setState({ message: value });
+ this.setState({ message: value.slice(0, CHAR_LIMIT) });
}
/**
diff --git a/react/features/chat/components/web/ChatMessage.tsx b/react/features/chat/components/web/ChatMessage.tsx
index 38427f3f37..7e2b00c3a2 100644
--- a/react/features/chat/components/web/ChatMessage.tsx
+++ b/react/features/chat/components/web/ChatMessage.tsx
@@ -21,6 +21,9 @@ interface IProps extends IChatMessageProps {
className?: string;
enablePrivateChat?: boolean;
isActiveSearchMatch?: boolean;
+ isEditing?: boolean;
+ onCancelEdit?: () => void;
+ onEditMessage?: (message: IChatMessageProps['message']) => void;
searchQuery?: string;
shouldDisplayMenuOnRight?: boolean;
state?: IReduxState;
@@ -196,6 +199,12 @@ const useStyles = makeStyles()((theme: Theme) => {
whiteSpace: 'nowrap',
flexShrink: 0
},
+ editedLabel: {
+ ...theme.typography.labelRegular,
+ color: theme.palette.chatTimestamp,
+ marginLeft: theme.spacing(1),
+ whiteSpace: 'nowrap'
+ },
reactionsPopover: {
padding: theme.spacing(2),
backgroundColor: theme.palette.chatInputBackground,
@@ -226,12 +235,28 @@ const useStyles = makeStyles()((theme: Theme) => {
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap'
- }
+ },
+ editingNotice: {
+ alignItems: 'center',
+ borderTop: `1px solid ${theme.palette.chatInputBorder}`,
+ color: theme.palette.chatMessageText,
+ display: 'flex',
+ justifyContent: 'space-between',
+ marginTop: theme.spacing(1),
+ paddingTop: theme.spacing(1),
+ width: '100%',
+ ...theme.typography.labelRegular
+ },
+ cancelEdit: {
+ cursor: 'pointer',
+ color: theme.palette.link01
+ },
};
});
const ChatMessage = ({
className = '',
+ isEditing,
message,
state,
showDisplayName,
@@ -240,6 +265,8 @@ const ChatMessage = ({
searchQuery,
enablePrivateChat,
knocking,
+ onCancelEdit,
+ onEditMessage,
t
}: IProps) => {
const { classes, cx } = useStyles();
@@ -273,6 +300,10 @@ const ChatMessage = ({
});
}, [ isActiveSearchMatch ]);
+ const handleEditMessage = useCallback(() => {
+ onEditMessage?.(message);
+ }, [ message, onEditMessage ]);
+
const handleMouseEnter = useCallback(() => {
setIsHovered(true);
}, []);
@@ -334,6 +365,24 @@ const ChatMessage = ({
);
}
+ /**
+ * Renders the editing notice for which message is edited.
+ *
+ * @returns {React$Element<*>}
+ */
+ function _renderEditingNotice() {
+ return (
+ <div className = { classes.editingNotice }>
+ <span>{t('chat.editingMessage', 'Editing')}</span>
+ <span
+ className = { classes.cancelEdit }
+ onClick = { onCancelEdit }>
+ {t('chat.cancel', 'Cancel')}
+ </span>
+ </div>
+ );
+ }
+
/**
* Renders the reactions for the message.
*
@@ -400,6 +449,12 @@ const ChatMessage = ({
);
}, [ message?.reactions, isHovered, isReactionsOpen ]);
+ const canEdit = message.messageType === MESSAGE_TYPE_LOCAL
+ && !message.lobbyChat
+ && !message.isReaction
+ && !message.isFromVisitor
+ && !isFileMessage(message);
+
return (
<div
className = { cx(classes.chatMessageWrapper, className) }
@@ -411,12 +466,14 @@ const ChatMessage = ({
{!shouldDisplayMenuOnRight && (
<div className = { classes.optionsButtonContainer }>
{isHovered && <MessageMenu
+ canEdit = { canEdit }
displayName = { message.displayName }
enablePrivateChat = { Boolean(enablePrivateChat) }
isFileMessage = { isFileMessage(message) }
isFromVisitor = { message.isFromVisitor }
isLobbyMessage = { message.lobbyChat }
message = { message.message }
+ onEditMessage = { handleEditMessage }
participantId = { message.participantId } />}
</div>
)}
@@ -464,6 +521,11 @@ const ChatMessage = ({
</>
)}
</div>
+ {message.isEdited && (
+ <div className = { classes.editedLabel }>
+ {t('chat.edited', '(edited)')}
+ </div>
+ )}
{_renderTimestamp()}
</div>
</div>
@@ -483,18 +545,21 @@ const ChatMessage = ({
<div>
<div className = { classes.optionsButtonContainer }>
{isHovered && <MessageMenu
+ canEdit = { canEdit }
displayName = { message.displayName }
enablePrivateChat = { Boolean(enablePrivateChat) }
isFileMessage = { isFileMessage(message) }
isFromVisitor = { message.isFromVisitor }
isLobbyMessage = { message.lobbyChat }
message = { message.message }
+ onEditMessage = { handleEditMessage }
participantId = { message.participantId } />}
</div>
</div>
</div>
)}
</div>
+ {isEditing && _renderEditingNotice()}
</div>
);
};
diff --git a/react/features/chat/components/web/ChatMessageGroup.tsx b/react/features/chat/components/web/ChatMessageGroup.tsx
index 400c041f22..c98df6bacf 100644
--- a/react/features/chat/components/web/ChatMessageGroup.tsx
+++ b/react/features/chat/components/web/ChatMessageGroup.tsx
@@ -14,10 +14,19 @@ interface IProps {
*/
className: string;
+ editingMessage?: IMessage;
+
/**
* The messages to display as a group.
*/
messages: Array<IMessage>;
+
+ onCancelEdit?: () => void;
+
+ /**
+ * Callback invoked when the user wants to edit a message.
+ */
+ onEditMessage?: (message: IMessage) => void;
}
const useStyles = makeStyles()(theme => {
@@ -54,7 +63,7 @@ const useStyles = makeStyles()(theme => {
});
-const ChatMessageGroup = ({ className = '', messages }: IProps) => {
+const ChatMessageGroup = ({ className = '', editingMessage, messages, onCancelEdit, onEditMessage }: IProps) => {
const { classes } = useStyles();
const messagesLength = messages.length;
@@ -72,8 +81,11 @@ const ChatMessageGroup = ({ className = '', messages }: IProps) => {
{messages.map((message, i) => (
<ChatMessage
className = { className }
+ isEditing = { editingMessage?.messageId === message.messageId }
key = { i }
message = { message }
+ onCancelEdit = { onCancelEdit }
+ onEditMessage = { onEditMessage }
showDisplayName = { i === 0 }
showTimestamp = { i === messages.length - 1 } />
))}
diff --git a/react/features/chat/components/web/MessageContainer.tsx b/react/features/chat/components/web/MessageContainer.tsx
index 1bb4afdfc3..c2bf85b1db 100644
--- a/react/features/chat/components/web/MessageContainer.tsx
+++ b/react/features/chat/components/web/MessageContainer.tsx
@@ -12,12 +12,18 @@ import NewMessagesButton from './NewMessagesButton';
interface IProps {
+ editingMessage?: IMessage;
/**
* Whether the message container is currently visible to the user.
* Defaults to true when not provided.
*/
isVisible?: boolean;
messages: IMessage[];
+ onCancelEdit?: () => void;
+ /**
+ * Callback invoked when the user wants to edit a message.
+ */
+ onEditMessage?: (message: IMessage) => void;
}
interface IState {
@@ -117,8 +123,11 @@ export default class MessageContainer extends Component<IProps, IState> {
return (
<ChatMessageGroup
className = { messageType || MESSAGE_TYPE_REMOTE }
+ editingMessage = { this.props.editingMessage }
key = { index }
- messages = { messages } />
+ messages = { messages }
+ onCancelEdit = { this.props.onCancelEdit }
+ onEditMessage = { this.props.onEditMessage } />
);
});
diff --git a/react/features/chat/components/web/MessageMenu.tsx b/react/features/chat/components/web/MessageMenu.tsx
index 40a7ba3d49..5653888df1 100644
--- a/react/features/chat/components/web/MessageMenu.tsx
+++ b/react/features/chat/components/web/MessageMenu.tsx
@@ -15,6 +15,7 @@ import { handleLobbyChatInitialized, openChat } from '../../actions.web';
import logger from '../../logger';
export interface IProps {
+ canEdit?: boolean;
className?: string;
displayName?: string;
enablePrivateChat: boolean;
@@ -22,6 +23,7 @@ export interface IProps {
isFromVisitor?: boolean;
isLobbyMessage: boolean;
message: string;
+ onEditMessage?: () => void;
participantId: string;
}
@@ -62,7 +64,7 @@ const useStyles = makeStyles()(theme => {
};
});
-const MessageMenu = ({ message, participantId, isFromVisitor, isLobbyMessage, enablePrivateChat, displayName, isFileMessage }: IProps) => {
+const MessageMenu = ({ canEdit, message, participantId, isFromVisitor, isLobbyMessage, enablePrivateChat, displayName, isFileMessage, onEditMessage }: IProps) => {
const dispatch = useDispatch();
const { classes, cx } = useStyles();
const { t } = useTranslation();
@@ -75,7 +77,7 @@ const MessageMenu = ({ message, participantId, isFromVisitor, isLobbyMessage, en
const participant = useSelector((state: IReduxState) => getParticipantById(state, participantId));
// If no menu items will be shown, don't render the menu button.
- if (!enablePrivateChat && isFileMessage) {
+ if (!enablePrivateChat && isFileMessage && !canEdit) {
return null;
}
@@ -135,8 +137,20 @@ const MessageMenu = ({ message, participantId, isFromVisitor, isLobbyMessage, en
handleClose();
}, [ message ]);
+ const handleEditClick = useCallback(() => {
+ onEditMessage?.();
+ handleClose();
+ }, [ onEditMessage, handleClose ]);
+
const popoverContent = (
<div className = { classes.menuPanel }>
+ {canEdit && (
+ <div
+ className = { classes.menuItem }
+ onClick = { handleEditClick }>
+ {t('Edit')}
+ </div>
+ )}
{enablePrivateChat && (
<div
className = { classes.menuItem }
diff --git a/react/features/chat/constants.ts b/react/features/chat/constants.ts
index cb3eac50c4..459477f3be 100644
--- a/react/features/chat/constants.ts
+++ b/react/features/chat/constants.ts
@@ -74,3 +74,10 @@ export const TIMESTAMP_FORMAT = 'H:mm';
export const MESSAGE_TYPE_SYSTEM = 'system_chat_message';
export const OPTION_GROUPCHAT = 'groupchat';
+
+export const EDIT_CHAT_MESSAGE = 'editChat';
+
+/**
+ * Maximum number of pending edits are allowed.
+ */
+export const MAX_PENDING_EDITS = 200;
diff --git a/react/features/chat/functions.ts b/react/features/chat/functions.ts
index c6a12d3f9a..095d9accf4 100644
--- a/react/features/chat/functions.ts
+++ b/react/features/chat/functions.ts
@@ -21,8 +21,8 @@ import { isCCTabEnabled } from '../subtitles/functions.any';
import { VIDEO_SPACE_MIN_SIZE } from '../video-layout/constants';
import { IVisitorChatParticipant } from '../visitors/types';
-import { ChatTabs, MESSAGE_TYPE_ERROR, MESSAGE_TYPE_LOCAL, TIMESTAMP_FORMAT } from './constants';
-import { IMessage } from './types';
+import { ChatTabs, MAX_PENDING_EDITS, MESSAGE_TYPE_ERROR, MESSAGE_TYPE_LOCAL, TIMESTAMP_FORMAT } from './constants';
+import { IMessage, IPendingEdit, IPendingEditsMap } from './types';
/**
* An ASCII emoticon regexp array to find and replace old-style ASCII
@@ -395,6 +395,30 @@ export function isFileMessage(message: IMessage): boolean {
}
/**
+ * Inserts a pending edit into the map, evicting the oldest entry if the cap is exceeded.
+ *
+ * @param {IPendingEditsMap} pendingEdits - The current pending edits map.
+ * @param {string} messageId - The id of the message the edit targets.
+ * @param {IPendingEdit} edit - The pending edit to insert.
+ * @returns {IPendingEditsMap} The updated pending edits map.
+ */
+export function addPendingEdit(
+ pendingEdits: IPendingEditsMap,
+ messageId: string,
+ edit: IPendingEdit
+): IPendingEditsMap {
+ const next = { ...pendingEdits, [messageId]: edit };
+ const keys = Object.keys(next);
+
+ if (keys.length > MAX_PENDING_EDITS) {
+ // Object key order is insertion order for string keys in JS, so the first key is the oldest.
+ delete next[keys[0]];
+ }
+
+ return next;
+}
+
+/*
* Returns the current chat search query.
*
* @param {IReduxState} state - The redux state.
diff --git a/react/features/chat/middleware.ts b/react/features/chat/middleware.ts
index b6c0c40c39..fa32af9b3e 100644
--- a/react/features/chat/middleware.ts
+++ b/react/features/chat/middleware.ts
@@ -1,4 +1,5 @@
import { AnyAction } from 'redux';
+import { v4 as uuidv4 } from 'uuid';
import { IReduxState, IStore } from '../app/types';
import { APP_WILL_MOUNT, APP_WILL_UNMOUNT } from '../base/app/actionTypes';
@@ -45,6 +46,7 @@ import {
CLOSE_CHAT,
OPEN_CHAT,
SEND_MESSAGE,
+ SEND_MESSAGE_EDIT,
SEND_REACTION,
SET_FOCUSED_TAB
} from './actionTypes';
@@ -53,13 +55,16 @@ import {
addMessageReaction,
clearChatState,
closeChat,
+ editMessage,
notifyPrivateRecipientsChanged,
openChat,
setPrivateMessageRecipient
} from './actions';
import { ChatPrivacyDialog } from './components';
import {
+ CHAR_LIMIT,
ChatTabs,
+ EDIT_CHAT_MESSAGE,
INCOMING_MSG_SOUND_ID,
LOBBY_CHAT_MESSAGE,
MESSAGE_TYPE_ERROR,
@@ -77,6 +82,7 @@ import {
} from './functions';
import { INCOMING_MSG_SOUND_FILE } from './sounds';
import './subscriber';
+import { IMessage } from './types';
/**
* Timeout for when to show the privacy notice after a private message was received.
@@ -142,13 +148,25 @@ MiddlewareRegistry.register(store => next => action => {
case ENDPOINT_MESSAGE_RECEIVED: {
const state = store.getState();
+ const { participant, data } = action;
+
+ if (data?.type === EDIT_CHAT_MESSAGE && data.messageId && data.message) {
+ const trimmedMessage = String(data.message).slice(0, CHAR_LIMIT);
+
+ store.dispatch(editMessage({
+ messageId: data.messageId,
+ message: trimmedMessage,
+ editedAt: data.editedAt,
+ participantId: participant.getId()
+ }));
+
+ break;
+ }
if (!isReactionsEnabled(state)) {
return next(action);
}
- const { participant, data } = action;
-
if (data?.name === ENDPOINT_REACTION_NAME) {
// Only accept known reaction keys, skip duplicates and keep just 3.
const reactions = Array.from(new Set(Array.isArray(data.reactions) ? data.reactions : []))
@@ -243,7 +261,42 @@ MiddlewareRegistry.register(store => next => action => {
break;
}
- case PARTICIPANT_JOINED:
+ case PARTICIPANT_JOINED: {
+ const result = next(action);
+
+ const state = store.getState();
+ const conference = getCurrentConference(state);
+ const local = getLocalParticipant(state);
+
+ if (conference && action.participant?.id && local?.id) {
+ const editedMessages = state['features/chat'].messages.filter(
+ (m: IMessage) =>
+ m.isEdited
+ && !m.privateMessage
+ && m.messageType === MESSAGE_TYPE_LOCAL
+ );
+
+ editedMessages.forEach(message => {
+ conference.sendPrivateTextMessage(
+ action.participant.id,
+ JSON.stringify({
+ type: EDIT_CHAT_MESSAGE,
+ messageId: message.messageId,
+ message: message.message,
+ editedAt: message.editedAt
+ }),
+ 'json-message'
+ );
+ });
+ }
+
+ if (_shouldNotifyPrivateRecipientsChanged(store, action)) {
+ dispatch(notifyPrivateRecipientsChanged());
+ }
+
+ return result;
+ }
+
case PARTICIPANT_LEFT:
case PARTICIPANT_UPDATED: {
if (action.type === PARTICIPANT_LEFT) {
@@ -304,11 +357,60 @@ MiddlewareRegistry.register(store => next => action => {
}, lobbyMessageRecipient.id);
_persistSentPrivateMessage(store, lobbyMessageRecipient, action.message, true);
} else if (privateMessageRecipient) {
- conference.sendPrivateTextMessage(privateMessageRecipient.id, action.message, 'body', isVisitorChatParticipant(privateMessageRecipient));
- _persistSentPrivateMessage(store, privateMessageRecipient, action.message);
+ const messageId = uuidv4();
+
+ conference.sendPrivateTextMessage(privateMessageRecipient.id, action.message, 'body', isVisitorChatParticipant(privateMessageRecipient), undefined, messageId);
+ _persistSentPrivateMessage(store, privateMessageRecipient, action.message, false, messageId);
+ } else {
+ const messageId = uuidv4();
+
+ conference.sendTextMessage(action.message, undefined, undefined, messageId);
+ }
+ }
+ break;
+ }
+
+ case SEND_MESSAGE_EDIT: {
+ const state = store.getState();
+ const conference = getCurrentConference(state);
+ const editedAt = Date.now();
+ const messageToEdit = state['features/chat'].messages.find(
+ message => message.messageId === action.messageId
+ );
+
+ if (
+ conference
+ && localParticipant?.id
+ && messageToEdit
+ && messageToEdit.participantId === localParticipant.id
+ && messageToEdit.messageType === MESSAGE_TYPE_LOCAL
+ && !messageToEdit.isFromVisitor
+ ) {
+ const trimmedMessage = String(action.message).trim().slice(0, CHAR_LIMIT);
+
+ const payload = {
+ type: EDIT_CHAT_MESSAGE,
+ messageId: action.messageId,
+ message: trimmedMessage,
+ editedAt
+ };
+
+ if (messageToEdit.privateMessage && messageToEdit.recipientId) {
+ conference.sendPrivateTextMessage(
+ messageToEdit.recipientId,
+ JSON.stringify(payload),
+ 'json-message'
+ );
} else {
- conference.sendTextMessage(action.message);
+ conference.sendTextMessage(JSON.stringify(payload), 'json-message');
}
+
+ store.dispatch(editMessage({
+ messageId: action.messageId,
+ message: trimmedMessage,
+ editedAt,
+ participantId: localParticipant.id
+ }));
}
break;
}
@@ -450,6 +552,25 @@ function _addChatMsgListener(conference: IJitsiConference, store: IStore) {
JitsiConferenceEvents.PRIVATE_MESSAGE_RECEIVED,
(participantId: string, message: string, timestamp: number, messageId: string, displayName?: string,
isFromVisitor?: boolean, replyToId?: string) => {
+ try {
+ const data = JSON.parse(message);
+
+ if (data?.type === EDIT_CHAT_MESSAGE && data.messageId && data.message) {
+ const trimmedMessage = String(data.message).slice(0, CHAR_LIMIT);
+
+ store.dispatch(editMessage({
+ messageId: data.messageId,
+ message: trimmedMessage,
+ editedAt: data.editedAt,
+ participantId
+ }));
+
+ // Don't treat edit payload as a new chat message.
+ return;
+ }
+ } catch (e) {
+ // Normal private message.
+ }
_onConferenceMessageReceived(store, {
participantId,
message,
@@ -726,10 +847,11 @@ interface IRecipient {
* @param {IRecipient} recipient - The recipient the private message was sent to.
* @param {string} message - The sent message.
* @param {boolean} isLobbyPrivateMessage - Is a lobby message.
+ * @param {string} messageId - The unique identifier of the private message used for message editing and tracking.
* @returns {void}
*/
function _persistSentPrivateMessage({ dispatch, getState }: IStore, recipient: IRecipient,
- message: string, isLobbyPrivateMessage = false) {
+ message: string, isLobbyPrivateMessage = false, messageId?: string) {
const state = getState();
const localParticipant = getLocalParticipant(state);
@@ -752,9 +874,11 @@ function _persistSentPrivateMessage({ dispatch, getState }: IStore, recipient: I
participantId: localParticipant.id,
messageType: MESSAGE_TYPE_LOCAL,
message,
+ messageId,
privateMessage: !isLobbyPrivateMessage,
lobbyChat: isLobbyPrivateMessage,
recipient: recipientName,
+ recipientId: recipient.id,
sentToVisitor: recipient.isVisitor,
timestamp: Date.now()
}));
diff --git a/react/features/chat/reducer.ts b/react/features/chat/reducer.ts
index 1ace41baf3..909a61b033 100644
--- a/react/features/chat/reducer.ts
+++ b/react/features/chat/reducer.ts
@@ -25,13 +25,15 @@ import {
SET_USER_CHAT_WIDTH
} from './actionTypes';
import { CHAT_SIZE, ChatTabs } from './constants';
-import { IMessage } from './types';
+import { addPendingEdit } from './functions';
+import { IMessage, IPendingEditsMap } from './types';
const DEFAULT_STATE = {
groupChatWithPermissions: false,
isOpen: false,
messages: [],
notifyPrivateRecipientsChangedTimestamp: undefined,
+ pendingEdits: {},
reactions: {},
unreadMessagesCount: 0,
unreadFilesCount: 0,
@@ -61,6 +63,7 @@ export interface IChatState {
} | ILocalParticipant;
messages: IMessage[];
notifyPrivateRecipientsChangedTimestamp?: number;
+ pendingEdits: IPendingEditsMap;
privateMessageRecipient?: IParticipant | IVisitorChatParticipant;
searchMatchIndex: number;
searchQuery: string;
@@ -77,11 +80,13 @@ ReducerRegistry.register<IChatState>('features/chat', (state = DEFAULT_STATE, ac
case ADD_MESSAGE: {
const newMessage: IMessage = {
displayName: action.displayName,
+ editedAt: action.editedAt,
error: action.error,
fileMetadata: action.fileMetadata,
isFromGuest: Boolean(action.isFromGuest),
isFromVisitor: Boolean(action.isFromVisitor),
participantId: action.participantId,
+ isEdited: Boolean(action.isEdited),
isReaction: action.isReaction,
messageId: action.messageId,
messageType: action.messageType,
@@ -90,28 +95,53 @@ ReducerRegistry.register<IChatState>('features/chat', (state = DEFAULT_STATE, ac
privateMessage: action.privateMessage,
lobbyChat: action.lobbyChat,
recipient: action.recipient,
+ recipientId: action.recipientId,
replyToMessageId: action.replyToMessageId,
sentToVisitor: Boolean(action.sentToVisitor),
timestamp: action.timestamp
};
+ const pendingEdit = action.messageId ? state.pendingEdits[action.messageId] : undefined;
+
+ // only apply a cached pending edit if its claimed author matches
+ // the author of the message that actually arrived. Prevents a forged/mismatched
+ // edit that was queued for a not-yet-seen messageId from silently overwriting
+ // someone else's message once it shows up.
+ const pendingEditValid = pendingEdit?.participantId === action.participantId;
+
+ const finalMessage = pendingEdit && pendingEditValid
+ ? {
+ ...newMessage,
+ message: pendingEdit.message,
+ isEdited: true,
+ editedAt: pendingEdit.editedAt
+ }
+ : newMessage;
+
// React native, unlike web, needs a reverse sorted message list.
const messages = navigator.product === 'ReactNative'
? [
- newMessage,
+ finalMessage,
...state.messages
]
: [
...state.messages,
- newMessage
+ finalMessage
];
+ const pendingEdits = { ...state.pendingEdits };
+
+ if (pendingEdit && pendingEditValid && action.messageId) {
+ delete pendingEdits[action.messageId];
+ }
+
return {
...state,
lastReadMessage:
- action.hasRead ? newMessage : state.lastReadMessage,
+ action.hasRead ? finalMessage : state.lastReadMessage,
unreadMessagesCount: state.focusedTab !== ChatTabs.CHAT ? state.unreadMessagesCount + 1 : state.unreadMessagesCount,
- messages
+ messages,
+ pendingEdits
};
}
@@ -162,20 +192,47 @@ ReducerRegistry.register<IChatState>('features/chat', (state = DEFAULT_STATE, ac
};
case EDIT_MESSAGE: {
- let found = false;
const newMessage = action.message;
+ let messageExists = false;
+ let applied = false;
+
const messages = state.messages.map(m => {
if (m.messageId === newMessage.messageId) {
- found = true;
+ messageExists = true;
- return newMessage;
+ // SECURITY: participantId must be present AND match the original
+ // author. A missing participantId must fail closed, not open.
+ if (newMessage.participantId && m.participantId !== newMessage.participantId) {
+ return m;
+ }
+
+ applied = true;
+
+ return {
+ ...m,
+ message: newMessage.message,
+ isEdited: true,
+ editedAt: newMessage.editedAt
+ };
}
return m;
});
- // no change
- if (!found) {
+ // Message hasn't arrived yet — cache it as a pending edit so it can be
+ // applied later, once ADD_MESSAGE validates authorship.
+ if (!messageExists) {
+ return {
+ ...state,
+ pendingEdits: addPendingEdit(state.pendingEdits, newMessage.messageId, {
+ message: newMessage.message,
+ editedAt: newMessage.editedAt,
+ participantId: newMessage.participantId
+ })
+ };
+ }
+
+ if (!applied) {
return state;
}
diff --git a/react/features/chat/types.ts b/react/features/chat/types.ts
index f82709e6ed..783e080441 100644
--- a/react/features/chat/types.ts
+++ b/react/features/chat/types.ts
@@ -16,8 +16,10 @@ export type ChatMessageType =
export interface IMessage {
displayName: string;
+ editedAt?: number;
error?: unknown;
fileMetadata?: IFileMetadata;
+ isEdited?: Boolean;
isFromGuest?: boolean;
isFromVisitor?: boolean;
isReaction: boolean;
@@ -29,6 +31,7 @@ export interface IMessage {
privateMessage: boolean;
reactions: Map<string, Set<string>>;
recipient: string;
+ recipientId?: string;
/**
* When set, XMPP message id of the message this one replies to (XEP-0461), from lib-jitsi-meet.
*/
@@ -109,3 +112,19 @@ export interface IChatMessageProps extends WithTranslation {
*/
showTimestamp: boolean;
}
+
+/**
+ * The shape of a single cached pending edit, keyed by messageId in Redux state.
+ */
+export interface IPendingEdit {
+ editedAt: number;
+ message: string;
+ participantId?: string;
+}
+
+/**
+ * The shape of the pendingEdits map in Redux state.
+ */
+export interface IPendingEditsMap {
+ [messageId: string]: IPendingEdit;
+}