allow reactions in timeline

This commit is contained in:
Ajay Bura 2026-08-31 15:18:24 +05:30
commit f59332cf99
9 changed files with 358 additions and 91 deletions

View file

@ -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,

View file

@ -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) => (
<Box
as="button"
className={classNames(css.Reaction, className)}
alignItems="Center"
shrink="No"
gap="200"
{...props}
ref={ref}
>
<Text className={css.ReactionText} as="span" size="T400">
{reaction.startsWith('mxc://') ? (
<img
className={css.ReactionImg}
src={mxcToHttp(ct.session.baseUrl, reaction, useAuthentication).url() ?? reaction}
alt={reaction}
/>
) : (
<Text as="span" size="Inherit" truncate>
{reaction}
</Text>
)}
</Text>
<Text as="span" size="T300">
{count}
</Text>
</Box>
));
>(({ className, count, adding, removing, reaction, ...props }, ref) => {
const ct = useClient();
const useAuthentication = useMediaAuthentication();
return (
<Box
as="button"
className={classNames(css.Reaction, className)}
alignItems="Center"
shrink="No"
gap="200"
{...props}
ref={ref}
>
<Text
className={classNames(css.ReactionText, { [css.ReactionChangeAnimation]: adding })}
as="span"
size="T400"
>
{reaction.startsWith('mxc://') ? (
<img
className={css.ReactionImg}
src={mxcToHttp(ct.session.baseUrl, reaction, useAuthentication).url() ?? reaction}
alt={reaction}
/>
) : (
<Text as="span" size="Inherit" truncate>
{reaction}
</Text>
)}
</Text>
<Text
className={classNames({ [css.ReactionChangeAnimation]: removing })}
as="span"
size="T300"
>
{count}
</Text>
</Box>
);
});
type ReactionTooltipMsgProps = {
reaction: string;

View file

@ -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 && (
<Reactions
style={{ marginTop: config.space.S200 }}
roomId={roomId}
reactions={reactionEvents}
eventId={event.event_id}
canSendReaction={canSendReaction}
onReactionToggle={handleReactionToggle}
canRedactReaction={canRedact || canDeleteOwn}
/>
);

View file

@ -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;
};

View file

@ -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<HTMLButtonElement>;
disabled?: boolean;
};
function ReactionUnpressed({
roomId,
eventId,
reaction,
onViewReaction,
disabled,
}: ReactionUnpressedProps) {
const ct = useClient();
const [sender, setSender] = useState<LocalEventSender<ReactionContent>>();
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 (
<TooltipProvider
key={reaction.key}
position="Top"
tooltip={
<Tooltip style={{ maxWidth: toRem(200) }}>
<Text className={css.ReactionsTooltipText} size="T300">
<ReactionTooltipMsg
shortcode={reaction.shortcode}
reaction={reaction.key}
users={Array.from(reaction.users)}
/>
</Text>
</Tooltip>
}
>
{(targetRef) => (
<Reaction
ref={targetRef}
data-reaction-key={reaction.key}
aria-pressed={!!sender}
reaction={reaction.key}
count={sender ? reaction.users.size + 1 : reaction.users.size}
adding={!!sender}
onClick={disabled ? undefined : handleToggleReaction}
onContextMenu={onViewReaction}
aria-disabled={disabled}
/>
)}
</TooltipProvider>
);
}
type ReactionPressedProps = {
roomId: string;
redactEventId: string;
reaction: ReactionGroup;
onViewReaction: MouseEventHandler<HTMLButtonElement>;
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 (
<TooltipProvider
key={reaction.key}
position="Top"
tooltip={
<Tooltip style={{ maxWidth: toRem(200) }}>
<Text className={css.ReactionsTooltipText} size="T300">
<ReactionTooltipMsg
shortcode={reaction.shortcode}
reaction={reaction.key}
users={Array.from(reaction.users)}
/>
</Text>
</Tooltip>
}
>
{(targetRef) => (
<Reaction
ref={targetRef}
data-reaction-key={reaction.key}
aria-pressed={!redactState}
reaction={reaction.key}
count={redactState ? reaction.users.size - 1 : reaction.users.size}
removing={!!redactState}
onClick={disabled ? undefined : handleToggleReaction}
onContextMenu={onViewReaction}
aria-disabled={disabled}
/>
)}
</TooltipProvider>
);
}
export type ReactionsProps = {
roomId: string;
eventId: string;
canSendReaction?: boolean;
canRedactReaction?: boolean;
reactions: MessageEventWithoutRoomId<ReactionContent>[];
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<boolean | string>(false);
const handleViewReaction: MouseEventHandler<HTMLButtonElement> = (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 (
<TooltipProvider
return myReactionEvent ? (
<ReactionPressed
key={reaction.key}
position="Top"
tooltip={
<Tooltip style={{ maxWidth: toRem(200) }}>
<Text className={css.ReactionsTooltipText} size="T300">
<ReactionTooltipMsg
shortcode={reaction.shortcode}
reaction={reaction.key}
users={Array.from(reaction.users)}
/>
</Text>
</Tooltip>
}
>
{(targetRef) => (
<Reaction
ref={targetRef}
data-reaction-key={reaction.key}
aria-pressed={isPressed}
key={reaction.key}
ct={ct}
reaction={reaction.key}
count={reaction.users.size}
onClick={
canSendReaction ? () => onReactionToggle(eventId, reaction.key) : undefined
}
onContextMenu={handleViewReaction}
aria-disabled={!canSendReaction}
useAuthentication={useAuthentication}
/>
)}
</TooltipProvider>
roomId={roomId}
redactEventId={myReactionEvent.event_id}
reaction={reaction}
onViewReaction={handleViewReaction}
disabled={!canRedactReaction}
/>
) : (
<ReactionUnpressed
key={reaction.key}
roomId={roomId}
eventId={eventId}
reaction={reaction}
onViewReaction={handleViewReaction}
disabled={!canSendReaction}
/>
);
})}
{reactions.length > 0 && (

View file

@ -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 && (
<Reactions
style={{ marginTop: config.space.S200 }}
roomId={roomId}
reactions={reactionEvents}
eventId={event.event_id}
canSendReaction={canSendReaction}
onReactionToggle={handleReactionToggle}
canRedactReaction={canRedact || canDeleteOwn}
/>
);

View file

@ -421,13 +421,14 @@ export const getEventReactions = (timelineSet: EventTimelineSet, eventId: string
export type ReactionGroup = {
key: string;
users: Set<string>;
events: MessageEventWithoutRoomId<ReactionContent>[];
shortcode?: string;
firstTs: number;
};
export const getReactionGroups = (
reactions: MessageEventWithoutRoomId<ReactionContent>[]
): Array<ReactionGroup> => {
const map = new Map<string, ReactionGroup>();
const groups = new Map<string, ReactionGroup>();
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 = (

View file

@ -10,8 +10,8 @@ export class LocalMessage<TContent extends object = object> {
}
}
export class LocalEvent {
public readonly original: LocalMessage;
export class LocalEvent<TContent extends object = object> {
public readonly original: LocalMessage<TContent>;
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<TContent>, wire: LocalMessage, txnId: string, ts: number) {
this.original = original;
this.wire = wire;
this.txnId = txnId;

View file

@ -30,8 +30,8 @@ export type LocalEventSenderState =
| EventSenderSuccess
| EventSenderError;
export class LocalEventSender {
public readonly localEvent: LocalEvent;
export class LocalEventSender<TContent extends object = object> {
public readonly localEvent: LocalEvent<TContent>;
private readonly request: MatrixRequest;
@ -41,7 +41,7 @@ export class LocalEventSender {
private sending = false;
constructor(localEvent: LocalEvent, request: MatrixRequest) {
constructor(localEvent: LocalEvent<TContent>, request: MatrixRequest) {
this.localEvent = localEvent;
this.request = request;
this.state = new ObservableValue(new EventSenderIdle(this.send.bind(this)), this.publishKey);