mirror of
https://github.com/SableClient/Sable.git
synced 2026-12-06 00:32:26 -08:00
redact events optimistically and reduce timeline flicker maybe (#1977)
<!-- Please read https://github.com/SableClient/Sable/blob/dev/CONTRIBUTING.md before submitting your pull request --> ### Description <!-- Please include a summary of the change. Please also include relevant motivation and context. List any dependencies that are required for this change. --> Optimistically redacts events/reactions and hopefully reduces the timeline flicker a little by removing some isReady gating and things #### Type of change - [x] Bug fix (non-breaking change which fixes an issue) - [ ] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [ ] This change requires a documentation update ### Checklist: - [ ] My code follows the style guidelines of this project - [ ] I have performed a self-review of my own code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [ ] My changes generate no new warnings ### AI disclosure: - [ ] Partially AI assisted (clarify which code was AI assisted and briefly explain what it does). - [ ] Fully AI generated (explain what all the generated code does in moderate detail). <!-- Write any explanation required here, but do not generate the explanation using AI!! You must prove you understand what the code in this PR does. -->
This commit is contained in:
8 files changed
+150
-84
No files matched your search
@@ -21,6 +21,7 @@ import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback';
|
||||
import { modalAtom, ModalType } from '$state/modal';
|
||||
import * as css from '$features/room/message/styles.css';
|
||||
import { createDebugLogger } from '$utils/debugLogger';
|
||||
import { optimisticallyRedactEvent } from '$utils/matrix';
|
||||
import * as Sentry from '@sentry/react';
|
||||
|
||||
const debugLog = createDebugLogger('MessageDelete');
|
||||
@@ -72,9 +73,9 @@ export function MessageDeleteInternal({ room, mEvent, onClose }: MessageDeleteIn
|
||||
|
||||
const [deleteState, deleteMessage] = useAsyncCallback(
|
||||
useCallback(
|
||||
(eventId: string, reason?: string) =>
|
||||
mx.redactEvent(room.roomId, eventId, undefined, reason ? { reason } : undefined),
|
||||
[mx, room]
|
||||
(reason?: string) =>
|
||||
optimisticallyRedactEvent(mx, room, mEvent, reason ? { reason } : undefined),
|
||||
[mx, room, mEvent]
|
||||
)
|
||||
);
|
||||
|
||||
@@ -106,7 +107,7 @@ export function MessageDeleteInternal({ room, mEvent, onClose }: MessageDeleteIn
|
||||
|
||||
debugLog.info('ui', 'Deleting message', { eventId, hasReason: !!reason });
|
||||
Sentry.metrics.count('sable.message.delete.attempt', 1);
|
||||
deleteMessage(eventId, reason);
|
||||
deleteMessage(reason);
|
||||
};
|
||||
|
||||
return (
|
||||
|
||||
@@ -46,6 +46,7 @@ const {
|
||||
},
|
||||
timelineSync: {
|
||||
eventsLength: 1,
|
||||
timelineVersion: 0,
|
||||
timeline: { linkedTimelines: [] },
|
||||
liveTimelineLinked: true,
|
||||
backwardStatus: 'idle',
|
||||
@@ -940,13 +941,13 @@ describe('MemoizedTimelineItem', () => {
|
||||
});
|
||||
|
||||
describe('jump reveal and focus-regain read receipts', () => {
|
||||
it('keeps the timeline hidden while a jump is still pending', () => {
|
||||
it('keeps rendering the timeline while a jump is still pending', () => {
|
||||
timelineSync.jumpFailed = false;
|
||||
const { getByText } = render(
|
||||
<RoomTimeline room={room} editor={{} as Editor} eventId="$jump:example.org" />
|
||||
);
|
||||
|
||||
expect(getByText('canRedact:false hideReads:false')).not.toBeVisible();
|
||||
expect(getByText('canRedact:false hideReads:false')).toBeVisible();
|
||||
});
|
||||
|
||||
it('restarts a route jump when the Room instance is replaced with the same id', () => {
|
||||
@@ -963,12 +964,12 @@ describe('jump reveal and focus-regain read receipts', () => {
|
||||
expect(timelineSync.loadEventTimeline).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('reveals the timeline when the jump fails instead of leaving a blank room', () => {
|
||||
it('keeps the timeline visible when the jump fails', () => {
|
||||
timelineSync.jumpFailed = false;
|
||||
const { getByText, rerender } = render(
|
||||
<RoomTimeline room={room} editor={{} as Editor} eventId="$jump:example.org" />
|
||||
);
|
||||
expect(getByText('canRedact:false hideReads:false')).not.toBeVisible();
|
||||
expect(getByText('canRedact:false hideReads:false')).toBeVisible();
|
||||
|
||||
timelineSync.jumpFailed = true;
|
||||
act(() => {
|
||||
|
||||
@@ -773,11 +773,9 @@ export function RoomTimeline({
|
||||
);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!isReady) return;
|
||||
if (timelineSync.eventsLength > 0) return;
|
||||
setIsReady(false);
|
||||
hasInitialScrolledRef.current = false;
|
||||
}, [isReady, timelineSync.eventsLength]);
|
||||
}, [timelineSync.eventsLength]);
|
||||
|
||||
const recalcTopSpacer = useCallback(() => {
|
||||
const v = vListRef.current;
|
||||
@@ -886,7 +884,6 @@ export function RoomTimeline({
|
||||
|
||||
useEffect(() => {
|
||||
if (!eventId) return;
|
||||
if (!timelineSyncRef.current.jumpFailed) setIsReady(false);
|
||||
jumpToEvent(eventId);
|
||||
}, [eventId, room, jumpToEvent]);
|
||||
|
||||
@@ -1324,15 +1321,15 @@ export function RoomTimeline({
|
||||
if (showLoadingPlaceholders) vListItemCount = 3;
|
||||
// One row so the error and its Retry have somewhere to render.
|
||||
else if (showEmptyPaginationError) vListItemCount = 1;
|
||||
const vListIndices = useMemo(() => {
|
||||
// Keep the cache-busting timeline identity explicit for exhaustive-deps.
|
||||
void timelineSync.timeline;
|
||||
return Array.from({ length: vListItemCount }, (_, i) => i);
|
||||
}, [vListItemCount, timelineSync.timeline]);
|
||||
const vListIndices = useMemo(
|
||||
() => Array.from({ length: vListItemCount }, (_, i) => i),
|
||||
[vListItemCount]
|
||||
);
|
||||
|
||||
const processedEvents = useProcessedTimeline({
|
||||
items: vListIndices,
|
||||
linkedTimelines: timelineSync.timeline.linkedTimelines,
|
||||
timelineVersion: timelineSync.timelineVersion,
|
||||
ignoredUsersSet,
|
||||
hiddenEvents,
|
||||
mxUserId: mx.getUserId(),
|
||||
@@ -1471,16 +1468,12 @@ export function RoomTimeline({
|
||||
width: '100%',
|
||||
overflow: 'hidden',
|
||||
position: 'relative',
|
||||
opacity:
|
||||
!hideTimelineForRoomState &&
|
||||
(isReady || showLoadingPlaceholders || showEmptyPaginationError)
|
||||
? 1
|
||||
: 0,
|
||||
opacity: hideTimelineForRoomState ? 0 : 1,
|
||||
}}
|
||||
>
|
||||
<TimelineScrollingProvider value={isTimelineScrolling}>
|
||||
<VList<ProcessedEvent>
|
||||
key={`${room.roomId}:${timelineSync.liveTimelineLinked ? 'live' : (timelineSync.focusItem?.eventId ?? scrollAnchorRef.current)}`}
|
||||
key={room.roomId}
|
||||
ref={vListRef}
|
||||
data={processedEvents}
|
||||
shift={shouldShift}
|
||||
@@ -1552,7 +1545,7 @@ export function RoomTimeline({
|
||||
</TimelineFloat>
|
||||
)}
|
||||
|
||||
{(!atBottomState || !timelineSync.liveTimelineLinked) && isReady && (
|
||||
{(!atBottomState || !timelineSync.liveTimelineLinked) && (
|
||||
<TimelineFloat position="Bottom">
|
||||
<Chip
|
||||
variant="SurfaceVariant"
|
||||
|
||||
@@ -35,6 +35,8 @@ export interface UseProcessedTimelineOptions {
|
||||
* where every reply legitimately has `threadRootId` set to the root.
|
||||
*/
|
||||
skipThreadFilter?: boolean;
|
||||
/** Bumped when displayed timeline events mutate in place (redactions, decrypt, reactions). */
|
||||
timelineVersion?: number;
|
||||
}
|
||||
|
||||
export interface ProcessedEvent {
|
||||
@@ -665,6 +667,7 @@ export function useProcessedTimeline({
|
||||
isReadOnly,
|
||||
hideMemberInReadOnly,
|
||||
skipThreadFilter,
|
||||
timelineVersion = 0,
|
||||
}: UseProcessedTimelineOptions): ProcessedEvent[] {
|
||||
const {
|
||||
showHiddenEvents,
|
||||
@@ -679,6 +682,7 @@ export function useProcessedTimeline({
|
||||
const cacheRef = useRef<ProcessingCache | undefined>(undefined);
|
||||
|
||||
return useMemo(() => {
|
||||
void timelineVersion;
|
||||
const timelineEvents = flattenTimelineEvents(linkedTimelines);
|
||||
const processingOptions: TimelineProcessingOptions = {
|
||||
ignoredUsersSet,
|
||||
@@ -814,5 +818,6 @@ export function useProcessedTimeline({
|
||||
isReadOnly,
|
||||
hideMemberInReadOnly,
|
||||
skipThreadFilter,
|
||||
timelineVersion,
|
||||
]);
|
||||
}
|
||||
@@ -532,7 +532,7 @@ describe('useTimelineSync', () => {
|
||||
|
||||
await act(async () => {
|
||||
emitLiveTimelineEvent(room, timeline, events, '@bob:test');
|
||||
await Promise.resolve();
|
||||
await flushRaf();
|
||||
});
|
||||
|
||||
expect(scrollToBottom).toHaveBeenCalledWith('smooth');
|
||||
@@ -560,7 +560,7 @@ describe('useTimelineSync', () => {
|
||||
|
||||
await act(async () => {
|
||||
emitLiveTimelineEvent(room, timeline, events, '@alice:test');
|
||||
await Promise.resolve();
|
||||
await flushRaf();
|
||||
});
|
||||
|
||||
expect(scrollToBottom).toHaveBeenCalledWith('instant');
|
||||
@@ -591,7 +591,7 @@ describe('useTimelineSync', () => {
|
||||
|
||||
await act(async () => {
|
||||
emitLiveTimelineEvent(room, timeline, events, '@bob:test');
|
||||
await Promise.resolve();
|
||||
await flushRaf();
|
||||
});
|
||||
|
||||
expect(setUnreadInfo).toHaveBeenCalledWith(unread);
|
||||
@@ -1273,7 +1273,7 @@ describe('live-arrive edge cases', () => {
|
||||
it('renders a stale non-live event appended to the live timeline', async () => {
|
||||
const { room, timeline, events } = createRoom();
|
||||
const { result } = renderSyncHook(room);
|
||||
const before = result.current.timeline;
|
||||
const before = result.current.timelineVersion;
|
||||
vi.mocked(isWindowFocused).mockReturnValue(true);
|
||||
await act(async () => {
|
||||
await flushRaf();
|
||||
@@ -1293,7 +1293,7 @@ describe('live-arrive edge cases', () => {
|
||||
await flushRaf();
|
||||
});
|
||||
|
||||
expect(result.current.timeline).not.toBe(before);
|
||||
expect(result.current.timelineVersion).toBeGreaterThan(before);
|
||||
expect(markAsRead).not.toHaveBeenCalled();
|
||||
vi.mocked(isWindowFocused).mockReturnValue(false);
|
||||
});
|
||||
@@ -1301,7 +1301,7 @@ describe('live-arrive edge cases', () => {
|
||||
it('renders a removal', async () => {
|
||||
const { room, timeline, events } = createRoom();
|
||||
const { result } = renderSyncHook(room);
|
||||
const before = result.current.timeline;
|
||||
const before = result.current.timelineVersion;
|
||||
|
||||
await act(async () => {
|
||||
events.pop();
|
||||
@@ -1309,10 +1309,10 @@ describe('live-arrive edge cases', () => {
|
||||
liveEvent: false,
|
||||
timeline,
|
||||
});
|
||||
await Promise.resolve();
|
||||
await flushRaf();
|
||||
});
|
||||
|
||||
expect(result.current.timeline).not.toBe(before);
|
||||
expect(result.current.timelineVersion).toBeGreaterThan(before);
|
||||
});
|
||||
|
||||
it('ignores events emitted for a thread timeline set', async () => {
|
||||
@@ -1320,7 +1320,7 @@ describe('live-arrive edge cases', () => {
|
||||
const otherSet = new EventEmitter() as FakeTimelineSet;
|
||||
const threadTimeline = { ...createTimeline(events), getTimelineSet: () => otherSet };
|
||||
const { result, scrollToBottom } = renderSyncHook(room);
|
||||
const before = result.current.timeline;
|
||||
const before = result.current.timelineVersion;
|
||||
|
||||
await act(async () => {
|
||||
room.emit(RoomEvent.Timeline, makeLiveEvent(room.roomId, Date.now()), room, false, false, {
|
||||
@@ -1330,14 +1330,14 @@ describe('live-arrive edge cases', () => {
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
expect(result.current.timeline).toBe(before);
|
||||
expect(result.current.timelineVersion).toBe(before);
|
||||
expect(scrollToBottom).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not treat a threaded reply as an arrival when it lands on the main set', async () => {
|
||||
const { room, timeline, events } = createRoom();
|
||||
const { result } = renderSyncHook(room);
|
||||
const before = result.current.timeline;
|
||||
const before = result.current.timelineVersion;
|
||||
vi.mocked(isWindowFocused).mockReturnValue(true);
|
||||
await act(async () => {
|
||||
await flushRaf();
|
||||
@@ -1363,7 +1363,7 @@ describe('live-arrive edge cases', () => {
|
||||
await flushRaf();
|
||||
});
|
||||
|
||||
expect(result.current.timeline).not.toBe(before);
|
||||
expect(result.current.timelineVersion).toBeGreaterThan(before);
|
||||
expect(markAsRead).not.toHaveBeenCalled();
|
||||
vi.mocked(isWindowFocused).mockReturnValue(false);
|
||||
});
|
||||
@@ -1378,7 +1378,7 @@ describe('live-arrive edge cases', () => {
|
||||
liveEvent: true,
|
||||
timeline,
|
||||
});
|
||||
await Promise.resolve();
|
||||
await flushRaf();
|
||||
});
|
||||
|
||||
expect(scrollToBottom).toHaveBeenCalledWith('instant');
|
||||
@@ -1461,7 +1461,7 @@ describe('live-arrive edge cases', () => {
|
||||
liveEvent: false,
|
||||
timeline: freshTimeline,
|
||||
});
|
||||
await Promise.resolve();
|
||||
await flushRaf();
|
||||
});
|
||||
expect(scrollToBottom).toHaveBeenCalledWith('instant');
|
||||
});
|
||||
@@ -1504,7 +1504,7 @@ describe('live-arrive edge cases', () => {
|
||||
it('re-renders when an event finishes decrypting', async () => {
|
||||
const { room } = createRoom();
|
||||
const { result } = renderSyncHook(room);
|
||||
const before = result.current.timeline;
|
||||
const before = result.current.timelineVersion;
|
||||
|
||||
await act(async () => {
|
||||
mxEmitter.emit(MatrixEventEvent.Decrypted, { getRoomId: () => room.roomId });
|
||||
@@ -1513,13 +1513,13 @@ describe('live-arrive edge cases', () => {
|
||||
});
|
||||
});
|
||||
|
||||
expect(result.current.timeline).not.toBe(before);
|
||||
expect(result.current.timelineVersion).toBeGreaterThan(before);
|
||||
});
|
||||
|
||||
it('ignores decryption of an event in another room', async () => {
|
||||
const { room } = createRoom();
|
||||
const { result } = renderSyncHook(room);
|
||||
const before = result.current.timeline;
|
||||
const before = result.current.timelineVersion;
|
||||
|
||||
await act(async () => {
|
||||
mxEmitter.emit(MatrixEventEvent.Decrypted, { getRoomId: () => '!other:test' });
|
||||
@@ -1528,20 +1528,20 @@ describe('live-arrive edge cases', () => {
|
||||
});
|
||||
});
|
||||
|
||||
expect(result.current.timeline).toBe(before);
|
||||
expect(result.current.timelineVersion).toBe(before);
|
||||
});
|
||||
|
||||
it('re-renders when a late local echo updates (slow send acknowledgement)', async () => {
|
||||
const { room } = createRoom();
|
||||
const { result } = renderSyncHook(room);
|
||||
const before = result.current.timeline;
|
||||
const before = result.current.timelineVersion;
|
||||
|
||||
await act(async () => {
|
||||
room.emit(RoomEvent.LocalEchoUpdated, {}, room);
|
||||
await Promise.resolve();
|
||||
await flushRaf();
|
||||
});
|
||||
|
||||
expect(result.current.timeline).not.toBe(before);
|
||||
expect(result.current.timelineVersion).toBeGreaterThan(before);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2409,9 +2409,8 @@ const flushFrame = async () => {
|
||||
};
|
||||
|
||||
describe('decryption refresh coalescing', () => {
|
||||
// Counts distinct timeline objects, not renders: unrelated re-renders reuse the object.
|
||||
const renderTrackingHook = (room: FakeRoom) => {
|
||||
const seen: unknown[] = [];
|
||||
const seen: number[] = [];
|
||||
renderHook(() => {
|
||||
const sync = useTimelineSync({
|
||||
room: room as Room,
|
||||
@@ -2425,7 +2424,7 @@ describe('decryption refresh coalescing', () => {
|
||||
readUptoEventIdRef: { current: undefined },
|
||||
isInactivePanelRef: { current: false },
|
||||
});
|
||||
if (!seen.includes(sync.timeline)) seen.push(sync.timeline);
|
||||
if (!seen.includes(sync.timelineVersion)) seen.push(sync.timelineVersion);
|
||||
return sync;
|
||||
});
|
||||
return seen;
|
||||
|
||||
@@ -443,6 +443,8 @@ export function useTimelineSync({
|
||||
const [focusItem, setFocusItem] = useState<TimelineFocusItem>();
|
||||
const [jumpFailedFor, setJumpFailedFor] = useState<string | undefined>();
|
||||
const jumpFailed = jumpFailedFor !== undefined && jumpFailedFor === eventId;
|
||||
const [timelineVersion, setTimelineVersion] = useState(0);
|
||||
const bumpTimeline = useCallback(() => setTimelineVersion((version) => version + 1), []);
|
||||
|
||||
const resetAutoScrollPendingRef = useRef(false);
|
||||
const pendingAutoScrollBehaviorRef = useRef<'instant' | 'smooth' | undefined>(undefined);
|
||||
@@ -613,6 +615,22 @@ export function useTimelineSync({
|
||||
[room]
|
||||
);
|
||||
|
||||
const refreshFrameRef = useRef<number | undefined>(undefined);
|
||||
const scheduleTimelineRefresh = useCallback(() => {
|
||||
if (refreshFrameRef.current !== undefined) return;
|
||||
refreshFrameRef.current = requestAnimationFrame(() => {
|
||||
refreshFrameRef.current = undefined;
|
||||
if (!alive()) return;
|
||||
bumpTimeline();
|
||||
});
|
||||
}, [alive, bumpTimeline]);
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (refreshFrameRef.current !== undefined) cancelAnimationFrame(refreshFrameRef.current);
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
useLiveEventArrive(
|
||||
room,
|
||||
useCallback(
|
||||
@@ -621,9 +639,7 @@ export function useTimelineSync({
|
||||
|
||||
const isDisplayedTimeline =
|
||||
evtTimeline === undefined || linkedTimelinesRef.current.includes(evtTimeline);
|
||||
if (isDisplayedTimeline) {
|
||||
setActiveTimeline((ct) => ({ ...ct }));
|
||||
}
|
||||
if (isDisplayedTimeline) scheduleTimelineRefresh();
|
||||
|
||||
if (!isLive) return;
|
||||
|
||||
@@ -675,10 +691,10 @@ export function useTimelineSync({
|
||||
setUnreadInfo,
|
||||
hideReadsRef,
|
||||
isInactivePanelRef,
|
||||
setActiveTimeline,
|
||||
focusLiveTimeline,
|
||||
redactInFocusedWindow,
|
||||
onReturnToLive,
|
||||
scheduleTimelineRefresh,
|
||||
]
|
||||
)
|
||||
);
|
||||
@@ -686,34 +702,19 @@ export function useTimelineSync({
|
||||
const handleLocalEchoUpdated = useCallback(
|
||||
(_mEvent: MatrixEvent, eventRoom: Room | undefined) => {
|
||||
if (eventRoom?.roomId !== room.roomId) return;
|
||||
setActiveTimeline((ct) => ({ ...ct }));
|
||||
scheduleTimelineRefresh();
|
||||
},
|
||||
[room, setActiveTimeline]
|
||||
[room, scheduleTimelineRefresh]
|
||||
);
|
||||
|
||||
useMatrixEvent(room, RoomEvent.LocalEchoUpdated, handleLocalEchoUpdated);
|
||||
|
||||
const decryptedFrameRef = useRef<number | undefined>(undefined);
|
||||
const handleDecrypted = useCallback(
|
||||
(mEvent: MatrixEvent) => {
|
||||
if (mEvent.getRoomId() !== room.roomId) return;
|
||||
if (decryptedFrameRef.current !== undefined) return;
|
||||
decryptedFrameRef.current = requestAnimationFrame(() => {
|
||||
decryptedFrameRef.current = undefined;
|
||||
if (!alive()) return;
|
||||
setActiveTimeline((ct) => ({ ...ct }));
|
||||
});
|
||||
scheduleTimelineRefresh();
|
||||
},
|
||||
[alive, room, setActiveTimeline]
|
||||
);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (decryptedFrameRef.current !== undefined) {
|
||||
cancelAnimationFrame(decryptedFrameRef.current);
|
||||
}
|
||||
},
|
||||
[]
|
||||
[room, scheduleTimelineRefresh]
|
||||
);
|
||||
|
||||
useMatrixEvent(mx, MatrixEventEvent.Decrypted, handleDecrypted);
|
||||
@@ -746,12 +747,7 @@ export function useTimelineSync({
|
||||
)
|
||||
);
|
||||
|
||||
useThreadUpdate(
|
||||
room,
|
||||
useCallback(() => {
|
||||
setActiveTimeline((ct) => ({ ...ct }));
|
||||
}, [setActiveTimeline])
|
||||
);
|
||||
useThreadUpdate(room, scheduleTimelineRefresh);
|
||||
|
||||
useEffect(() => {
|
||||
const resetAutoScrollPending = resetAutoScrollPendingRef.current;
|
||||
@@ -773,7 +769,7 @@ export function useTimelineSync({
|
||||
|
||||
lastScrolledAtEventsLengthRef.current = eventsLength;
|
||||
scrollToBottom(behavior);
|
||||
}, [isAtBottom, liveTimelineLinked, eventsLength, scrollToBottom]);
|
||||
}, [isAtBottom, liveTimelineLinked, eventsLength, timelineVersion, scrollToBottom]);
|
||||
|
||||
useEffect(() => {
|
||||
if (eventId) return;
|
||||
@@ -793,6 +789,7 @@ export function useTimelineSync({
|
||||
|
||||
return {
|
||||
timeline,
|
||||
timelineVersion,
|
||||
eventsLength,
|
||||
liveTimelineLinked,
|
||||
canPaginateBack,
|
||||
|
||||
@@ -21,8 +21,13 @@ vi.mock('@tauri-apps/api/core', () => tauriApi);
|
||||
vi.mock('./mediaTransport', () => mediaTransport);
|
||||
vi.mock('./room/relations', () => reactions);
|
||||
|
||||
const { getDMRoomFor, mxcUrlToHttp, rewriteAuthenticatedMediaUrl, toggleReaction } =
|
||||
await import('./matrix');
|
||||
const {
|
||||
getDMRoomFor,
|
||||
mxcUrlToHttp,
|
||||
rewriteAuthenticatedMediaUrl,
|
||||
toggleReaction,
|
||||
optimisticallyRedactEvent,
|
||||
} = await import('./matrix');
|
||||
|
||||
describe('rewriteAuthenticatedMediaUrl', () => {
|
||||
beforeEach(() => {
|
||||
@@ -109,28 +114,66 @@ describe('rewriteAuthenticatedMediaUrl', () => {
|
||||
|
||||
describe('toggleReaction', () => {
|
||||
it('redacts the existing reaction from the current user', () => {
|
||||
const redaction = {};
|
||||
const reaction = {
|
||||
getId: () => '$reaction',
|
||||
getSender: () => '@me:example.org',
|
||||
getRelation: () => ({ event_id: '$message' }),
|
||||
isRedacted: () => false,
|
||||
markLocallyRedacted: vi.fn<(event: unknown) => void>(),
|
||||
unmarkLocallyRedacted: vi.fn<() => void>(),
|
||||
};
|
||||
reactions.getEventReactions.mockReturnValue({
|
||||
getSortedAnnotationsByKey: () => [['👍', new Set([reaction])]],
|
||||
});
|
||||
const mx = {
|
||||
getUserId: () => '@me:example.org',
|
||||
redactEvent: vi.fn<(roomId: string, eventId: string) => void>(),
|
||||
makeTxnId: () => 'txn',
|
||||
redactEvent: vi.fn<(...args: unknown[]) => Promise<object>>(() => Promise.resolve({})),
|
||||
sendEvent: vi.fn<(...args: unknown[]) => void>(),
|
||||
} as unknown as MatrixClient;
|
||||
const room = {
|
||||
roomId: '!room:example.org',
|
||||
getUnfilteredTimelineSet: vi.fn<() => unknown>(),
|
||||
findEventById: () => redaction,
|
||||
};
|
||||
|
||||
toggleReaction(mx, room as never, '$message', '👍');
|
||||
|
||||
expect(mx.redactEvent).toHaveBeenCalledWith('!room:example.org', '$reaction');
|
||||
expect(mx.redactEvent).toHaveBeenCalledWith('!room:example.org', '$reaction', 'txn', undefined);
|
||||
expect(reaction.markLocallyRedacted).toHaveBeenCalledWith(redaction);
|
||||
expect(mx.sendEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rolls back an optimistic redaction when sending fails', async () => {
|
||||
const relation = {
|
||||
addEvent: vi.fn<(event: unknown) => Promise<void>>(() => Promise.resolve()),
|
||||
};
|
||||
reactions.getEventReactions.mockReturnValue(relation);
|
||||
const target = {
|
||||
getId: () => '$reaction',
|
||||
getRelation: () => ({ event_id: '$message' }),
|
||||
isRedacted: () => false,
|
||||
markLocallyRedacted: vi.fn<(event: unknown) => void>(),
|
||||
unmarkLocallyRedacted: vi.fn<() => void>(),
|
||||
};
|
||||
const error = new Error('failed');
|
||||
const mx = {
|
||||
makeTxnId: () => 'txn',
|
||||
redactEvent: () => Promise.reject(error),
|
||||
} as unknown as MatrixClient;
|
||||
const timelineSet = {};
|
||||
const room = {
|
||||
roomId: '!room:example.org',
|
||||
getUnfilteredTimelineSet: () => timelineSet,
|
||||
findEventById: () => ({}),
|
||||
};
|
||||
|
||||
await expect(optimisticallyRedactEvent(mx, room as never, target as never)).rejects.toBe(error);
|
||||
|
||||
expect(target.unmarkLocallyRedacted).toHaveBeenCalledOnce();
|
||||
expect(relation.addEvent).toHaveBeenCalledWith(target);
|
||||
});
|
||||
});
|
||||
|
||||
describe('mxcUrlToHttp', () => {
|
||||
|
||||
+29
-2
@@ -571,8 +571,9 @@ export const toggleReaction = (
|
||||
const myReaction = reactions.find(factoryEventSentBy(mx.getUserId()!));
|
||||
|
||||
if (myReaction) {
|
||||
const eventId = myReaction.getId();
|
||||
if (eventId) mx.redactEvent(room.roomId, eventId);
|
||||
void optimisticallyRedactEvent(mx, room, myReaction, undefined, timelineSet).catch(
|
||||
() => undefined
|
||||
);
|
||||
return;
|
||||
}
|
||||
const rShortcode =
|
||||
@@ -590,3 +591,29 @@ export const toggleReaction = (
|
||||
) as TimelineEvents[keyof TimelineEvents]
|
||||
);
|
||||
};
|
||||
|
||||
export const optimisticallyRedactEvent = (
|
||||
mx: MatrixClient,
|
||||
room: Room,
|
||||
target: MatrixEvent,
|
||||
opts?: { reason?: string },
|
||||
timelineSet = room.getUnfilteredTimelineSet()
|
||||
) => {
|
||||
const eventId = target.getId();
|
||||
if (!eventId) return Promise.reject(new Error('Cannot redact an event without an ID'));
|
||||
|
||||
const txnId = mx.makeTxnId();
|
||||
const request = mx.redactEvent(room.roomId, eventId, txnId, opts);
|
||||
const redaction = room.findEventById(`~${room.roomId}:${txnId}`);
|
||||
if (!redaction || target.isRedacted()) return request;
|
||||
|
||||
target.markLocallyRedacted(redaction);
|
||||
return request.catch(async (error) => {
|
||||
target.unmarkLocallyRedacted();
|
||||
const relation = target.getRelation();
|
||||
if (relation?.event_id) {
|
||||
await getEventReactions(timelineSet, relation.event_id)?.addEvent(target);
|
||||
}
|
||||
throw error;
|
||||
});
|
||||
};
|
||||
Reference in new issue
Block a user