diff --git a/.changeset/swipe-to-edit.md b/.changeset/swipe-to-edit.md new file mode 100644 index 000000000..6897c15f9 --- /dev/null +++ b/.changeset/swipe-to-edit.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Add swipe-to-edit gesture on mobile messages. diff --git a/src/app/components/SwipeableMessageWrapper.tsx b/src/app/components/SwipeableMessageWrapper.tsx index bb96af68c..dd41e8a1c 100644 --- a/src/app/components/SwipeableMessageWrapper.tsx +++ b/src/app/components/SwipeableMessageWrapper.tsx @@ -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(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('none'); + const actionModeRef = useRef('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 ( -
-
+ {/* Darkened backdrop for the revealed gap, anchored to the right edge */} + - - + + + {children} + + {/* Action icon pinned to the right edge of the sliding message */} + + -
- - {children}
); @@ -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 {children}; + return ( + + {children} + + ); } diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index e5f53370e..cc686b15f 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -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( - ({ 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( [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(); + const preEditDraftRef = useRef(); + 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>/, '') + : 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( 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( // 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( ); 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 = `${sanitizeText(pmpDisplayname)}: `; + 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( selectedFiles, enableMediaGalleries, sendIndividualAttachmentAsCaption, + editingEvent, + getEditingContent, + onCancelEdit, ]); const handleKeyDown: KeyboardEventHandler = useCallback( @@ -1339,6 +1619,12 @@ export const RoomInput = forwardRef( } 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( onEditLastMessage, setEmojiBoardTab, shortcutOverrides, + editingEvent, + onCancelEdit, ] ); @@ -1666,6 +1954,45 @@ export const RoomInput = forwardRef( )} + {editingEvent && mobileOrTablet() && ( +
+ + { + onCancelEdit?.(); + resetEditor(editor); + resetEditorHistory(editor); + }} + variant="SurfaceVariant" + style={{ background: 'transparent' }} + size="300" + radii="300" + aria-label="Cancel editing" + title="Cancel editing" + > + {chipIcon(X)} + + + {menuIcon(PencilSimple)} + + Editing message: {editingEvent.getContent().body as string} + + + +
+ )} {replyDraft && (!threadRootId || replyDraft.body) && (
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) { 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(); diff --git a/src/app/features/room/RoomView.tsx b/src/app/features/room/RoomView.tsx index 02b8fe947..9b1996084 100644 --- a/src/app/features/room/RoomView.tsx +++ b/src/app/features/room/RoomView.tsx @@ -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} />
@@ -184,6 +195,8 @@ export function RoomView({ eventId }: { eventId?: string }) { fileDropContainerRef={roomViewRef} ref={roomInputRef} onEditLastMessage={() => editLastMessageRef.current?.()} + editId={editId} + onCancelEdit={() => handleEdit(undefined)} /> )} {!canMessage && ( diff --git a/src/app/features/room/message/Message.tsx b/src/app/features/room/message/Message.tsx index a60904169..806c700f4 100644 --- a/src/app/features/room/message/Message.tsx +++ b/src/app/features/room/message/Message.tsx @@ -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; 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 ( - + {msgContentJSX} @@ -287,7 +289,7 @@ function WrappedMessage({ ); if (messageLayout === MessageLayout.Bubble) return ( - + ); return ( - + {headerJSX} {msgContentJSX} @@ -762,7 +764,7 @@ function MessageInternal( )} {reply} - {edit && onEditId ? ( + {edit && onEditId && !mobileOrTablet() ? ( { + 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 ( diff --git a/src/app/hooks/useMessageEdit.ts b/src/app/hooks/useMessageEdit.ts index 120137d36..4480ba416 100644 --- a/src/app/hooks/useMessageEdit.ts +++ b/src/app/hooks/useMessageEdit.ts @@ -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();