mirror of
https://github.com/SableClient/Sable.git
synced 2026-11-24 02:51:17 -08:00
feat: add mobile swipe-to-edit composer flow
This commit is contained in:
1 parent
e3ff86dfce
commit
9b40a487ff
7 files changed
+498
-44
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Add swipe-to-edit gesture on mobile messages.
|
||||
@@ -3,36 +3,76 @@ import { useDrag } from '@use-gesture/react';
|
||||
import type { ReactNode } from 'react';
|
||||
import { useMemo, useRef, useState } from 'react';
|
||||
import { useAtomValue } from 'jotai';
|
||||
import { config } from 'folds';
|
||||
import { ArrowBendUpLeftIcon, getPhosphorIconSize } from '$components/icons/phosphor';
|
||||
import { ArrowBendUpLeftIcon, PencilSimple, getPhosphorIconSize } from '$components/icons/phosphor';
|
||||
import { haptic } from '$utils/haptics';
|
||||
import { mobileOrTablet } from '$utils/user-agent';
|
||||
import { RightSwipeAction, settingsAtom } from '$state/settings';
|
||||
|
||||
function ActiveSwipeWrapper({ children, onReply }: { children: ReactNode; onReply: () => void }) {
|
||||
type SwipeActionMode = 'none' | 'reply' | 'edit';
|
||||
|
||||
function ActiveSwipeWrapper({
|
||||
children,
|
||||
onReply,
|
||||
onEdit,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
onReply: () => void;
|
||||
onEdit?: () => void;
|
||||
}) {
|
||||
const containerRef = useRef<HTMLDivElement | null>(null);
|
||||
const x = useMotionValue(0);
|
||||
const [isReady, setIsReady] = useState(false);
|
||||
const isReadyRef = useRef(false);
|
||||
const iconOpacity = useTransform(x, [0, -8], [0, 1]);
|
||||
const [actionMode, setActionMode] = useState<SwipeActionMode>('none');
|
||||
const actionModeRef = useRef<SwipeActionMode>('none');
|
||||
const iconOpacity = useTransform(x, [0, -12], [0, 1]);
|
||||
const bgOpacity = useTransform(x, [0, -15], [0, 1]);
|
||||
const gapWidth = useTransform(x, (val) => Math.abs(Math.min(0, val)));
|
||||
|
||||
const bind = useDrag(
|
||||
({ first, active, movement: [mx] }) => {
|
||||
if (first) x.stop();
|
||||
|
||||
const width = containerRef.current?.clientWidth || 360;
|
||||
const replyThreshold = -Math.min(50, width * 0.2);
|
||||
const editThreshold = -Math.min(110, width * 0.38);
|
||||
|
||||
if (active) {
|
||||
const val = mx < 0 ? mx : 0;
|
||||
x.set(Math.max(-80, val));
|
||||
const nextReady = mx < -50;
|
||||
if (nextReady !== isReadyRef.current) {
|
||||
isReadyRef.current = nextReady;
|
||||
setIsReady(nextReady);
|
||||
if (nextReady) haptic('selection');
|
||||
const dragDist = Math.abs(val);
|
||||
const linearLimit = onEdit ? Math.min(100, width * 0.32) : Math.min(60, width * 0.18);
|
||||
let smoothedDist = dragDist;
|
||||
|
||||
if (dragDist > linearLimit) {
|
||||
const excess = dragDist - linearLimit;
|
||||
const maxExcess = 45;
|
||||
// Smooth exponential ease-out deceleration so the swipe slows down gradually instead of stopping abruptly
|
||||
smoothedDist = linearLimit + maxExcess * (1 - Math.exp(-excess / 40));
|
||||
}
|
||||
x.set(-smoothedDist);
|
||||
|
||||
let nextMode: SwipeActionMode = 'none';
|
||||
if (onEdit && mx < editThreshold) {
|
||||
nextMode = 'edit';
|
||||
} else if (mx < replyThreshold) {
|
||||
nextMode = 'reply';
|
||||
}
|
||||
|
||||
if (nextMode !== actionModeRef.current) {
|
||||
actionModeRef.current = nextMode;
|
||||
setActionMode(nextMode);
|
||||
if (nextMode !== 'none') {
|
||||
haptic(nextMode === 'edit' ? 'medium' : 'selection');
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (mx < -50) onReply();
|
||||
animate(x, 0, { type: 'spring', stiffness: 300, damping: 35 });
|
||||
isReadyRef.current = false;
|
||||
setIsReady(false);
|
||||
const currentMode = actionModeRef.current;
|
||||
if (currentMode === 'edit' && onEdit) {
|
||||
onEdit();
|
||||
} else if (currentMode === 'reply') {
|
||||
onReply();
|
||||
}
|
||||
animate(x, 0, { type: 'spring', stiffness: 300, damping: 26 });
|
||||
actionModeRef.current = 'none';
|
||||
setActionMode('none');
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -44,34 +84,66 @@ function ActiveSwipeWrapper({ children, onReply }: { children: ReactNode; onRepl
|
||||
}
|
||||
);
|
||||
|
||||
const IconComponent = actionMode === 'edit' ? PencilSimple : ArrowBendUpLeftIcon;
|
||||
const iconColor =
|
||||
actionMode === 'edit'
|
||||
? 'var(--sable-primary-color, #6e56cf)'
|
||||
: actionMode === 'reply'
|
||||
? 'var(--sable-surface-on-container, #ffffff)'
|
||||
: 'rgba(255, 255, 255, 0.6)';
|
||||
|
||||
return (
|
||||
<div {...bind()} style={{ position: 'relative', touchAction: 'pan-y' }}>
|
||||
<div
|
||||
<div
|
||||
data-gestures="ignore"
|
||||
ref={containerRef}
|
||||
{...bind()}
|
||||
style={{ position: 'relative', touchAction: 'pan-y' }}
|
||||
>
|
||||
{/* Darkened backdrop for the revealed gap, anchored to the right edge */}
|
||||
<motion.div
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
right: 0,
|
||||
paddingRight: config.space.S400,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
width: gapWidth,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.35)',
|
||||
opacity: bgOpacity,
|
||||
borderTopRightRadius: '8px',
|
||||
borderBottomRightRadius: '8px',
|
||||
zIndex: 0,
|
||||
pointerEvents: 'none',
|
||||
}}
|
||||
>
|
||||
<motion.div style={{ opacity: iconOpacity }}>
|
||||
<ArrowBendUpLeftIcon
|
||||
/>
|
||||
|
||||
<motion.div style={{ x, position: 'relative', zIndex: 2, willChange: 'transform' }}>
|
||||
{children}
|
||||
|
||||
{/* Action icon pinned to the right edge of the sliding message */}
|
||||
<motion.div
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
left: '100%',
|
||||
width: '60px',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
zIndex: 1,
|
||||
pointerEvents: 'none',
|
||||
opacity: iconOpacity,
|
||||
}}
|
||||
>
|
||||
<IconComponent
|
||||
size={getPhosphorIconSize('toolbar')}
|
||||
style={{
|
||||
color: isReady
|
||||
? 'var(--sable-surface-on-container)'
|
||||
: 'var(--sable-surface-container)',
|
||||
transition: 'color 0.2s',
|
||||
color: iconColor,
|
||||
transition: 'color 0.2s, transform 0.2s',
|
||||
transform: actionMode === 'edit' ? 'scale(1.2)' : 'scale(1)',
|
||||
}}
|
||||
/>
|
||||
</motion.div>
|
||||
</div>
|
||||
<motion.div style={{ x, position: 'relative', zIndex: 1, willChange: 'transform' }}>
|
||||
{children}
|
||||
</motion.div>
|
||||
</div>
|
||||
);
|
||||
@@ -80,9 +152,11 @@ function ActiveSwipeWrapper({ children, onReply }: { children: ReactNode; onRepl
|
||||
export function SwipeableMessageWrapper({
|
||||
children,
|
||||
onReply,
|
||||
onEdit,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
onReply?: () => void;
|
||||
onEdit?: () => void;
|
||||
}) {
|
||||
const settings = useAtomValue(settingsAtom);
|
||||
|
||||
@@ -98,5 +172,9 @@ export function SwipeableMessageWrapper({
|
||||
return children;
|
||||
}
|
||||
|
||||
return <ActiveSwipeWrapper onReply={onReply}>{children}</ActiveSwipeWrapper>;
|
||||
return (
|
||||
<ActiveSwipeWrapper onReply={onReply} onEdit={onEdit}>
|
||||
{children}
|
||||
</ActiveSwipeWrapper>
|
||||
);
|
||||
}
|
||||
@@ -76,6 +76,7 @@ import {
|
||||
replaceWithElement,
|
||||
BlockType,
|
||||
} from '$components/editor';
|
||||
import { stripMarkdownEscapesForHiddenPreviews } from './message/hiddenLinkPreviews';
|
||||
import { plainToEditorInput } from '$components/editor/input';
|
||||
import type { GifData } from '$components/emoji-board';
|
||||
import { EmojiBoard, EmojiBoardTab } from '$components/emoji-board';
|
||||
@@ -110,7 +111,13 @@ import { fulfilledPromiseSettledResult } from '$utils/common';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
import { settingsAtom } from '$state/settings';
|
||||
import { matchesShortcut } from '../../keyboard/shortcuts';
|
||||
import { getMentionContent, isThreadRelationEvent, reactionOrEditEvent } from '$utils/room';
|
||||
import {
|
||||
getEditedEvent,
|
||||
getMentionContent,
|
||||
isThreadRelationEvent,
|
||||
reactionOrEditEvent,
|
||||
} from '$utils/room';
|
||||
import { htmlToMarkdown } from '$plugins/markdown';
|
||||
import { Command, SHRUG, TABLEFLIP, UNFLIP, useCommands } from '$hooks/useCommands';
|
||||
import { mobileOrTablet } from '$utils/user-agent';
|
||||
import { Reply, ThreadIndicator } from '$components/message';
|
||||
@@ -163,6 +170,7 @@ import {
|
||||
menuIcon,
|
||||
Microphone,
|
||||
PaperPlaneTilt,
|
||||
PencilSimple,
|
||||
getPhosphorIconSize,
|
||||
PlusCircle,
|
||||
Smiley,
|
||||
@@ -301,10 +309,24 @@ interface RoomInputProps {
|
||||
room: Room;
|
||||
threadRootId?: string;
|
||||
onEditLastMessage?: () => void;
|
||||
editId?: string;
|
||||
onCancelEdit?: () => void;
|
||||
}
|
||||
|
||||
export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
({ editor, fileDropContainerRef, roomId, room, threadRootId, onEditLastMessage }, ref) => {
|
||||
(
|
||||
{
|
||||
editor,
|
||||
fileDropContainerRef,
|
||||
roomId,
|
||||
room,
|
||||
threadRootId,
|
||||
onEditLastMessage,
|
||||
editId,
|
||||
onCancelEdit,
|
||||
},
|
||||
ref
|
||||
) => {
|
||||
// When in thread mode, isolate drafts by thread root ID so thread replies
|
||||
// don't clobber the main room draft (and vice versa).
|
||||
const draftKey = threadRootId ?? roomId;
|
||||
@@ -563,6 +585,138 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
[draftKey, editor, setMsgDraft]
|
||||
);
|
||||
|
||||
const editingEvent = editId ? room.findEventById(editId) : undefined;
|
||||
const getEditingContent = useCallback(
|
||||
(event: MatrixEvent): IContent => {
|
||||
const eventId = event.getId();
|
||||
const timeline = eventId ? room.getTimelineForEvent(eventId) : undefined;
|
||||
const latestEdit =
|
||||
eventId && timeline
|
||||
? getEditedEvent(eventId, event, timeline.getTimelineSet())
|
||||
: undefined;
|
||||
return latestEdit?.getContent()['m.new_content'] ?? event.getContent();
|
||||
},
|
||||
[room]
|
||||
);
|
||||
|
||||
const prevEditingEventId = useRef<string>();
|
||||
const preEditDraftRef = useRef<Editor['children']>();
|
||||
useEffect(() => {
|
||||
if (!mobileOrTablet()) {
|
||||
prevEditingEventId.current = undefined;
|
||||
preEditDraftRef.current = undefined;
|
||||
return;
|
||||
}
|
||||
|
||||
if (editingEvent) {
|
||||
if (editingEvent.getId() !== prevEditingEventId.current) {
|
||||
if (!prevEditingEventId.current) {
|
||||
preEditDraftRef.current = structuredClone(editor.children);
|
||||
}
|
||||
prevEditingEventId.current = editingEvent.getId();
|
||||
|
||||
const content = getEditingContent(editingEvent);
|
||||
let bodyText = (content.body as string | undefined) ?? '';
|
||||
const customHtml = (content.formatted_body as string | undefined) ?? undefined;
|
||||
|
||||
const rawPmp = content['com.beeper.per_message_profile'];
|
||||
const pmpDisplayname =
|
||||
rawPmp !== null &&
|
||||
typeof rawPmp === 'object' &&
|
||||
'displayname' in rawPmp &&
|
||||
typeof rawPmp.displayname === 'string' &&
|
||||
rawPmp.displayname.length > 0
|
||||
? (rawPmp.displayname as string)
|
||||
: undefined;
|
||||
|
||||
if (pmpDisplayname && typeof bodyText === 'string') {
|
||||
const bodyPrefix = `${pmpDisplayname}: `;
|
||||
if (bodyText.startsWith(bodyPrefix)) {
|
||||
bodyText = bodyText.slice(bodyPrefix.length);
|
||||
}
|
||||
}
|
||||
const editableHtml = pmpDisplayname
|
||||
? customHtml?.replace(/^<strong\s+data-mx-profile-fallback[^>]*>.*?<\/strong>/, '')
|
||||
: customHtml;
|
||||
|
||||
const mentionOptions = {
|
||||
room,
|
||||
nicknames,
|
||||
mxUserId: mx.getUserId() ?? undefined,
|
||||
};
|
||||
|
||||
const initialValue = plainToEditorInput(
|
||||
editableHtml
|
||||
? stripMarkdownEscapesForHiddenPreviews(htmlToMarkdown(editableHtml))
|
||||
: typeof bodyText === 'string'
|
||||
? stripMarkdownEscapesForHiddenPreviews(bodyText)
|
||||
: '',
|
||||
mentionOptions
|
||||
);
|
||||
|
||||
resetEditor(editor);
|
||||
resetEditorHistory(editor);
|
||||
Transforms.insertFragment(editor, initialValue);
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
try {
|
||||
ReactEditor.focus(editor);
|
||||
moveCursor(editor);
|
||||
} catch {
|
||||
// Ignore focus error
|
||||
}
|
||||
});
|
||||
}
|
||||
} else {
|
||||
const previousDraft = preEditDraftRef.current;
|
||||
if (prevEditingEventId.current && previousDraft) {
|
||||
resetEditor(editor);
|
||||
resetEditorHistory(editor);
|
||||
Transforms.insertFragment(editor, previousDraft);
|
||||
}
|
||||
preEditDraftRef.current = undefined;
|
||||
if (
|
||||
prevEditingEventId.current &&
|
||||
(!replyDraft?.eventId || replyDraft.eventId === threadRootId)
|
||||
) {
|
||||
requestAnimationFrame(() => {
|
||||
try {
|
||||
const domNode = ReactEditor.toDOMNode(editor, editor);
|
||||
domNode.blur();
|
||||
(document.activeElement as HTMLElement)?.blur();
|
||||
} catch {
|
||||
// Ignore blur error
|
||||
}
|
||||
});
|
||||
}
|
||||
prevEditingEventId.current = undefined;
|
||||
}
|
||||
}, [
|
||||
editingEvent,
|
||||
editor,
|
||||
getEditingContent,
|
||||
mx,
|
||||
nicknames,
|
||||
room,
|
||||
replyDraft?.eventId,
|
||||
threadRootId,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
if (editId && replyDraft?.eventId && replyDraft.eventId !== threadRootId) {
|
||||
if (threadRootId) {
|
||||
setReplyDraft({
|
||||
userId: mx.getUserId() ?? '',
|
||||
eventId: threadRootId,
|
||||
body: '',
|
||||
relation: { rel_type: RelationType.Thread, event_id: threadRootId },
|
||||
});
|
||||
} else {
|
||||
setReplyDraft(undefined);
|
||||
}
|
||||
}
|
||||
}, [editId, threadRootId, setReplyDraft, mx, replyDraft?.eventId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (replyDraft !== undefined) {
|
||||
setSilentReply(replyDraft.userId === mx.getUserId() || !mentionInReplies);
|
||||
@@ -571,10 +725,13 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
|
||||
const prevReplyEventId = useRef(replyDraft?.eventId);
|
||||
useEffect(() => {
|
||||
if (replyDraft?.eventId !== prevReplyEventId.current) {
|
||||
prevReplyEventId.current = replyDraft?.eventId;
|
||||
const prevId = prevReplyEventId.current;
|
||||
const newId = replyDraft?.eventId;
|
||||
|
||||
if (replyDraft?.eventId) {
|
||||
if (newId !== prevId) {
|
||||
prevReplyEventId.current = newId;
|
||||
|
||||
if (newId && newId !== threadRootId) {
|
||||
requestAnimationFrame(() => {
|
||||
try {
|
||||
ReactEditor.focus(editor);
|
||||
@@ -583,9 +740,19 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
// Ignore focus errors
|
||||
}
|
||||
});
|
||||
} else if (!newId && prevId && prevId !== threadRootId && !editId) {
|
||||
requestAnimationFrame(() => {
|
||||
try {
|
||||
const domNode = ReactEditor.toDOMNode(editor, editor);
|
||||
domNode.blur();
|
||||
(document.activeElement as HTMLElement)?.blur();
|
||||
} catch {
|
||||
// Ignore blur errors
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}, [replyDraft?.eventId, editor]);
|
||||
}, [replyDraft?.eventId, threadRootId, editId, editor]);
|
||||
|
||||
const handleFileMetadata = useCallback(
|
||||
(fileItem: TUploadItem, metadata: TUploadMetadata) => {
|
||||
@@ -879,6 +1046,116 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
);
|
||||
|
||||
const submit = useCallback(async () => {
|
||||
if (editingEvent && mobileOrTablet()) {
|
||||
let plainText = toPlainText(editor.children).trim();
|
||||
if (!plainText) {
|
||||
onCancelEdit?.();
|
||||
return;
|
||||
}
|
||||
|
||||
let customHtml = trimCustomHtml(
|
||||
toMatrixCustomHTML(editor.children, {
|
||||
forEmote: editingEvent.getContent().msgtype === MsgType.Emote,
|
||||
room,
|
||||
})
|
||||
);
|
||||
const oldContent = editingEvent.getContent();
|
||||
const currentContent = getEditingContent(editingEvent);
|
||||
const eventId = editingEvent.getId();
|
||||
if (!eventId) return;
|
||||
|
||||
const msgtype = oldContent.msgtype ?? MsgType.Text;
|
||||
const newContent: IContent = {
|
||||
msgtype,
|
||||
body: plainText,
|
||||
};
|
||||
|
||||
const rawPmp =
|
||||
currentContent['com.beeper.per_message_profile'] ??
|
||||
oldContent['com.beeper.per_message_profile'];
|
||||
const pmpDisplayname =
|
||||
rawPmp !== null &&
|
||||
typeof rawPmp === 'object' &&
|
||||
'displayname' in rawPmp &&
|
||||
typeof rawPmp.displayname === 'string' &&
|
||||
rawPmp.displayname.length > 0
|
||||
? rawPmp.displayname
|
||||
: undefined;
|
||||
|
||||
if (pmpDisplayname) {
|
||||
const bodyPrefix = `${pmpDisplayname}: `;
|
||||
if (!plainText.startsWith(bodyPrefix)) plainText = bodyPrefix + plainText;
|
||||
|
||||
const htmlPrefix = `<strong data-mx-profile-fallback>${sanitizeText(pmpDisplayname)}: </strong>`;
|
||||
if (!customHtml.startsWith(htmlPrefix)) customHtml = htmlPrefix + customHtml;
|
||||
newContent.body = plainText;
|
||||
newContent['com.beeper.per_message_profile'] = rawPmp;
|
||||
}
|
||||
|
||||
const mentionData = getMentions(mx, roomId, editor);
|
||||
const previousMentions = currentContent['m.mentions'];
|
||||
if (
|
||||
previousMentions &&
|
||||
typeof previousMentions === 'object' &&
|
||||
'user_ids' in previousMentions &&
|
||||
Array.isArray(previousMentions.user_ids)
|
||||
) {
|
||||
previousMentions.user_ids.forEach((userId) => {
|
||||
if (typeof userId === 'string') mentionData.users.add(userId);
|
||||
});
|
||||
}
|
||||
const mMentions = getMentionContent(Array.from(mentionData.users), mentionData.room);
|
||||
newContent['m.mentions'] = mMentions;
|
||||
|
||||
const content: IContent = {
|
||||
...oldContent,
|
||||
'm.relates_to': {
|
||||
event_id: eventId,
|
||||
rel_type: RelationType.Replace,
|
||||
},
|
||||
body: `* ${plainText}`,
|
||||
'm.mentions': mMentions,
|
||||
'm.new_content': newContent,
|
||||
};
|
||||
|
||||
if (pmpDisplayname || !customHtmlEqualsPlainText(customHtml, plainText)) {
|
||||
newContent.format = 'org.matrix.custom.html';
|
||||
newContent.formatted_body = customHtml;
|
||||
content.format = 'org.matrix.custom.html';
|
||||
content.formatted_body = `* ${customHtml}`;
|
||||
} else {
|
||||
delete content.format;
|
||||
delete content.formatted_body;
|
||||
}
|
||||
|
||||
if (oldContent.info !== undefined && oldContent.msgtype !== MsgType.Text) {
|
||||
const filename = 'filename' in oldContent ? oldContent.filename : oldContent.body;
|
||||
content.filename = filename;
|
||||
newContent.filename = filename;
|
||||
content.info = oldContent.info;
|
||||
newContent.info = oldContent.info;
|
||||
if (oldContent.file !== undefined) newContent.file = oldContent.file;
|
||||
if (oldContent.url !== undefined) newContent.url = oldContent.url;
|
||||
|
||||
const spoilerKey = 'page.codeberg.everypizza.msc4193.spoiler';
|
||||
if (oldContent[spoilerKey] !== undefined) {
|
||||
content[spoilerKey] = oldContent[spoilerKey];
|
||||
newContent[spoilerKey] = oldContent[spoilerKey];
|
||||
}
|
||||
}
|
||||
|
||||
const linkPreviews = getLinks(editor.children)?.map((matchedUrl) => ({
|
||||
matched_url: matchedUrl,
|
||||
}));
|
||||
content['com.beeper.linkpreviews'] = linkPreviews ?? [];
|
||||
newContent['com.beeper.linkpreviews'] = linkPreviews ?? [];
|
||||
|
||||
await mx.sendMessage(roomId, content as RoomMessageEventContent);
|
||||
onCancelEdit?.();
|
||||
sendTypingStatus(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (selectedFiles.some((f) => f.encrypting)) return;
|
||||
uploadBoardHandlers.current?.handleSend();
|
||||
if (
|
||||
@@ -1282,6 +1559,9 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
selectedFiles,
|
||||
enableMediaGalleries,
|
||||
sendIndividualAttachmentAsCaption,
|
||||
editingEvent,
|
||||
getEditingContent,
|
||||
onCancelEdit,
|
||||
]);
|
||||
|
||||
const handleKeyDown: KeyboardEventHandler = useCallback(
|
||||
@@ -1339,6 +1619,12 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
}
|
||||
if (isKeyHotkey('escape', evt)) {
|
||||
evt.preventDefault();
|
||||
if (editingEvent && mobileOrTablet()) {
|
||||
onCancelEdit?.();
|
||||
resetEditor(editor);
|
||||
resetEditorHistory(editor);
|
||||
return;
|
||||
}
|
||||
if (showAudioRecorder) {
|
||||
audioRecorderRef.current?.cancel();
|
||||
return;
|
||||
@@ -1367,6 +1653,8 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
onEditLastMessage,
|
||||
setEmojiBoardTab,
|
||||
shortcutOverrides,
|
||||
editingEvent,
|
||||
onCancelEdit,
|
||||
]
|
||||
);
|
||||
|
||||
@@ -1666,6 +1954,45 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
</Box>
|
||||
</div>
|
||||
)}
|
||||
{editingEvent && mobileOrTablet() && (
|
||||
<div>
|
||||
<Box
|
||||
alignItems="Center"
|
||||
gap="300"
|
||||
style={{
|
||||
padding: `${config.space.S200} ${config.space.S300} 0`,
|
||||
}}
|
||||
>
|
||||
<IconButton
|
||||
onClick={() => {
|
||||
onCancelEdit?.();
|
||||
resetEditor(editor);
|
||||
resetEditorHistory(editor);
|
||||
}}
|
||||
variant="SurfaceVariant"
|
||||
style={{ background: 'transparent' }}
|
||||
size="300"
|
||||
radii="300"
|
||||
aria-label="Cancel editing"
|
||||
title="Cancel editing"
|
||||
>
|
||||
{chipIcon(X)}
|
||||
</IconButton>
|
||||
<Box
|
||||
direction="Row"
|
||||
gap="200"
|
||||
alignItems="Center"
|
||||
grow="Yes"
|
||||
style={{ minWidth: 0 }}
|
||||
>
|
||||
{menuIcon(PencilSimple)}
|
||||
<Text size="T300" truncate>
|
||||
Editing message: {editingEvent.getContent().body as string}
|
||||
</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
</div>
|
||||
)}
|
||||
{replyDraft && (!threadRootId || replyDraft.body) && (
|
||||
<div>
|
||||
<Box
|
||||
|
||||
@@ -303,6 +303,8 @@ export type RoomTimelineProps = {
|
||||
editor: Editor;
|
||||
onEditorReset?: () => void;
|
||||
onEditLastMessageRef?: React.MutableRefObject<(() => void) | undefined>;
|
||||
editId?: string;
|
||||
onEditId?: (editId?: string) => void;
|
||||
};
|
||||
|
||||
export function RoomTimeline({
|
||||
@@ -311,12 +313,16 @@ export function RoomTimeline({
|
||||
editor,
|
||||
onEditorReset,
|
||||
onEditLastMessageRef,
|
||||
editId: propsEditId,
|
||||
onEditId: propsOnEditId,
|
||||
}: Readonly<RoomTimelineProps>) {
|
||||
const mx = useMatrixClient();
|
||||
const alive = useAlive();
|
||||
const roomSyncLoading = useSlidingSyncRoomLoading(room.roomId);
|
||||
|
||||
const { editId, handleEdit } = useMessageEdit(editor, { onReset: onEditorReset, alive });
|
||||
const internalEdit = useMessageEdit(editor, { onReset: onEditorReset, alive });
|
||||
const editId = propsOnEditId ? propsEditId : internalEdit.editId;
|
||||
const handleEdit = propsOnEditId ?? internalEdit.handleEdit;
|
||||
const { navigateRoom } = useRoomNavigate();
|
||||
const isInactivePanel = useIsInactivePanel();
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import { useEditor, resetEditor } from '$components/editor';
|
||||
import { Page } from '$components/page';
|
||||
import { useKeyDown } from '$hooks/useKeyDown';
|
||||
import { editableActiveElement } from '$utils/dom';
|
||||
import { mobileOrTablet } from '$utils/user-agent';
|
||||
import { settingsAtom } from '$state/settings';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
import { useRoomPermissions } from '$hooks/useRoomPermissions';
|
||||
@@ -30,6 +31,8 @@ import { callEmbedAtom } from '$state/callEmbed';
|
||||
import { useCallJoined } from '$hooks/useCallEmbed';
|
||||
import { CallView } from '$features/call/CallView';
|
||||
import { useRoom } from '$hooks/useRoom';
|
||||
import { useMessageEdit } from '$hooks/useMessageEdit';
|
||||
import { useAlive } from '$hooks/useAlive';
|
||||
import { RoomViewFollowing, RoomViewFollowingPlaceholder } from './RoomViewFollowing';
|
||||
import { RoomInput } from './RoomInput';
|
||||
import { RoomTombstone } from './RoomTombstone';
|
||||
@@ -92,6 +95,12 @@ export function RoomView({ eventId }: { eventId?: string }) {
|
||||
|
||||
const [editorResetKey, setEditorResetKey] = useState(0);
|
||||
const handleResetEditor = useCallback(() => setEditorResetKey((prev) => prev + 1), []);
|
||||
const alive = useAlive();
|
||||
const { editId, handleEdit } = useMessageEdit(editor, {
|
||||
onReset: handleResetEditor,
|
||||
alive,
|
||||
focusOnCancel: !mobileOrTablet(),
|
||||
});
|
||||
|
||||
useDelayedEventsSupport();
|
||||
const delayedEventsSupported = useAtomValue(delayedEventsSupportedAtom);
|
||||
@@ -156,6 +165,8 @@ export function RoomView({ eventId }: { eventId?: string }) {
|
||||
editor={editor}
|
||||
onEditorReset={handleResetEditor}
|
||||
onEditLastMessageRef={editLastMessageRef}
|
||||
editId={editId}
|
||||
onEditId={handleEdit}
|
||||
/>
|
||||
<div style={{ position: 'relative', flexShrink: 0 }}>
|
||||
<RoomViewTyping room={room} />
|
||||
@@ -184,6 +195,8 @@ export function RoomView({ eventId }: { eventId?: string }) {
|
||||
fileDropContainerRef={roomViewRef}
|
||||
ref={roomInputRef}
|
||||
onEditLastMessage={() => editLastMessageRef.current?.()}
|
||||
editId={editId}
|
||||
onCancelEdit={() => handleEdit(undefined)}
|
||||
/>
|
||||
)}
|
||||
{!canMessage && (
|
||||
|
||||
@@ -39,7 +39,7 @@ import {
|
||||
Username,
|
||||
UsernameBold,
|
||||
} from '$components/message';
|
||||
import { getEditedEvent, getMemberAvatarMxc } from '$utils/room';
|
||||
import { canEditEvent, getEditedEvent, getMemberAvatarMxc } from '$utils/room';
|
||||
import { getMxIdLocalPart, mxcUrlToHttp } from '$utils/matrix';
|
||||
import type { MessageSpacing } from '$state/settings';
|
||||
import { getSettings, MessageLayout, settingsAtom } from '$state/settings';
|
||||
@@ -263,6 +263,7 @@ type WrappedMessageProps = {
|
||||
msgContentJSX: JSX.Element;
|
||||
messageLayout?: MessageLayout;
|
||||
handleSwipeReply?: () => void;
|
||||
handleSwipeEdit?: () => void;
|
||||
handleContextMenu: MouseEventHandler<HTMLDivElement>;
|
||||
align?: 'left' | 'right';
|
||||
};
|
||||
@@ -272,6 +273,7 @@ function WrappedMessage({
|
||||
msgContentJSX,
|
||||
messageLayout,
|
||||
handleSwipeReply,
|
||||
handleSwipeEdit,
|
||||
handleContextMenu,
|
||||
align,
|
||||
}: WrappedMessageProps) {
|
||||
@@ -279,7 +281,7 @@ function WrappedMessage({
|
||||
|
||||
if (messageLayout === MessageLayout.Compact)
|
||||
return (
|
||||
<SwipeableMessageWrapper onReply={handleSwipeReply}>
|
||||
<SwipeableMessageWrapper onReply={handleSwipeReply} onEdit={handleSwipeEdit}>
|
||||
<CompactLayout before={headerJSX} onContextMenu={handleContextMenu}>
|
||||
{msgContentJSX}
|
||||
</CompactLayout>
|
||||
@@ -287,7 +289,7 @@ function WrappedMessage({
|
||||
);
|
||||
if (messageLayout === MessageLayout.Bubble)
|
||||
return (
|
||||
<SwipeableMessageWrapper onReply={handleSwipeReply}>
|
||||
<SwipeableMessageWrapper onReply={handleSwipeReply} onEdit={handleSwipeEdit}>
|
||||
<BubbleLayout
|
||||
before={avatarJSX}
|
||||
header={headerJSX}
|
||||
@@ -299,7 +301,7 @@ function WrappedMessage({
|
||||
</SwipeableMessageWrapper>
|
||||
);
|
||||
return (
|
||||
<SwipeableMessageWrapper onReply={handleSwipeReply}>
|
||||
<SwipeableMessageWrapper onReply={handleSwipeReply} onEdit={handleSwipeEdit}>
|
||||
<ModernLayout before={avatarJSX} onContextMenu={handleContextMenu}>
|
||||
{headerJSX}
|
||||
{msgContentJSX}
|
||||
@@ -762,7 +764,7 @@ function MessageInternal(
|
||||
</Chip>
|
||||
)}
|
||||
{reply}
|
||||
{edit && onEditId ? (
|
||||
{edit && onEditId && !mobileOrTablet() ? (
|
||||
<MessageEditor
|
||||
style={{
|
||||
maxWidth: '100%',
|
||||
@@ -914,6 +916,9 @@ function MessageInternal(
|
||||
};
|
||||
|
||||
const handleSwipeReply = () => {
|
||||
if (onEditId) {
|
||||
onEditId(undefined);
|
||||
}
|
||||
const currentId = mEvent.getId();
|
||||
const targetId = activeReplyId === currentId ? null : currentId;
|
||||
const mockEvent = {
|
||||
@@ -925,6 +930,21 @@ function MessageInternal(
|
||||
onReplyClick(mockEvent);
|
||||
};
|
||||
|
||||
const handleSwipeEdit = useMemo(
|
||||
() =>
|
||||
canEditEvent(mx, mEvent) && onEditId
|
||||
? () => {
|
||||
const currentId = mEvent.getId();
|
||||
if (edit) {
|
||||
onEditId(undefined);
|
||||
} else {
|
||||
onEditId(currentId);
|
||||
}
|
||||
}
|
||||
: undefined,
|
||||
[mx, mEvent, onEditId, edit]
|
||||
);
|
||||
|
||||
return (
|
||||
<MessageBase
|
||||
className={classNames(css.MessageBase, className, {
|
||||
@@ -987,6 +1007,7 @@ function MessageInternal(
|
||||
msgContentJSX={msgContentJSX}
|
||||
messageLayout={messageLayout}
|
||||
handleSwipeReply={handleSwipeReply}
|
||||
handleSwipeEdit={handleSwipeEdit}
|
||||
handleContextMenu={handleContextMenu}
|
||||
align={useRightBubbles && senderId === mx.getUserId() ? 'right' : 'left'}
|
||||
/>
|
||||
|
||||
@@ -6,6 +6,7 @@ import { isEmptyEditor, moveCursor } from '$components/editor';
|
||||
export interface UseMessageEditOptions {
|
||||
onReset?: () => void;
|
||||
alive?: () => boolean;
|
||||
focusOnCancel?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -27,6 +28,8 @@ export function useMessageEdit(
|
||||
aliveRef.current = options?.alive;
|
||||
const onResetRef = useRef(options?.onReset);
|
||||
onResetRef.current = options?.onReset;
|
||||
const focusOnCancelRef = useRef(options?.focusOnCancel ?? true);
|
||||
focusOnCancelRef.current = options?.focusOnCancel ?? true;
|
||||
|
||||
const handleEdit = useCallback(
|
||||
(targetEditId?: string) => {
|
||||
@@ -35,6 +38,7 @@ export function useMessageEdit(
|
||||
return;
|
||||
}
|
||||
setEditId(undefined);
|
||||
if (!focusOnCancelRef.current) return;
|
||||
requestAnimationFrame(() => {
|
||||
if (aliveRef.current && !aliveRef.current()) return;
|
||||
if (onResetRef.current && isEmptyEditor(editor)) onResetRef.current();
|
||||
|
||||
Reference in new issue
Block a user