diff --git a/src/app/features/room/RoomTimeline.test.tsx b/src/app/features/room/RoomTimeline.test.tsx index 5269a8d08..a982dd0d5 100644 --- a/src/app/features/room/RoomTimeline.test.tsx +++ b/src/app/features/room/RoomTimeline.test.tsx @@ -24,7 +24,7 @@ const { vListHandle, timelineSync, setUnreadTimelineMock } = vi.hoisted(() => ({ backwardStatus: 'idle', forwardStatus: 'idle', canPaginateBack: false, - focusItem: undefined, + focusItem: undefined as { index: number; scrollTo: boolean; highlight: boolean } | undefined, setFocusItem: vi.fn<() => void>(), setTimeline: vi.fn<() => void>(), loadEventTimeline: vi.fn<() => void>(), @@ -236,6 +236,8 @@ describe('RoomTimeline content ResizeObserver', () => { vListHandle.viewportSize = 600; vListHandle.scrollToIndex.mockReset(); vListHandle.scrollTo.mockReset(); + timelineSync.focusItem = undefined; + (timelineSync.setFocusItem as ReturnType).mockReset(); globalThis.ResizeObserver = ResizeObserverStub as unknown as typeof ResizeObserver; }); @@ -278,4 +280,34 @@ describe('RoomTimeline content ResizeObserver', () => { expect(vListHandle.scrollToIndex).not.toHaveBeenCalled(); }); + + it('scrolls to the nearest visible row when the jump target is filtered out', async () => { + const { rerender } = renderTimeline(); + + // Let the mount-time initial scroll settle, then isolate the focus jump. + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 150)); + }); + vListHandle.scrollToIndex.mockClear(); + + // The mocked timeline exposes one row (itemIndex 0), so raw index 5 has no + // exact row to match. + timelineSync.focusItem = { index: 5, scrollTo: true, highlight: true }; + rerender(); + + expect(vListHandle.scrollToIndex).toHaveBeenCalledWith( + 0, + expect.objectContaining({ align: 'center' }) + ); + + // The highlight is retargeted to the row we actually landed on. + const [setFocusItemCall] = (timelineSync.setFocusItem as ReturnType).mock.calls; + type FocusItem = NonNullable; + const updater = setFocusItemCall?.[0] as (prev: FocusItem) => FocusItem; + expect(updater({ index: 5, scrollTo: true, highlight: true })).toEqual({ + index: 0, + scrollTo: false, + highlight: true, + }); + }); }); diff --git a/src/app/features/room/RoomTimeline.tsx b/src/app/features/room/RoomTimeline.tsx index ed98b702b..efec8313b 100644 --- a/src/app/features/room/RoomTimeline.tsx +++ b/src/app/features/room/RoomTimeline.tsx @@ -408,7 +408,12 @@ export function RoomTimeline({ const v = vListRef.current; if (!v) return; const scrollTop = offset ?? v.scrollOffset; - const isNowAtBottom = v.scrollSize - scrollTop - v.viewportSize < 100; + let isNowAtBottom = v.scrollSize - scrollTop - v.viewportSize < 100; + // Don't arm atBottom while a focus jump is pending: the swapped-in + // context window transiently clamps to its bottom edge. + if (isNowAtBottom && !atBottomRef.current && timelineSyncRef.current.focusItem) { + isNowAtBottom = false; + } if (isNowAtBottom !== atBottomRef.current) setAtBottom(isNowAtBottom); }, [setAtBottom] @@ -724,10 +729,25 @@ export function RoomTimeline({ let timeoutId: ReturnType | undefined; if (timelineSync.focusItem) { if (timelineSync.focusItem.scrollTo && vListRef.current) { - const processedIndex = getRawIndexToProcessedIndex(timelineSync.focusItem.index); + let processedIndex = getRawIndexToProcessedIndex(timelineSync.focusItem.index); + let focusRawIndex = timelineSync.focusItem.index; + if (processedIndex === undefined) { + // Jump targets with no rendered row (thread replies, hidden + // membership/name events): land on the nearest visible row. + const nearest = getProcessedRowIndexForRawTimelineIndex( + processedEventsRef.current, + timelineSync.focusItem.index + ); + if (nearest) { + processedIndex = nearest.rowIndex; + focusRawIndex = nearest.focusRawIndex; + } + } if (processedIndex !== undefined) { vListRef.current.scrollToIndex(processedIndex, { align: 'center' }); - timelineSync.setFocusItem((prev) => (prev ? { ...prev, scrollTo: false } : undefined)); + timelineSync.setFocusItem((prev) => + prev ? { ...prev, index: focusRawIndex, scrollTo: false } : undefined + ); } } timeoutId = setTimeout(() => { diff --git a/tests/e2e/fixtures/continuwuity.ts b/tests/e2e/fixtures/continuwuity.ts index 1df168789..cdb942818 100644 --- a/tests/e2e/fixtures/continuwuity.ts +++ b/tests/e2e/fixtures/continuwuity.ts @@ -112,6 +112,25 @@ export async function sendText( return ((await res.json()) as { event_id: string }).event_id; } +export async function sendMessage( + baseUrl: string, + token: string, + roomId: string, + content: Record, + txnId: number +): Promise { + const url = `${baseUrl}/_matrix/client/v3/rooms/${encodeURIComponent(roomId)}/send/m.room.message/${txnId}`; + const res = await fetch(url, { + method: 'PUT', + headers: { authorization: `Bearer ${token}` }, + body: JSON.stringify(content), + }); + if (!res.ok) { + throw new Error(`sendMessage failed: ${res.status} ${await res.text()}`); + } + return ((await res.json()) as { event_id: string }).event_id; +} + export async function inviteUser( baseUrl: string, token: string, diff --git a/tests/e2e/permalink-jump.spec.ts b/tests/e2e/permalink-jump.spec.ts new file mode 100644 index 000000000..b8a9dfb25 --- /dev/null +++ b/tests/e2e/permalink-jump.spec.ts @@ -0,0 +1,175 @@ +import { readFile } from 'node:fs/promises'; +import { test, expect, type Page } from '@playwright/test'; +import { createRoom, registerUser, sendMessage, sendText } from './fixtures/continuwuity'; +import { AppShell } from './pages/AppShell'; + +const PASSWORD = 'test-passw0rd'; +const HISTORY_SIZE = 100; + +type InjectedSession = { + baseUrl: string; + userId: string; + deviceId: string; + accessToken: string; + slidingSyncOptIn?: boolean; +}; + +async function homeserverBaseUrl(storageStatePath: string): Promise { + const state = JSON.parse(await readFile(storageStatePath, 'utf8')) as { + origins: { localStorage: { name: string; value: string }[] }[]; + }; + const entry = state.origins[0]!.localStorage.find((item) => item.name === 'matrixSessions')!; + return (JSON.parse(entry.value) as InjectedSession[])[0]!.baseUrl; +} + +async function loginAsFreshUser( + page: Page, + baseUrl: string, + name: string +): Promise<{ accessToken: string }> { + const user = await registerUser(baseUrl, name, PASSWORD); + const session: InjectedSession = { + baseUrl, + userId: user.userId, + deviceId: user.deviceId, + accessToken: user.accessToken, + slidingSyncOptIn: true, + }; + await page.addInitScript((injected: InjectedSession) => { + localStorage.setItem('matrixSessions', JSON.stringify([injected])); + localStorage.setItem('matrixActiveSession', JSON.stringify(injected.userId)); + localStorage.setItem('dismissNotice', 'true'); + }, session); + return user; +} + +const permalinkTo = (roomId: string, eventId: string): string => + `https://matrix.to/#/${roomId}/${eventId}`; + +const permalinkLink = (page: Page, eventId: string) => + page.locator(`a[data-mention-event-id="${eventId}"]`); + +function sendPermalink( + baseUrl: string, + token: string, + roomId: string, + targetEventId: string, + txnId: number +): Promise { + const url = permalinkTo(roomId, targetEventId); + return sendMessage( + baseUrl, + token, + roomId, + { + msgtype: 'm.text', + body: url, + format: 'org.matrix.custom.html', + formatted_body: `permalink`, + }, + txnId + ); +} + +test.describe('permalink jumps', () => { + test('jumps to a message beyond the loaded window when its permalink is clicked', async ({ + page, + }, testInfo) => { + test.skip(testInfo.project.name !== 'desktop', 'desktop-focused'); + test.setTimeout(300_000); + const storageStatePath = testInfo.project.use.storageState as string; + const hsBaseUrl = await homeserverBaseUrl(storageStatePath); + const tag = `plink-${process.pid}-${Date.now().toString(36)}`; + const app = new AppShell(page); + const user = await loginAsFreshUser(page, hsBaseUrl, `${tag}-u`); + + const room = await createRoom(hsBaseUrl, user.accessToken, { + name: `${tag} Room`, + preset: 'private_chat', + }); + + // The client initially loads only the latest 60 events, so message 20 sits + // outside the loaded timeline: the jump has to fetch its context. + let targetId = ''; + let latestId = ''; + for (let i = 1; i <= HISTORY_SIZE; i += 1) { + const eventId = await sendText(hsBaseUrl, user.accessToken, room, `${tag}-${i}`, i); + if (i === 20) targetId = eventId; + latestId = eventId; + } + await sendPermalink(hsBaseUrl, user.accessToken, room, targetId, HISTORY_SIZE + 1); + + await page.goto('/'); + await expect(page.getByText(`${tag} Room`).first()).toBeVisible({ timeout: 180_000 }); + await app.openRoom(`${tag} Room`); + + const targetRow = app.messageByEventId(targetId); + await expect(permalinkLink(page, targetId)).toBeVisible({ timeout: 60_000 }); + await expect(targetRow).toHaveCount(0); + + await permalinkLink(page, targetId).click(); + + await expect(targetRow).toBeVisible({ timeout: 60_000 }); + await expect(app.messageByEventId(latestId)).toHaveCount(0); + }); + + test('opens the thread when the permalink target is a thread reply', async ({ + page, + }, testInfo) => { + test.skip(testInfo.project.name !== 'desktop', 'desktop-focused'); + test.setTimeout(300_000); + const storageStatePath = testInfo.project.use.storageState as string; + const hsBaseUrl = await homeserverBaseUrl(storageStatePath); + const tag = `plinkf-${process.pid}-${Date.now().toString(36)}`; + const app = new AppShell(page); + const user = await loginAsFreshUser(page, hsBaseUrl, `${tag}-u`); + + const room = await createRoom(hsBaseUrl, user.accessToken, { + name: `${tag} Room`, + preset: 'private_chat', + }); + + // Thread reply permalinks reroute to the thread drawer instead of jumping + // the main timeline (Room.tsx opens it for events with a threadRootId). + let txn = 1; + let replyId = ''; + for (let i = 1; i <= HISTORY_SIZE; i += 1) { + const eventId = await sendText(hsBaseUrl, user.accessToken, room, `${tag}-${i}`, txn); + txn += 1; + if (i === 50) { + const rootId = eventId; + replyId = await sendMessage( + hsBaseUrl, + user.accessToken, + room, + { + msgtype: 'm.text', + body: `${tag}-thread-reply`, + 'm.relates_to': { + rel_type: 'm.thread', + event_id: rootId, + is_falling_back: true, + 'm.in_reply_to': { event_id: rootId }, + }, + }, + txn + ); + txn += 1; + } + } + await sendPermalink(hsBaseUrl, user.accessToken, room, replyId, txn); + + await page.goto('/'); + await expect(page.getByText(`${tag} Room`).first()).toBeVisible({ timeout: 180_000 }); + await app.openRoom(`${tag} Room`); + + await expect(permalinkLink(page, replyId)).toBeVisible({ timeout: 60_000 }); + + await permalinkLink(page, replyId).click(); + + await expect(page.getByRole('button', { name: 'Close thread' })).toBeVisible({ + timeout: 60_000, + }); + await expect(page.getByText(`${tag}-thread-reply`, { exact: true })).toBeVisible(); + }); +});