feat: forward modal swap & forward to same room

This commit is contained in:
7w1 committed 2026-05-13 19:17:45 -05:00
1 parent ac2c7f1305
commit b2adebdc70
4 files changed
+277 -244

No files matched your search

@@ -14,10 +14,14 @@ import { MessageReadReceiptInternal } from './MessageReadRecipts';
export function GlobalModalManager() {
const [modal, setModal] = useAtom(modalAtom);
if (!modal) return null;
const close = () => setModal(null);
if (modal?.type === ModalType.Forward) {
return <MessageForwardInternal room={modal.room} mEvent={modal.mEvent} onClose={close} />;
}
if (!modal) return null;
return (
<Overlay open backdrop={<OverlayBackdrop />}>
<OverlayCenter>
@@ -42,12 +46,6 @@ export function GlobalModalManager() {
</Box>
)}
{modal.type === ModalType.Forward && (
<Box>
<MessageForwardInternal room={modal.room} mEvent={modal.mEvent} onClose={close} />
</Box>
)}
{modal.type === ModalType.Source && (
<Modal variant="Surface" size="300">
<MessageSourceInternal room={modal.room} mEvent={modal.mEvent} onClose={close} />
@@ -2,23 +2,10 @@
import { useMatrixClient } from '$hooks/useMatrixClient';
import { modalAtom, ModalType } from '$state/modal';
import {
Box,
Button,
Dialog,
Header,
Icon,
Icons,
IconButton,
MenuItem,
Text,
config,
Scroll,
as,
} from 'folds';
import { Icon, Icons, MenuItem, Text, as } from 'folds';
import { useAtomValue, useSetAtom } from 'jotai';
import type { MatrixEvent, Room } from '$types/matrix-sdk';
import { useEffect, useMemo, useState } from 'react';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { allRoomsAtom } from '$state/room-list/roomList';
import { useAllJoinedRoomsSet, useGetRoom } from '$hooks/useGetRoom';
import { factoryRoomIdByActivity } from '$utils/sort';
@@ -28,7 +15,7 @@ import { createDebugLogger } from '$utils/debugLogger';
import * as Sentry from '@sentry/react';
import { isRoomPrivate } from '$utils/roomVisibility';
import * as prefix from '$unstable/prefixes';
import { RoomSearchModal } from '$features/search';
const debugLog = createDebugLogger('MessageForward');
// Message forwarding component
@@ -106,11 +93,9 @@ export function MessageForwardInternal({
}: Readonly<MessageForwardInternalProps>) {
const mx = useMatrixClient();
const [isTargetSelected, setIsTargetSelected] = useState(false);
const [isForwardSuccess, setIsForwardSuccess] = useState(false);
const [isForwarding, setIsForwarding] = useState(false);
const [forwardError, setForwardError] = useState<string | null>(null);
const [targetRoomId, setTargetRoomId] = useState<string | null>(null);
const allRooms = useAtomValue(allRoomsAtom);
const allJoinedRooms = useAllJoinedRoomsSet();
const getRoom = useGetRoom(allJoinedRooms);
@@ -118,13 +103,12 @@ export function MessageForwardInternal({
const forwardTargets = useMemo(
() =>
allRooms
.filter((id) => id !== room.roomId)
.filter((id) => {
const target = getRoom(id);
return !!target && !target.isSpaceRoom() && target.maySendMessage();
})
.sort(factoryRoomIdByActivity(mx)),
[allRooms, room.roomId, getRoom, mx]
[allRooms, getRoom, mx]
);
useEffect(() => {
@@ -136,203 +120,156 @@ export function MessageForwardInternal({
}
}, [isForwardSuccess, onClose]);
// actually forward the message to the selected room
const handleForwardClick = () => {
setIsForwarding(true);
if (!targetRoomId) {
setIsForwarding(false);
return;
}
const forwardToRoom = useCallback(
(targetRoomId: string) => {
setIsForwarding(true);
setForwardError(null);
const targetRoom = getRoom(targetRoomId);
const eventId = mEvent.getId();
if (!targetRoom || !eventId) {
setIsForwarding(false);
return;
}
type SendEventType = Parameters<typeof mx.sendEvent>[2];
type SendEventContent = Parameters<typeof mx.sendEvent>[3];
const eventType = mEvent.getType() as SendEventType;
const originalContent = mEvent.getContent();
const isTextMessage = originalContent.msgtype === 'm.text';
// using reference relation to indicate that this is a forwarded message,
// which allows clients to display it as such
const originalBody = typeof originalContent.body === 'string' ? originalContent.body : '';
const originalFormattedBody =
originalContent.format === 'org.matrix.custom.html' &&
typeof originalContent.formatted_body === 'string'
? originalContent.formatted_body
: undefined;
const bodyModifText = `(Forwarded message from ${
isRoomPrivate(mx, room) ? 'a private room' : (getRoom(room.roomId)?.name ?? 'a room')
})`;
let newBodyPlain = '';
let newBodyHtml = '';
// transform if msgtype is m.text
if (isTextMessage) {
const quotedBody = originalBody
.split('\n')
.map((line) => `> ${line}`)
.join('\n');
newBodyPlain = originalBody.length > 0 ? `${bodyModifText}\n\n${quotedBody}` : bodyModifText;
const safeHtml =
originalFormattedBody === undefined
? sanitizeText(originalBody).replaceAll('\n', '<br>')
: sanitizeCustomHtml(originalFormattedBody);
newBodyHtml =
`<div data-forward-marker>` +
`<p>${sanitizeText(bodyModifText)}</p>` +
`<blockquote>${safeHtml}</blockquote>` +
`</div>`;
}
// the quoted body
const forwardedTextContent = isTextMessage
? {
body: newBodyPlain,
format: 'org.matrix.custom.html',
formatted_body: newBodyHtml,
}
: {};
const baseContent = { ...mEvent.getContent() };
delete baseContent['m.relates_to']; // remove relations from the forwarded message
delete baseContent['m.mentions']; // remove mentions from forwarded message
delete baseContent[prefix.MATRIX_UNSTABLE_PER_MESSAGE_PROFILE_PROPERTY_NAME]; // remove per-message profile as that could confuse clients in the target room
let content;
// handle privacy stuff
if (isRoomPrivate(mx, room)) {
// if the message is from a private room, we should strip any media or mentions to avoid leaking information to the target room
// we can still include the original message content in the body of the message, so we'll just use a fallback text/plain content with the original message body
content = {
...baseContent,
...forwardedTextContent,
[prefix.MATRIX_SABLE_UNSTABLE_MESSAGE_FORWARD_META_PROPERTY_NAME]: {
v: 1,
is_forwarded: true,
original_timestamp: mEvent.getTs(),
original_event_private: true,
} satisfies ForwardMeta,
[prefix.MATRIX_UNSTABLE_MESSAGE_FORWARD_META_PROPERTY_NAME]: {
origin_server_ts: mEvent.getTs(),
} satisfies MSC2723ForwardMeta,
};
} else {
content = {
...baseContent,
...forwardedTextContent,
[prefix.MATRIX_SABLE_UNSTABLE_MESSAGE_FORWARD_META_PROPERTY_NAME]: {
v: 1,
is_forwarded: true,
original_timestamp: mEvent.getTs(),
original_room_id: room.roomId,
original_event_id: eventId,
original_event_private: false,
} satisfies ForwardMeta,
[prefix.MATRIX_UNSTABLE_MESSAGE_FORWARD_META_PROPERTY_NAME]: {
event_id: eventId,
room_id: room.roomId,
origin_server_ts: mEvent.getTs(),
} satisfies MSC2723ForwardMeta,
};
}
const msgtype = originalContent.msgtype ?? 'unknown';
debugLog.info('ui', 'Forwarding message', {
sourceRoomId: room.roomId,
targetRoomId: targetRoom.roomId,
msgtype,
isPrivate: isRoomPrivate(mx, room),
});
Sentry.metrics.count('sable.message.forward.attempt', 1, { attributes: { msgtype } });
mx.sendEvent(targetRoom.roomId, null, eventType, content as unknown as SendEventContent)
.then(() => {
debugLog.info('ui', 'Message forwarded successfully', {
sourceRoomId: room.roomId,
targetRoomId: targetRoom.roomId,
});
Sentry.metrics.count('sable.message.forward.success', 1);
setIsForwardSuccess(true);
})
.catch((err: unknown) => {
const message = err instanceof Error ? err.message : String(err);
debugLog.error('ui', 'Message forward failed', {
sourceRoomId: room.roomId,
targetRoomId: targetRoom.roomId,
error: message,
});
Sentry.metrics.count('sable.message.forward.error', 1);
const targetRoom = getRoom(targetRoomId);
const eventId = mEvent.getId();
if (!targetRoom || !eventId) {
setIsForwarding(false);
setIsForwardSuccess(false);
setForwardError(message);
});
};
return;
}
return (
<Dialog variant="Surface">
<Header
style={{
padding: `0 ${config.space.S200} 0 ${config.space.S400}`,
borderBottomWidth: config.borderWidth.B300,
}}
variant="Surface"
size="500"
>
<Box grow="Yes">
<Text size="H4">Forward Message</Text>
</Box>
<IconButton size="300" onClick={onClose} radii="300">
<Icon src={Icons.Cross} />
</IconButton>
</Header>
<Box direction="Column" style={{ height: '300px' }}>
<Scroll hideTrack>
<Box direction="Column" style={{ padding: config.space.S300 }}>
{forwardTargets.map((roomId) => {
const target = getRoom(roomId);
if (!target) return null;
return (
<MenuItem
key={roomId}
data-room-id={roomId}
onClick={() => {
setIsTargetSelected(true);
setTargetRoomId(roomId);
}}
variant={targetRoomId === roomId ? 'Success' : 'Surface'}
aria-pressed={targetRoomId === roomId}
size="400"
radii="400"
>
<Text truncate>{target.name}</Text>
</MenuItem>
);
})}
</Box>
</Scroll>
{isTargetSelected && targetRoomId && (
<Button
style={{ margin: config.space.S300 }}
onClick={handleForwardClick}
disabled={isForwarding}
>
<Text>Forward to {getRoom(targetRoomId)?.name}</Text>
</Button>
)}
{forwardError && (
<Text size="T300" color="Critical600" style={{ margin: config.space.S300 }}>
Failed to forward: {forwardError}
</Text>
)}
</Box>
</Dialog>
type SendEventType = Parameters<typeof mx.sendEvent>[2];
type SendEventContent = Parameters<typeof mx.sendEvent>[3];
const eventType = mEvent.getType() as SendEventType;
const originalContent = mEvent.getContent();
const isTextMessage = originalContent.msgtype === 'm.text';
const originalBody = typeof originalContent.body === 'string' ? originalContent.body : '';
const originalFormattedBody =
originalContent.format === 'org.matrix.custom.html' &&
typeof originalContent.formatted_body === 'string'
? originalContent.formatted_body
: undefined;
const bodyModifText = `(Forwarded message from ${
isRoomPrivate(mx, room) ? 'a private room' : (getRoom(room.roomId)?.name ?? 'a room')
})`;
let newBodyPlain = '';
let newBodyHtml = '';
// transform if msgtype is m.text
if (isTextMessage) {
const quotedBody = originalBody
.split('\n')
.map((line) => `> ${line}`)
.join('\n');
newBodyPlain =
originalBody.length > 0 ? `${bodyModifText}\n\n${quotedBody}` : bodyModifText;
const safeHtml =
originalFormattedBody === undefined
? sanitizeText(originalBody).replaceAll('\n', '<br>')
: sanitizeCustomHtml(originalFormattedBody);
newBodyHtml =
`<div data-forward-marker>` +
`<p>${sanitizeText(bodyModifText)}</p>` +
`<blockquote>${safeHtml}</blockquote>` +
`</div>`;
}
// the quoted body
const forwardedTextContent = isTextMessage
? {
body: newBodyPlain,
format: 'org.matrix.custom.html',
formatted_body: newBodyHtml,
}
: {};
const baseContent = { ...mEvent.getContent() };
delete baseContent['m.relates_to']; // remove relations from the forwarded message
delete baseContent['m.mentions']; // remove mentions from forwarded message
delete baseContent[prefix.MATRIX_UNSTABLE_PER_MESSAGE_PROFILE_PROPERTY_NAME]; // remove per-message profile as that could confuse clients in the target room
let content;
// handle privacy stuff
if (isRoomPrivate(mx, room)) {
// if the message is from a private room, we should strip any media or mentions to avoid leaking information to the target room
// we can still include the original message content in the body of the message, so we'll just use a fallback text/plain content with the original message body
content = {
...baseContent,
...forwardedTextContent,
[prefix.MATRIX_SABLE_UNSTABLE_MESSAGE_FORWARD_META_PROPERTY_NAME]: {
v: 1,
is_forwarded: true,
original_timestamp: mEvent.getTs(),
original_event_private: true,
} satisfies ForwardMeta,
[prefix.MATRIX_UNSTABLE_MESSAGE_FORWARD_META_PROPERTY_NAME]: {
origin_server_ts: mEvent.getTs(),
} satisfies MSC2723ForwardMeta,
};
} else {
content = {
...baseContent,
...forwardedTextContent,
[prefix.MATRIX_SABLE_UNSTABLE_MESSAGE_FORWARD_META_PROPERTY_NAME]: {
v: 1,
is_forwarded: true,
original_timestamp: mEvent.getTs(),
original_room_id: room.roomId,
original_event_id: eventId,
original_event_private: false,
} satisfies ForwardMeta,
[prefix.MATRIX_UNSTABLE_MESSAGE_FORWARD_META_PROPERTY_NAME]: {
event_id: eventId,
room_id: room.roomId,
origin_server_ts: mEvent.getTs(),
} satisfies MSC2723ForwardMeta,
};
}
const msgtype = originalContent.msgtype ?? 'unknown';
debugLog.info('ui', 'Forwarding message', {
sourceRoomId: room.roomId,
targetRoomId: targetRoom.roomId,
msgtype,
isPrivate: isRoomPrivate(mx, room),
});
Sentry.metrics.count('sable.message.forward.attempt', 1, { attributes: { msgtype } });
mx.sendEvent(targetRoom.roomId, null, eventType, content as unknown as SendEventContent)
.then(() => {
debugLog.info('ui', 'Message forwarded successfully', {
sourceRoomId: room.roomId,
targetRoomId: targetRoom.roomId,
});
Sentry.metrics.count('sable.message.forward.success', 1);
setIsForwardSuccess(true);
})
.catch((err: unknown) => {
const message = err instanceof Error ? err.message : String(err);
debugLog.error('ui', 'Message forward failed', {
sourceRoomId: room.roomId,
targetRoomId: targetRoom.roomId,
error: message,
});
Sentry.metrics.count('sable.message.forward.error', 1);
setIsForwarding(false);
setIsForwardSuccess(false);
setForwardError(message);
});
},
[getRoom, mEvent, mx, room]
);
const pickRoom = useMemo(
() => ({
title: 'Forward message',
eligibleRoomIds: forwardTargets,
onPickRoom: (roomId: string) => {
forwardToRoom(roomId);
},
errorMessage: forwardError ? `Failed to forward: ${forwardError}` : null,
busy: isForwarding || isForwardSuccess,
}),
[forwardError, forwardTargets, forwardToRoom, isForwarding, isForwardSuccess]
);
return <RoomSearchModal requestClose={onClose} pickRoom={pickRoom} />;
}
type MessageForwardItemProps = {
+14 -5
View File
@@ -633,12 +633,18 @@ function MessageInternal(
const mentionClickHandler = useMentionClickHandler(room.roomId);
const forwardedNotice = useMemo(() => {
const isSameRoomForward = (originalRoomId: string | undefined) =>
originalRoomId !== undefined && originalRoomId === room.roomId;
if (messageForwardedProps?.isForwarded) {
const originalRoomId = messageForwardedProps.originalRoomId;
return {
label: messageForwardedProps.originalEventPrivate
? 'Forwarded private message'
: 'Forwarded from another room',
roomId: messageForwardedProps.originalRoomId,
: isSameRoomForward(originalRoomId)
? 'Forwarded from earlier in this room'
: 'Forwarded from another room',
roomId: originalRoomId,
eventId: messageForwardedProps.originalEventId,
ts: messageForwardedProps.originalTimestamp ?? 0,
showLink: !messageForwardedProps.originalEventPrivate,
@@ -646,9 +652,12 @@ function MessageInternal(
}
if (msc2723ForwardedMessageProps) {
const originalRoomId = msc2723ForwardedMessageProps.room_id;
return {
label: 'Forwarded from another room',
roomId: msc2723ForwardedMessageProps.room_id,
label: isSameRoomForward(originalRoomId)
? 'Forwarded from earlier in this room'
: 'Forwarded from another room',
roomId: originalRoomId,
eventId: msc2723ForwardedMessageProps.event_id,
ts: msc2723ForwardedMessageProps.origin_server_ts ?? 0,
showLink: true,
@@ -656,7 +665,7 @@ function MessageInternal(
}
return null;
}, [messageForwardedProps, msc2723ForwardedMessageProps]);
}, [messageForwardedProps, msc2723ForwardedMessageProps, room.roomId]);
const handleResendClick: MouseEventHandler<HTMLButtonElement> = useCallback(
(evt) => {
+107 -18
View File
@@ -4,6 +4,7 @@ import {
Box,
config,
Icon,
IconButton,
Icons,
Input,
Line,
@@ -122,10 +123,20 @@ const SEARCH_OPTIONS: UseAsyncSearchOptions = {
},
};
type SearchProps = {
requestClose: () => void;
export type RoomSearchPickRoomConfig = {
title: string;
eligibleRoomIds: readonly string[];
onPickRoom: (roomId: string) => void;
errorMessage?: string | null;
busy?: boolean;
};
export function Search({ requestClose }: SearchProps) {
export type RoomSearchModalProps = {
requestClose: () => void;
pickRoom?: RoomSearchPickRoomConfig;
};
export function RoomSearchModal({ requestClose, pickRoom }: RoomSearchModalProps) {
const mx = useMatrixClient();
const useAuthentication = useMediaAuthentication();
const scrollRef = useRef<HTMLDivElement>(null);
@@ -145,8 +156,23 @@ export function Search({ requestClose }: SearchProps) {
const spaces = useSpaces(mx, allRoomsAtom);
const directs = useDirects(mx, allRoomsAtom, mDirects);
const topActiveRooms = useTopActiveRooms(searchRoomType, rooms, directs, spaces);
const targetRooms = useSearchTargetRooms(searchRoomType, rooms, directs, spaces);
const eligibleSet = useMemo(
() => (pickRoom ? new Set(pickRoom.eligibleRoomIds) : null),
[pickRoom]
);
const rawTopActiveRooms = useTopActiveRooms(searchRoomType, rooms, directs, spaces);
const rawTargetRooms = useSearchTargetRooms(searchRoomType, rooms, directs, spaces);
const topActiveRooms = useMemo(() => {
if (!eligibleSet) return rawTopActiveRooms;
return rawTopActiveRooms.filter((id) => eligibleSet.has(id));
}, [eligibleSet, rawTopActiveRooms]);
const targetRooms = useMemo(() => {
if (!eligibleSet) return rawTargetRooms;
return rawTargetRooms.filter((id) => eligibleSet.has(id));
}, [eligibleSet, rawTargetRooms]);
const getTargetStr: SearchItemStrGetter<string> = useCallback(
(roomId: string) => {
@@ -181,7 +207,12 @@ export function Search({ requestClose }: SearchProps) {
? makeHighlightRegex(result.query.split(' '))
: undefined;
const openRoomId = (roomId: string, isSpace: boolean) => {
const handleActivateRoom = (roomId: string, isSpace: boolean) => {
if (pickRoom) {
if (pickRoom.busy) return;
pickRoom.onPickRoom(roomId);
return;
}
if (isSpace) navigateSpace(roomId);
else navigateRoom(roomId);
requestClose();
@@ -211,7 +242,7 @@ export function Search({ requestClose }: SearchProps) {
const handleInputKeyDown: KeyboardEventHandler<HTMLInputElement> = (evt) => {
const roomId = roomsToRender[listFocus.index];
if (isKeyHotkey('enter', evt) && roomId) {
openRoomId(roomId, spaces.includes(roomId));
handleActivateRoom(roomId, spaces.includes(roomId));
return;
}
if (isKeyHotkey('arrowdown', evt)) {
@@ -230,7 +261,7 @@ export function Search({ requestClose }: SearchProps) {
const roomId = target.getAttribute('data-room-id');
const isSpace = target.getAttribute('data-space') === 'true';
if (!roomId) return;
openRoomId(roomId, isSpace);
handleActivateRoom(roomId, isSpace);
};
useEffect(() => {
@@ -261,6 +292,35 @@ export function Search({ requestClose }: SearchProps) {
}}
>
<Modal size="400" style={{ maxHeight: toRem(400), borderRadius: config.radii.R500 }}>
{pickRoom && (
<Box
shrink="No"
direction="Row"
alignItems="Center"
justifyContent="SpaceBetween"
style={{
padding: `${config.space.S400} ${config.space.S400} ${config.space.S200}`,
}}
>
<Text size="H4">{pickRoom.title}</Text>
<IconButton
size="300"
onClick={requestClose}
radii="300"
aria-label="Close"
disabled={pickRoom.busy}
>
<Icon src={Icons.Cross} />
</IconButton>
</Box>
)}
{pickRoom?.errorMessage ? (
<Box shrink="No" style={{ padding: `0 ${config.space.S400} ${config.space.S200}` }}>
<Text size="T200" color="Critical600">
{pickRoom.errorMessage}
</Text>
</Box>
) : null}
<Box
shrink="No"
style={{ padding: config.space.S400, paddingBottom: 0 }}
@@ -272,10 +332,11 @@ export function Search({ requestClose }: SearchProps) {
variant="Background"
radii="400"
outlined
placeholder="Search"
placeholder={pickRoom ? 'Search rooms' : 'Search'}
before={<Icon size="200" src={Icons.Search} />}
onChange={handleInputChange}
onKeyDown={handleInputKeyDown}
disabled={pickRoom?.busy}
/>
</Box>
<Box grow="Yes">
@@ -289,12 +350,26 @@ export function Search({ requestClose }: SearchProps) {
gap="100"
>
<Text size="H6" align="Center">
{result ? 'No Match Found' : `No Rooms'}`}
{pickRoom
? result
? 'No Match Found'
: pickRoom.eligibleRoomIds.length === 0
? 'No rooms to forward to'
: 'No rooms match this filter'
: result
? 'No Match Found'
: 'No Rooms'}
</Text>
<Text size="T200" align="Center">
{result
? `No match found for "${result.query}".`
: `You do not have any Rooms to display yet.`}
{pickRoom
? result
? `No match found for "${result.query}".`
: pickRoom.eligibleRoomIds.length === 0
? 'You cannot send messages in any joined room yet.'
: 'Try another search, or use # for group rooms and @ for direct messages.'
: result
? `No match found for "${result.query}".`
: 'You do not have any Rooms to display yet.'}
</Text>
</Box>
)}
@@ -335,6 +410,7 @@ export function Search({ requestClose }: SearchProps) {
data-room-id={roomId}
data-space={room.isSpaceRoom()}
onClick={handleRoomClick}
disabled={pickRoom?.busy}
variant={listFocus.index === index ? 'Primary' : 'Surface'}
aria-pressed={listFocus.index === index}
radii="400"
@@ -417,10 +493,19 @@ export function Search({ requestClose }: SearchProps) {
<Line size="300" />
<Box shrink="No" justifyContent="Center" style={{ padding: config.space.S200 }}>
<Text size="T200" priority="300">
Type <b>#</b> for rooms, <b>@</b> for DMs and <b>*</b> for spaces. Hotkey:{' '}
<b>{isMacOS() ? KeySymbol.Command : 'Ctrl'} + k</b>
{' / '}
<b>{isMacOS() ? KeySymbol.Command : 'Ctrl'} + f</b>
{pickRoom ? (
<>
Type <b>#</b> for rooms and <b>@</b> for direct messages. Choose a room to
forward this message.
</>
) : (
<>
Type <b>#</b> for rooms, <b>@</b> for DMs and <b>*</b> for spaces. Hotkey:{' '}
<b>{isMacOS() ? KeySymbol.Command : 'Ctrl'} + k</b>
{' / '}
<b>{isMacOS() ? KeySymbol.Command : 'Ctrl'} + f</b>
</>
)}
</Text>
</Box>
</Modal>
@@ -455,5 +540,9 @@ export function SearchModalRenderer() {
)
);
return opened && <Search requestClose={() => setOpen(false)} />;
return opened && <RoomSearchModal requestClose={() => setOpen(false)} />;
}
export function Search(props: { requestClose: () => void }) {
return <RoomSearchModal requestClose={props.requestClose} />;
}