From f59332cf99e8550d4ffafe58d61749f5b90473fb Mon Sep 17 00:00:00 2001 From: Ajay Bura <32841439+ajbura@users.noreply.github.com> Date: Mon, 31 Aug 2026 15:18:24 +0530 Subject: [PATCH] allow reactions in timeline --- src/app/components/message/Reaction.css.ts | 17 +- src/app/components/message/Reaction.tsx | 76 ++--- src/app/features/room/RoomTimeline.tsx | 8 +- .../features/room/hooks/useSendReaction.ts | 56 ++++ src/app/features/room/message/Reactions.tsx | 261 +++++++++++++++--- .../room/thread-view/TimelineView.tsx | 8 +- src/app/utils/room.ts | 11 +- src/client/room/local-event/LocalEvent.ts | 6 +- .../room/local-event/LocalEventSender.ts | 6 +- 9 files changed, 358 insertions(+), 91 deletions(-) create mode 100644 src/app/features/room/hooks/useSendReaction.ts diff --git a/src/app/components/message/Reaction.css.ts b/src/app/components/message/Reaction.css.ts index f020080e..6182b44b 100644 --- a/src/app/components/message/Reaction.css.ts +++ b/src/app/components/message/Reaction.css.ts @@ -1,4 +1,4 @@ -import { createVar, style } from '@vanilla-extract/css'; +import { createVar, keyframes, style } from '@vanilla-extract/css'; import { DefaultReset, FocusOutline, color, config, toRem } from 'folds'; const Container = createVar(); @@ -48,6 +48,7 @@ export const Reaction = style([ }, '&[aria-disabled=true], &:disabled': { cursor: 'not-allowed', + backgroundColor: `${Container} !important`, }, }, }, @@ -63,6 +64,20 @@ export const ReactionText = style([ lineHeight: toRem(20), }, ]); +const scaleAnimation = keyframes({ + '0%': { + transform: 'scale(1)', + }, + '50%': { + transform: 'scale(1.2)', + }, + '100%': { + transform: 'scale(1)', + }, +}); +export const ReactionChangeAnimation = style({ + animation: `${scaleAnimation} 1000ms ease-in-out infinite`, +}); export const ReactionImg = style([ DefaultReset, diff --git a/src/app/components/message/Reaction.tsx b/src/app/components/message/Reaction.tsx index ebce3dd4..7be632b0 100644 --- a/src/app/components/message/Reaction.tsx +++ b/src/app/components/message/Reaction.tsx @@ -4,45 +4,59 @@ import classNames from 'classnames'; import * as css from './Reaction.css'; import { getHexcodeForEmoji, getShortcodeFor } from '../../plugins/emoji'; import { useRoomMembersAPI } from '../../hooks/useRoomMembers'; -import { ClientContext } from '../../../client/context'; import { mxcToHttp } from '../../../client/mxcToHttp'; +import { useClient } from '../../hooks/useClient'; +import { useMediaAuthentication } from '../../hooks/useMediaAuthentication'; export const Reaction = as< 'button', { - ct: ClientContext; count: number; + adding?: boolean; + removing?: boolean; reaction: string; - useAuthentication?: boolean; } ->(({ className, ct, count, reaction, useAuthentication, ...props }, ref) => ( - - - {reaction.startsWith('mxc://') ? ( - {reaction} - ) : ( - - {reaction} - - )} - - - {count} - - -)); +>(({ className, count, adding, removing, reaction, ...props }, ref) => { + const ct = useClient(); + const useAuthentication = useMediaAuthentication(); + + return ( + + + {reaction.startsWith('mxc://') ? ( + {reaction} + ) : ( + + {reaction} + + )} + + + {count} + + + ); +}); type ReactionTooltipMsgProps = { reaction: string; diff --git a/src/app/features/room/RoomTimeline.tsx b/src/app/features/room/RoomTimeline.tsx index 29f5686f..2ac09799 100644 --- a/src/app/features/room/RoomTimeline.tsx +++ b/src/app/features/room/RoomTimeline.tsx @@ -75,6 +75,7 @@ import { useUserReadReceipt } from '../../hooks/useReadReceipt'; import { useMessageParserOptions } from '../../hooks/useMessageParserOptions'; import { MessageContent } from '../../components/MessageContent'; import { MessageEditor } from './message/MessageEditor'; +import { useSendReaction } from './hooks/useSendReaction'; type RoomTimelineProps = { eventId?: string; @@ -312,9 +313,7 @@ export function RoomTimeline({ eventId, roomInputRef, editor, timeline }: RoomTi const handleUsernameClick = useUsernameClickHandler(editor); const [replyDraft, handleReplyClick] = useReplyClickHandler(editor); - const handleReactionToggle = useCallback((targetEventId: string) => { - console.log(targetEventId); - }, []); + const handleReactionToggle = useSendReaction(); const handleEdit = useCallback( (editEvtId?: string) => { @@ -353,10 +352,11 @@ export function RoomTimeline({ eventId, roomInputRef, editor, timeline }: RoomTi const reactionJSX = reactionEvents && reactionEvents?.length > 0 && ( ); diff --git a/src/app/features/room/hooks/useSendReaction.ts b/src/app/features/room/hooks/useSendReaction.ts new file mode 100644 index 00000000..ae9d77be --- /dev/null +++ b/src/app/features/room/hooks/useSendReaction.ts @@ -0,0 +1,56 @@ +import { useCallback } from 'react'; +import { ReactionContent, RelationType } from '../../../../types/matrix/common'; +import { MessageEvent } from '../../../../types/matrix/room'; +import { useClient } from '../../../hooks/useClient'; +import { + EventSenderIdle, + LocalEvent, + LocalEventSender, + LocalMessage, +} from '../../../../client/room/local-event'; +import { useRoom } from '../../../hooks/useRoom'; +import { useTimelineView } from './useTimeline'; + +export const useSendReaction = () => { + const ct = useClient(); + const roomId = useRoom(); + const timeline = useTimelineView(); + + const handleAddReaction = useCallback( + (targetEventId: string, key: string, shortcode?: string) => { + const redacted = timeline.relations.redacted.read; + const reactions = timeline.relations.reactions.eventToRelations.read + .get(targetEventId) + ?.filter((r) => !redacted.has(r.event_id)); + if ( + reactions?.some( + (evt) => evt.sender === ct.session.userId && evt.content['m.relates_to'].key === key + ) + ) { + // Already reacted with this emoji + return; + } + + const content: ReactionContent = { + 'm.relates_to': { + event_id: targetEventId, + key, + rel_type: RelationType.Annotation, + }, + shortcode, + }; + + const localMessage = new LocalMessage(roomId, MessageEvent.Reaction, content); + const txnId = ct.getTxnId(); + const localEvent = new LocalEvent(localMessage, localMessage, txnId, Date.now()); + const eventSender = new LocalEventSender(localEvent, ct.requestAuthJSON); + + if (eventSender.state.read instanceof EventSenderIdle) { + eventSender.state.read.send(); + } + }, + [ct, roomId, timeline] + ); + + return handleAddReaction; +}; diff --git a/src/app/features/room/message/Reactions.tsx b/src/app/features/room/message/Reactions.tsx index b01068cd..aa361f5c 100644 --- a/src/app/features/room/message/Reactions.tsx +++ b/src/app/features/room/message/Reactions.tsx @@ -1,4 +1,4 @@ -import React, { MouseEventHandler, useMemo, useState } from 'react'; +import React, { MouseEventHandler, useEffect, useMemo, useState } from 'react'; import { MessageEventWithoutRoomId } from 'neurone/lib/api/types'; import { Box, @@ -14,25 +14,220 @@ import { } from 'folds'; import classNames from 'classnames'; import FocusTrap from 'focus-trap-react'; +import { parseMatrixResp } from 'neurone/lib/matrix-request'; +import { putRedact } from 'neurone/lib/api/matrix/client/v3/rooms'; import { Reaction, ReactionTooltipMsg } from '../../../components/message'; import * as css from './styles.css'; import { ReactionViewer } from '../reaction-viewer'; import { stopPropagation } from '../../../utils/keyboard'; -import { useMediaAuthentication } from '../../../hooks/useMediaAuthentication'; -import { ReactionContent } from '../../../../types/matrix/common'; +import { ReactionContent, RelationType } from '../../../../types/matrix/common'; import { useClient } from '../../../hooks/useClient'; -import { getReactionGroups } from '../../../utils/room'; +import { getReactionGroups, ReactionGroup } from '../../../utils/room'; +import { + EventSenderError, + EventSenderIdle, + EventSenderPending, + LocalEvent, + LocalEventSender, + LocalMessage, +} from '../../../../client/room/local-event'; +import { MessageEvent } from '../../../../types/matrix/room'; +import { useObservableValueOptionally } from '../../../hooks/useObservableValue'; +import { useAlive } from '../../../hooks/useAlive'; + +type ReactionUnpressedProps = { + roomId: string; + eventId: string; + reaction: ReactionGroup; + onViewReaction: MouseEventHandler; + disabled?: boolean; +}; +function ReactionUnpressed({ + roomId, + eventId, + reaction, + onViewReaction, + disabled, +}: ReactionUnpressedProps) { + const ct = useClient(); + + const [sender, setSender] = useState>(); + + const senderState = useObservableValueOptionally(sender?.state); + + useEffect(() => { + if (senderState instanceof EventSenderError) { + setSender(undefined); + } + }, [senderState]); + + const handleToggleReaction = () => { + if (senderState instanceof EventSenderPending) { + senderState.abort(); + setSender(undefined); + return; + } + + // guard against double reaction + // we have already clicked + if (sender) return; + + const content: ReactionContent = { + 'm.relates_to': { + event_id: eventId, + key: reaction.key, + rel_type: RelationType.Annotation, + }, + shortcode: reaction.shortcode, + }; + + const localMessage = new LocalMessage(roomId, MessageEvent.Reaction, content); + const txnId = ct.getTxnId(); + const localEvent = new LocalEvent(localMessage, localMessage, txnId, Date.now()); + const eventSender = new LocalEventSender(localEvent, ct.requestAuthJSON); + + if (eventSender.state.read instanceof EventSenderIdle) { + eventSender.state.read.send(); + } + + setSender(eventSender); + }; + + return ( + + + + + + } + > + {(targetRef) => ( + + )} + + ); +} + +type ReactionPressedProps = { + roomId: string; + redactEventId: string; + reaction: ReactionGroup; + onViewReaction: MouseEventHandler; + disabled?: boolean; +}; +function ReactionPressed({ + roomId, + reaction, + redactEventId, + onViewReaction, + disabled, +}: ReactionPressedProps) { + const ct = useClient(); + const alive = useAlive(); + + const [redactState, setRedactState] = useState<{ + status: 'pending' | 'error' | 'success'; + controller?: AbortController; + }>(); + + useEffect(() => { + if (redactState?.status === 'error') { + setRedactState(undefined); + } + }, [redactState]); + + const handleToggleReaction = async () => { + if (redactState) { + redactState.controller?.abort(); + setRedactState(undefined); + return; + } + + const controller = new AbortController(); + setRedactState({ status: 'pending', controller }); + try { + const resp = await ct.requestAuthJSON( + putRedact({ pathParams: { roomId, eventId: redactEventId, txnId: ct.getTxnId() } }) + ); + + const [error] = await parseMatrixResp(resp); + if (error) throw new Error(error.data.error); + if (!alive()) return; + setRedactState({ status: 'success' }); + } catch (e) { + if (!alive()) return; + if (e instanceof Error && e.name === 'AbortError') { + // we already removed the state on key press + return; + } + setRedactState({ status: 'error' }); + } + }; + + return ( + + + + + + } + > + {(targetRef) => ( + + )} + + ); +} export type ReactionsProps = { + roomId: string; eventId: string; canSendReaction?: boolean; + canRedactReaction?: boolean; reactions: MessageEventWithoutRoomId[]; - onReactionToggle: (targetEventId: string, key: string, shortcode?: string) => void; }; export const Reactions = as<'div', ReactionsProps>( - ({ className, reactions, eventId, canSendReaction, onReactionToggle, ...props }, ref) => { + ( + { className, reactions, roomId, eventId, canSendReaction, canRedactReaction, ...props }, + ref + ) => { const ct = useClient(); - const useAuthentication = useMediaAuthentication(); const [viewer, setViewer] = useState(false); const handleViewReaction: MouseEventHandler = (evt) => { @@ -54,42 +249,26 @@ export const Reactions = as<'div', ReactionsProps>( ref={ref} > {reactionGroups.map((reaction) => { - const isPressed = reaction.users.has(ct.session.userId); + const myReactionEvent = reaction.events.find((ev) => ev.sender === ct.session.userId); - return ( - - - - - - } - > - {(targetRef) => ( - onReactionToggle(eventId, reaction.key) : undefined - } - onContextMenu={handleViewReaction} - aria-disabled={!canSendReaction} - useAuthentication={useAuthentication} - /> - )} - + roomId={roomId} + redactEventId={myReactionEvent.event_id} + reaction={reaction} + onViewReaction={handleViewReaction} + disabled={!canRedactReaction} + /> + ) : ( + ); })} {reactions.length > 0 && ( diff --git a/src/app/features/room/thread-view/TimelineView.tsx b/src/app/features/room/thread-view/TimelineView.tsx index f6979bab..a81f096c 100644 --- a/src/app/features/room/thread-view/TimelineView.tsx +++ b/src/app/features/room/thread-view/TimelineView.tsx @@ -73,6 +73,7 @@ import { useUserReadReceipt } from '../../../hooks/useReadReceipt'; import { useMessageParserOptions } from '../../../hooks/useMessageParserOptions'; import { MessageContent } from '../../../components/MessageContent'; import { MessageEditor } from '../message/MessageEditor'; +import { useSendReaction } from '../hooks/useSendReaction'; type TimelineViewProps = { threadTimeline: ThreadTimeline; @@ -265,9 +266,7 @@ export function TimelineView({ threadTimeline, threadInputRef }: TimelineViewPro const handleUsernameClick = useUsernameClickHandler(editor); const [replyDraft, handleReplyClick] = useReplyClickHandler(editor, threadTimeline.threadId); - const handleReactionToggle = useCallback((targetEventId: string) => { - console.log(targetEventId); - }, []); + const handleReactionToggle = useSendReaction(); const handleEdit = useCallback( (editEvtId?: string) => { @@ -309,10 +308,11 @@ export function TimelineView({ threadTimeline, threadInputRef }: TimelineViewPro const reactionJSX = reactionEvents && reactionEvents?.length > 0 && ( ); diff --git a/src/app/utils/room.ts b/src/app/utils/room.ts index 1dcdfa3f..57af4667 100644 --- a/src/app/utils/room.ts +++ b/src/app/utils/room.ts @@ -421,13 +421,14 @@ export const getEventReactions = (timelineSet: EventTimelineSet, eventId: string export type ReactionGroup = { key: string; users: Set; + events: MessageEventWithoutRoomId[]; shortcode?: string; firstTs: number; }; export const getReactionGroups = ( reactions: MessageEventWithoutRoomId[] ): Array => { - const map = new Map(); + const groups = new Map(); reactions.forEach((event) => { const { key } = event.content['m.relates_to']; @@ -435,17 +436,19 @@ export const getReactionGroups = ( const { shortcode } = event.content; const ts = event.origin_server_ts; - const existing = map.get(key); + const existing = groups.get(key); if (!existing) { - map.set(key, { + groups.set(key, { key, users: new Set([userId]), + events: [event], shortcode, firstTs: ts, }); } else { existing.users.add(userId); + existing.events.push(event); if (!existing.shortcode && shortcode) { existing.shortcode = shortcode; @@ -458,7 +461,7 @@ export const getReactionGroups = ( } }); - return Array.from(map.values()).sort((a, b) => a.firstTs - b.firstTs); + return Array.from(groups.values()).sort((a, b) => a.firstTs - b.firstTs); }; export const getLatestEditEvent = ( diff --git a/src/client/room/local-event/LocalEvent.ts b/src/client/room/local-event/LocalEvent.ts index 275547ec..551c9875 100644 --- a/src/client/room/local-event/LocalEvent.ts +++ b/src/client/room/local-event/LocalEvent.ts @@ -10,8 +10,8 @@ export class LocalMessage { } } -export class LocalEvent { - public readonly original: LocalMessage; +export class LocalEvent { + public readonly original: LocalMessage; public readonly wire: LocalMessage; @@ -19,7 +19,7 @@ export class LocalEvent { public readonly ts: number; - constructor(original: LocalMessage, wire: LocalMessage, txnId: string, ts: number) { + constructor(original: LocalMessage, wire: LocalMessage, txnId: string, ts: number) { this.original = original; this.wire = wire; this.txnId = txnId; diff --git a/src/client/room/local-event/LocalEventSender.ts b/src/client/room/local-event/LocalEventSender.ts index 9d885d76..7126823c 100644 --- a/src/client/room/local-event/LocalEventSender.ts +++ b/src/client/room/local-event/LocalEventSender.ts @@ -30,8 +30,8 @@ export type LocalEventSenderState = | EventSenderSuccess | EventSenderError; -export class LocalEventSender { - public readonly localEvent: LocalEvent; +export class LocalEventSender { + public readonly localEvent: LocalEvent; private readonly request: MatrixRequest; @@ -41,7 +41,7 @@ export class LocalEventSender { private sending = false; - constructor(localEvent: LocalEvent, request: MatrixRequest) { + constructor(localEvent: LocalEvent, request: MatrixRequest) { this.localEvent = localEvent; this.request = request; this.state = new ObservableValue(new EventSenderIdle(this.send.bind(this)), this.publishKey);