-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathThreadDrawer.tsx
More file actions
880 lines (824 loc) · 30.3 KB
/
ThreadDrawer.tsx
File metadata and controls
880 lines (824 loc) · 30.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
import { MouseEventHandler, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Box, Header, Icon, IconButton, Icons, Scroll, Text, config } from 'folds';
import {
MatrixEvent,
PushProcessor,
ReceiptType,
RelationType,
Room,
RoomEvent,
ThreadEvent,
} from '$types/matrix-sdk';
import { useAtomValue, useSetAtom } from 'jotai';
import { ReactEditor } from 'slate-react';
import { HTMLReactParserOptions } from 'html-react-parser';
import { Opts as LinkifyOpts } from 'linkifyjs';
import { ImageContent, MSticker, RedactedContent, Reply } from '$components/message';
import { RenderMessageContent } from '$components/RenderMessageContent';
import { Image } from '$components/media';
import { ImageViewer } from '$components/image-viewer';
import { ClientSideHoverFreeze } from '$components/ClientSideHoverFreeze';
import {
factoryRenderLinkifyWithMention,
getReactCustomHtmlParser,
LINKIFY_OPTS,
makeMentionCustomProps,
renderMatrixMention,
} from '$plugins/react-custom-html-parser';
import {
getEditedEvent,
getEventReactions,
getMemberDisplayName,
reactionOrEditEvent,
} from '$utils/room';
import { getMxIdLocalPart, toggleReaction } from '$utils/matrix';
import { minuteDifference } from '$utils/time';
import { useMatrixClient } from '$hooks/useMatrixClient';
import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
import { nicknamesAtom } from '$state/nicknames';
import { MessageLayout, MessageSpacing, settingsAtom } from '$state/settings';
import { useSetting } from '$state/hooks/settings';
import { createMentionElement, moveCursor, useEditor } from '$components/editor';
import { useMentionClickHandler } from '$hooks/useMentionClickHandler';
import { useSpoilerClickHandler } from '$hooks/useSpoilerClickHandler';
import { GetContentCallback, MessageEvent, StateEvent } from '$types/matrix/room';
import { usePowerLevelsContext } from '$hooks/usePowerLevels';
import { useRoomPermissions } from '$hooks/useRoomPermissions';
import { useRoomCreators } from '$hooks/useRoomCreators';
import { useImagePackRooms } from '$hooks/useImagePackRooms';
import { useOpenUserRoomProfile } from '$state/hooks/userRoomProfile';
import { IReplyDraft, roomIdToReplyDraftAtomFamily } from '$state/room/roomInputDrafts';
import { roomToParentsAtom } from '$state/room/roomToParents';
import { EncryptedContent, Message, Reactions } from './message';
import { RoomInput } from './RoomInput';
import { RoomViewFollowing, RoomViewFollowingPlaceholder } from './RoomViewFollowing';
import * as css from './ThreadDrawer.css';
/**
* Resolve the list of reply events to show in the thread drawer.
*
* Prefers events from the SDK Thread object (authoritative, full history) but
* falls back to scanning the main room timeline when the Thread object was
* created without `initialEvents` (as happens with classic sync). In that
* case `thread.events` contains only the root event, so filtering it yields an
* empty array — we must fall back rather than showing nothing.
*
* Exported for unit testing.
*/
export function getThreadReplyEvents(room: Room, threadRootId: string): MatrixEvent[] {
const thread = room.getThread(threadRootId);
const fromThread = thread?.events ?? [];
const filteredFromThread = fromThread.filter(
(ev) => ev.getId() !== threadRootId && !reactionOrEditEvent(ev)
);
if (filteredFromThread.length > 0) {
return filteredFromThread;
}
return room
.getUnfilteredTimelineSet()
.getLiveTimeline()
.getEvents()
.filter(
(ev) =>
ev.threadRootId === threadRootId && ev.getId() !== threadRootId && !reactionOrEditEvent(ev)
);
}
type ForwardedMessageProps = {
isForwarded: boolean;
originalTimestamp: number;
originalRoomId: string;
originalEventId: string;
originalEventPrivate: boolean;
};
type ThreadMessageProps = {
room: Room;
mEvent: MatrixEvent;
threadRootId: string;
editId: string | undefined;
onEditId: (id?: string) => void;
messageLayout: MessageLayout;
messageSpacing: MessageSpacing;
canDelete: boolean;
canSendReaction: boolean;
canPinEvent: boolean;
imagePackRooms: Room[];
activeReplyId: string | undefined;
hour24Clock: boolean;
dateFormatString: string;
onUserClick: MouseEventHandler<HTMLButtonElement>;
onUsernameClick: MouseEventHandler<HTMLButtonElement>;
onReplyClick: MouseEventHandler<HTMLButtonElement>;
onReactionToggle: (targetEventId: string, key: string, shortcode?: string) => void;
onResend?: (event: MatrixEvent) => void;
onDeleteFailedSend?: (event: MatrixEvent) => void;
pushProcessor: PushProcessor;
linkifyOpts: LinkifyOpts;
htmlReactParserOptions: HTMLReactParserOptions;
showHideReads: boolean;
showDeveloperTools: boolean;
onReferenceClick: MouseEventHandler<HTMLButtonElement>;
jumpToEventId?: string;
collapse?: boolean;
};
function ThreadMessage({
room,
threadRootId: threadRootIdProp,
mEvent,
editId,
onEditId,
messageLayout,
messageSpacing,
canDelete,
canSendReaction,
collapse = false,
canPinEvent,
imagePackRooms,
activeReplyId,
hour24Clock,
dateFormatString,
onUserClick,
onUsernameClick,
onReplyClick,
onReactionToggle,
onResend,
onDeleteFailedSend,
pushProcessor,
linkifyOpts,
htmlReactParserOptions,
showHideReads,
showDeveloperTools,
onReferenceClick,
jumpToEventId,
}: ThreadMessageProps) {
// Use the thread's own timeline set so reactions/edits on thread events are found correctly
const threadTimelineSet = room.getThread(threadRootIdProp)?.timelineSet;
const timelineSet = threadTimelineSet ?? room.getUnfilteredTimelineSet();
const mEventId = mEvent.getId()!;
const senderId = mEvent.getSender() ?? '';
const nicknames = useAtomValue(nicknamesAtom);
const senderDisplayName =
getMemberDisplayName(room, senderId, nicknames) ?? getMxIdLocalPart(senderId) ?? senderId;
const [mediaAutoLoad] = useSetting(settingsAtom, 'mediaAutoLoad');
const [urlPreview] = useSetting(settingsAtom, 'urlPreview');
const [encUrlPreview] = useSetting(settingsAtom, 'encUrlPreview');
const showUrlPreview = room.hasEncryptionStateEvent() ? encUrlPreview : urlPreview;
const [autoplayStickers] = useSetting(settingsAtom, 'autoplayStickers');
const editedEvent = getEditedEvent(mEventId, mEvent, timelineSet);
const editedNewContent = editedEvent?.getContent()['m.new_content'];
const baseContent = mEvent.getContent();
const safeContent =
Object.keys(baseContent).length > 0 ? baseContent : mEvent.getOriginalContent();
const getContent = (() => editedNewContent ?? safeContent) as GetContentCallback;
const reactionRelations = getEventReactions(timelineSet, mEventId);
const reactions = reactionRelations?.getSortedAnnotationsByKey();
const hasReactions = reactions && reactions.length > 0;
const pushActions = pushProcessor.actionsForEvent(mEvent);
let notifyHighlight: 'silent' | 'loud' | undefined;
if (pushActions?.notify && pushActions.tweaks?.highlight) {
notifyHighlight = pushActions.tweaks?.sound ? 'loud' : 'silent';
}
// Extract message forwarding info
const forwardContent = safeContent['moe.sable.message.forward'] as
| {
original_timestamp?: unknown;
original_room_id?: string;
original_event_id?: string;
original_event_private?: boolean;
}
| undefined;
const messageForwardedProps: ForwardedMessageProps | undefined = forwardContent
? {
isForwarded: true,
originalTimestamp:
typeof forwardContent.original_timestamp === 'number'
? forwardContent.original_timestamp
: mEvent.getTs(),
originalRoomId: forwardContent.original_room_id ?? room.roomId,
originalEventId: forwardContent.original_event_id ?? '',
originalEventPrivate: forwardContent.original_event_private ?? false,
}
: undefined;
const { replyEventId } = mEvent;
const relation = mEvent.getRelation();
const contentRelatesTo = mEvent.getContent()?.['m.relates_to'];
const isFallback =
relation?.is_falling_back === true || contentRelatesTo?.is_falling_back === true;
return (
<Message
key={mEvent.getId()}
data-message-id={mEventId}
room={room}
mEvent={mEvent}
messageSpacing={messageSpacing}
messageLayout={messageLayout}
collapse={collapse}
highlight={jumpToEventId === mEventId}
notifyHighlight={notifyHighlight}
edit={editId === mEventId}
canDelete={canDelete}
canSendReaction={canSendReaction}
canPinEvent={canPinEvent}
imagePackRooms={imagePackRooms}
relations={hasReactions ? reactionRelations : undefined}
onUserClick={onUserClick}
onUsernameClick={onUsernameClick}
onReplyClick={onReplyClick}
onReactionToggle={onReactionToggle}
onEditId={onEditId}
senderId={senderId}
senderDisplayName={senderDisplayName}
messageForwardedProps={messageForwardedProps}
sendStatus={mEvent.getAssociatedStatus()}
onResend={onResend}
onDeleteFailedSend={onDeleteFailedSend}
activeReplyId={activeReplyId ?? null}
hour24Clock={hour24Clock}
dateFormatString={dateFormatString}
hideReadReceipts={showHideReads}
showDeveloperTools={showDeveloperTools}
reply={
replyEventId &&
!isFallback && (
<Reply
room={room}
timelineSet={timelineSet}
replyEventId={replyEventId}
onClick={onReferenceClick}
/>
)
}
reactions={
hasReactions ? (
<Reactions
style={{ marginTop: config.space.S200 }}
room={room}
relations={reactionRelations!}
mEventId={mEventId}
canSendReaction={canSendReaction}
canDeleteOwn={canDelete}
onReactionToggle={onReactionToggle}
/>
) : undefined
}
>
{mEvent.isRedacted() ? (
<RedactedContent reason={mEvent.getUnsigned().redacted_because?.content.reason} />
) : (
<EncryptedContent mEvent={mEvent}>
{() => {
if (mEvent.isRedacted())
return (
<RedactedContent reason={mEvent.getUnsigned().redacted_because?.content.reason} />
);
if (mEvent.getType() === MessageEvent.Sticker)
return (
<MSticker
content={mEvent.getContent()}
renderImageContent={(props) => (
<ImageContent
{...props}
autoPlay={mediaAutoLoad}
renderImage={(p) => {
if (!autoplayStickers && p.src) {
return (
<ClientSideHoverFreeze src={p.src}>
<Image {...p} loading="lazy" />
</ClientSideHoverFreeze>
);
}
return <Image {...p} loading="lazy" />;
}}
renderViewer={(p) => <ImageViewer {...p} />}
/>
)}
/>
);
if (mEvent.getType() === MessageEvent.RoomMessage) {
return (
<RenderMessageContent
displayName={senderDisplayName}
msgType={(editedNewContent ?? safeContent).msgtype ?? ''}
ts={mEvent.getTs()}
edited={!!editedEvent}
getContent={getContent}
mediaAutoLoad={mediaAutoLoad}
urlPreview={showUrlPreview}
htmlReactParserOptions={htmlReactParserOptions}
linkifyOpts={linkifyOpts}
outlineAttachment={messageLayout === MessageLayout.Bubble}
/>
);
}
return (
<RenderMessageContent
displayName={senderDisplayName}
msgType={(editedNewContent ?? safeContent).msgtype ?? ''}
ts={mEvent.getTs()}
edited={!!editedEvent}
getContent={getContent}
mediaAutoLoad={mediaAutoLoad}
urlPreview={showUrlPreview}
htmlReactParserOptions={htmlReactParserOptions}
linkifyOpts={linkifyOpts}
outlineAttachment={messageLayout === MessageLayout.Bubble}
/>
);
}}
</EncryptedContent>
)}
</Message>
);
}
type ThreadDrawerProps = {
room: Room;
threadRootId: string;
onClose: () => void;
overlay?: boolean;
};
export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDrawerProps) {
const mx = useMatrixClient();
const drawerRef = useRef<HTMLDivElement>(null);
const editor = useEditor();
const [, forceUpdate] = useState(0);
const [editId, setEditId] = useState<string | undefined>(undefined);
const [jumpToEventId, setJumpToEventId] = useState<string | undefined>(undefined);
const scrollRef = useRef<HTMLDivElement>(null);
const prevReplyCountRef = useRef(0);
const replyEventsRef = useRef<MatrixEvent[]>([]);
const nicknames = useAtomValue(nicknamesAtom);
const pushProcessor = useMemo(() => new PushProcessor(mx), [mx]);
const useAuthentication = useMediaAuthentication();
const mentionClickHandler = useMentionClickHandler(room.roomId);
const spoilerClickHandler = useSpoilerClickHandler();
// Settings
const [messageLayout] = useSetting(settingsAtom, 'messageLayout');
const [messageSpacing] = useSetting(settingsAtom, 'messageSpacing');
const [hour24Clock] = useSetting(settingsAtom, 'hour24Clock');
const [dateFormatString] = useSetting(settingsAtom, 'dateFormatString');
const [hideReads] = useSetting(settingsAtom, 'hideReads');
const [showDeveloperTools] = useSetting(settingsAtom, 'developerTools');
// Memoized parsing options
const linkifyOpts = useMemo<LinkifyOpts>(
() => ({
...LINKIFY_OPTS,
render: factoryRenderLinkifyWithMention((href) =>
renderMatrixMention(
mx,
room.roomId,
href,
makeMentionCustomProps(mentionClickHandler),
nicknames
)
),
}),
[mx, room, mentionClickHandler, nicknames]
);
const htmlReactParserOptions = useMemo<HTMLReactParserOptions>(
() =>
getReactCustomHtmlParser(mx, room.roomId, {
linkifyOpts,
useAuthentication,
handleSpoilerClick: spoilerClickHandler,
handleMentionClick: mentionClickHandler,
nicknames,
}),
[mx, room, linkifyOpts, spoilerClickHandler, mentionClickHandler, useAuthentication, nicknames]
);
// Power levels & permissions
const powerLevels = usePowerLevelsContext();
const creators = useRoomCreators(room);
const permissions = useRoomPermissions(creators, powerLevels);
const canRedact = permissions.action('redact', mx.getSafeUserId());
const canDeleteOwn = permissions.event(MessageEvent.RoomRedaction, mx.getSafeUserId());
const canSendReaction = permissions.event(MessageEvent.Reaction, mx.getSafeUserId());
const canPinEvent = permissions.stateEvent(StateEvent.RoomPinnedEvents, mx.getSafeUserId());
// Image packs
const roomToParents = useAtomValue(roomToParentsAtom);
const imagePackRooms: Room[] = useImagePackRooms(room.roomId, roomToParents);
// Reply draft (keyed by threadRootId to match RoomInput's draftKey logic)
const setReplyDraft = useSetAtom(roomIdToReplyDraftAtomFamily(threadRootId));
const replyDraft = useAtomValue(roomIdToReplyDraftAtomFamily(threadRootId));
const activeReplyId = replyDraft?.eventId;
// User profile popup
const openUserRoomProfile = useOpenUserRoomProfile();
const rootEvent = room.findEventById(threadRootId);
// When the drawer is opened with classic sync (no server-side thread support),
// room.createThread() may have been called with empty initialEvents so
// thread.events only has the root. Backfill events from the main room
// timeline so the authoritative source is populated for subsequent renders.
//
// IMPORTANT: skip this backfill when server-side thread support is active
// (initialEventsFetched starts false). In that case the SDK will call
// updateThreadMetadata() → resetLiveTimeline() + paginateEventTimeline()
// automatically. Calling thread.addEvents() ourselves first would trigger
// that same cascade prematurely and cause a flood of
// "EventTimelineSet.addEventToTimeline: Ignoring event=…" warnings because
// canContain() fails while the timeline is in the middle of being reset and
// repopulated.
useEffect(() => {
const thread = room.getThread(threadRootId);
if (!thread) return;
// initialEventsFetched === false ↔ Thread.hasServerSideSupport is set.
// The SDK handles initialization itself; our manual backfill must not run.
if (!thread.initialEventsFetched) return;
const hasRepliesInThread = thread.events.some(
(ev) => ev.getId() !== threadRootId && !reactionOrEditEvent(ev)
);
if (hasRepliesInThread) return; // already populated, nothing to do
const liveEvents = room
.getUnfilteredTimelineSet()
.getLiveTimeline()
.getEvents()
.filter(
(ev) =>
ev.threadRootId === threadRootId &&
ev.getId() !== threadRootId &&
!reactionOrEditEvent(ev)
);
if (liveEvents.length > 0) {
thread.addEvents(liveEvents, false);
}
}, [room, threadRootId]);
// Re-render when new thread events arrive (including reactions via ThreadEvent.Update).
useEffect(() => {
const isEventInThread = (mEvent: MatrixEvent): boolean => {
// Direct thread message or the root itself
if (mEvent.threadRootId === threadRootId || mEvent.getId() === threadRootId) {
return true;
}
// Check if this is a reaction/edit targeting an event in this thread
if (reactionOrEditEvent(mEvent)) {
const relation = mEvent.getRelation();
const targetEventId = relation?.event_id;
if (targetEventId) {
const targetEvent = room.findEventById(targetEventId);
if (
targetEvent &&
(targetEvent.threadRootId === threadRootId || targetEvent.getId() === threadRootId)
) {
return true;
}
}
}
return false;
};
const onTimeline = (mEvent: MatrixEvent) => {
if (isEventInThread(mEvent)) {
forceUpdate((n) => n + 1);
}
};
const onRedaction = (mEvent: MatrixEvent) => {
// Redactions (removing reactions/messages) should also trigger updates
if (isEventInThread(mEvent)) {
forceUpdate((n) => n + 1);
}
};
const onThreadUpdate = () => forceUpdate((n) => n + 1);
mx.on(RoomEvent.Timeline, onTimeline as any);
room.on(RoomEvent.Redaction, onRedaction as any);
room.on(ThreadEvent.Update, onThreadUpdate as any);
room.on(ThreadEvent.NewReply, onThreadUpdate as any);
return () => {
mx.off(RoomEvent.Timeline, onTimeline as any);
room.removeListener(RoomEvent.Redaction, onRedaction as any);
room.removeListener(ThreadEvent.Update, onThreadUpdate as any);
room.removeListener(ThreadEvent.NewReply, onThreadUpdate as any);
};
}, [mx, room, threadRootId]);
// Mark thread as read when viewing it
useEffect(() => {
const markThreadAsRead = async () => {
const thread = room.getThread(threadRootId);
if (!thread) return;
const events = thread.events || [];
if (events.length === 0) return;
const lastEvent = events[events.length - 1];
if (!lastEvent || lastEvent.isSending()) return;
const userId = mx.getUserId();
if (!userId) return;
const readUpToId = thread.getEventReadUpTo(userId, false);
const lastEventId = lastEvent.getId();
// Only send receipt if we haven't already read up to the last event
if (readUpToId !== lastEventId) {
try {
await mx.sendReadReceipt(lastEvent, ReceiptType.Read);
} catch (err) {
// eslint-disable-next-line no-console
console.warn('Failed to send thread read receipt:', err);
}
}
};
// Mark as read when opened and when new messages arrive
markThreadAsRead();
}, [mx, room, threadRootId, forceUpdate]);
const replyEvents = getThreadReplyEvents(room, threadRootId);
replyEventsRef.current = replyEvents;
// Auto-scroll to bottom when event count grows (if the user is near the bottom).
useEffect(() => {
const el = scrollRef.current;
if (!el) return;
const isAtBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 150;
if (prevReplyCountRef.current === 0 || isAtBottom) {
el.scrollTop = el.scrollHeight;
}
prevReplyCountRef.current = replyEvents.length;
}, [replyEvents.length]);
const handleUserClick: MouseEventHandler<HTMLButtonElement> = useCallback(
(evt) => {
evt.preventDefault();
evt.stopPropagation();
const userId = evt.currentTarget.getAttribute('data-user-id');
if (!userId) return;
openUserRoomProfile(
room.roomId,
undefined,
userId,
evt.currentTarget.getBoundingClientRect()
);
},
[room, openUserRoomProfile]
);
const handleUsernameClick: MouseEventHandler<HTMLButtonElement> = useCallback(
(evt) => {
evt.preventDefault();
const userId = evt.currentTarget.getAttribute('data-user-id');
if (!userId) return;
const localNicknames = undefined; // will be resolved via getMemberDisplayName in editor
const name =
getMemberDisplayName(room, userId, localNicknames) ?? getMxIdLocalPart(userId) ?? userId;
editor.insertNode(
createMentionElement(
userId,
name.startsWith('@') ? name : `@${name}`,
userId === mx.getUserId()
)
);
ReactEditor.focus(editor);
moveCursor(editor);
},
[mx, room, editor]
);
const handleReplyClick: MouseEventHandler<HTMLButtonElement> = useCallback(
(evt) => {
const replyId = evt.currentTarget.getAttribute('data-event-id');
if (!replyId) {
// In thread mode, resetting means going back to base thread draft
setReplyDraft({
userId: mx.getUserId() ?? '',
eventId: threadRootId,
body: '',
relation: { rel_type: RelationType.Thread, event_id: threadRootId },
});
return;
}
const replyEvt = room.findEventById(replyId);
if (!replyEvt) return;
const editedReply = getEditedEvent(replyId, replyEvt, room.getUnfilteredTimelineSet());
const content = editedReply?.getContent()['m.new_content'] ?? replyEvt.getContent();
const { body, formatted_body: formattedBody } = content;
const senderId = replyEvt.getSender();
if (senderId) {
const draft: IReplyDraft = {
userId: senderId,
eventId: replyId,
body: typeof body === 'string' ? body : '',
formattedBody,
relation: { rel_type: RelationType.Thread, event_id: threadRootId },
};
// Only toggle off if we're actively replying to this event (non-empty body distinguishes
// a real reply draft from the seeded base-thread draft, which has body: '').
if (activeReplyId === replyId && replyDraft?.body) {
// Toggle off — reset to base thread draft
setReplyDraft({
userId: mx.getUserId() ?? '',
eventId: threadRootId,
body: '',
relation: { rel_type: RelationType.Thread, event_id: threadRootId },
});
} else {
setReplyDraft(draft);
}
}
},
[mx, room, setReplyDraft, activeReplyId, threadRootId, replyDraft]
);
const handleReactionToggle = useCallback(
(targetEventId: string, key: string, shortcode?: string) => {
const threadTimelineSet = room.getThread(threadRootId)?.timelineSet;
toggleReaction(mx, room, targetEventId, key, shortcode, threadTimelineSet);
},
[mx, room, threadRootId]
);
const handleEdit = useCallback(
(evtId?: string) => {
setEditId(evtId);
if (!evtId) {
ReactEditor.focus(editor);
moveCursor(editor);
}
},
[editor]
);
const handleResend = useCallback(
(event: MatrixEvent) => {
mx.resendEvent(event, room);
},
[mx, room]
);
const handleDeleteFailedSend = useCallback(
(event: MatrixEvent) => {
mx.cancelPendingEvent(event);
},
[mx]
);
const handleOpenReply: MouseEventHandler<HTMLButtonElement> = useCallback(
(evt) => {
const targetId = evt.currentTarget.getAttribute('data-event-id');
if (!targetId) return;
const isRoot = targetId === threadRootId;
const isInReplies = replyEventsRef.current.some((e) => e.getId() === targetId);
if (!isRoot && !isInReplies) return;
setJumpToEventId(targetId);
setTimeout(() => setJumpToEventId(undefined), 2500);
const el = drawerRef.current;
if (el) {
const target = el.querySelector(`[data-message-id="${targetId}"]`);
target?.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
}
},
[threadRootId]
);
const sharedMessageProps = {
room,
threadRootId,
editId,
onEditId: handleEdit,
messageLayout,
messageSpacing,
canDelete: canRedact || canDeleteOwn,
canSendReaction,
canPinEvent,
imagePackRooms,
activeReplyId,
hour24Clock,
dateFormatString,
onUserClick: handleUserClick,
onUsernameClick: handleUsernameClick,
onReplyClick: handleReplyClick,
onReactionToggle: handleReactionToggle,
onResend: handleResend,
onDeleteFailedSend: handleDeleteFailedSend,
pushProcessor,
linkifyOpts,
htmlReactParserOptions,
showHideReads: hideReads,
showDeveloperTools,
onReferenceClick: handleOpenReply,
jumpToEventId,
};
// Latest thread event for the following indicator (latest reply, or root if no replies)
const threadParticipantIds = new Set(
[rootEvent, ...replyEvents].map((ev) => ev?.getSender()).filter(Boolean) as string[]
);
const latestThreadEventId = (
replyEvents.length > 0 ? replyEvents[replyEvents.length - 1] : rootEvent
)?.getId();
return (
<Box
ref={drawerRef}
className={overlay ? css.ThreadDrawerOverlay : css.ThreadDrawer}
direction="Column"
shrink="No"
>
{/* Header */}
<Header className={css.ThreadDrawerHeader} variant="Background" size="600">
<Box grow="Yes" alignItems="Center" gap="200">
<Icon size="200" src={Icons.Thread} />
<Text size="H4" truncate>
Thread
</Text>
</Box>
<Box alignItems="Center" gap="200" shrink="No">
<Text size="T300" priority="300" truncate>
# {room.name}
</Text>
<IconButton
onClick={onClose}
variant="SurfaceVariant"
size="300"
radii="300"
aria-label="Close thread"
>
<Icon size="200" src={Icons.Cross} />
</IconButton>
</Box>
</Header>
{/* Thread root message */}
{rootEvent && (
<Scroll
variant="Background"
visibility="Hover"
direction="Vertical"
hideTrack
style={{
maxHeight: '200px',
height: 'fit-content',
flexShrink: 0,
}}
>
<Box
className={css.messageList}
direction="Column"
style={{
padding: `${config.space.S200} 0 ${config.space.S100} 0`,
}}
>
<ThreadMessage {...sharedMessageProps} mEvent={rootEvent} />
</Box>
</Scroll>
)}
{/* Replies */}
<Box className={css.ThreadDrawerContent} grow="Yes" direction="Column">
<Scroll
ref={scrollRef}
variant="Background"
visibility="Hover"
direction="Vertical"
hideTrack
style={{ flexGrow: 1 }}
>
{replyEvents.length === 0 ? (
<Box
direction="Column"
alignItems="Center"
justifyContent="Center"
style={{ padding: config.space.S400, gap: config.space.S200 }}
>
<Icon size="400" src={Icons.Thread} />
<Text size="T300" align="Center">
No replies yet. Start the thread below!
</Text>
</Box>
) : (
<>
{/* Reply count label inside scroll area */}
<Box
style={{
padding: `${config.space.S200} ${config.space.S400}`,
flexShrink: 0,
}}
>
<Text size="T300" priority="300">
{replyEvents.length} {replyEvents.length === 1 ? 'reply' : 'replies'}
</Text>
</Box>
<Box
className={css.messageList}
direction="Column"
style={{ padding: `0 0 ${config.space.S600} 0` }}
>
{replyEvents.map((mEvent, i) => {
const prevEvent = i > 0 ? replyEvents[i - 1] : undefined;
const collapse =
prevEvent !== undefined &&
prevEvent.getSender() === mEvent.getSender() &&
prevEvent.getType() === mEvent.getType() &&
minuteDifference(prevEvent.getTs(), mEvent.getTs()) < 2;
return (
<ThreadMessage
key={mEvent.getId()}
{...sharedMessageProps}
mEvent={mEvent}
collapse={collapse}
/>
);
})}
</Box>
</>
)}
</Scroll>
</Box>
{/* Thread input */}
<Box className={css.ThreadDrawerInput} direction="Column" shrink="No">
<div style={{ padding: `0 ${config.space.S400}` }}>
<RoomInput
key={threadRootId}
room={room}
roomId={room.roomId}
threadRootId={threadRootId}
editor={editor}
fileDropContainerRef={drawerRef}
/>
</div>
{hideReads ? (
<RoomViewFollowingPlaceholder />
) : (
<RoomViewFollowing
room={room}
threadEventId={latestThreadEventId}
participantIds={threadParticipantIds}
/>
)}
</Box>
</Box>
);
}