fix(timeline): land on the linked message when jumping to a permalink (#1516)

<!-- Please read
https://github.com/SableClient/Sable/blob/dev/CONTRIBUTING.md before
submitting your pull request -->

### Description

Fixes permalink jumps landing on the wrong message: filtered targets
(e.g. thread replies) never scrolled at all, and uncached targets got
re-yanked to the live bottom. Now the jump falls back to the nearest
visible row and atBottom stays disarmed while a jump is pending.

Fixes #

#### 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:

- [x] My code follows the style guidelines of this project
- [x] 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:
7w1 authored and GitHub committed 2026-07-30 19:36:01 +00:00
commit e3ed527888
4 files changed
+250 -4

No files matched your search

+33 -1
View File
@@ -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<typeof vi.fn>).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(<RoomTimeline room={room} editor={{} as Editor} />);
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<typeof vi.fn>).mock.calls;
type FocusItem = NonNullable<typeof timelineSync.focusItem>;
const updater = setFocusItemCall?.[0] as (prev: FocusItem) => FocusItem;
expect(updater({ index: 5, scrollTo: true, highlight: true })).toEqual({
index: 0,
scrollTo: false,
highlight: true,
});
});
});
+23 -3
View File
@@ -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<typeof setTimeout> | 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(() => {
+19
View File
@@ -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<string, unknown>,
txnId: number
): Promise<string> {
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,
+175
View File
@@ -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<string> {
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<string> {
const url = permalinkTo(roomId, targetEventId);
return sendMessage(
baseUrl,
token,
roomId,
{
msgtype: 'm.text',
body: url,
format: 'org.matrix.custom.html',
formatted_body: `<a href="${url}">permalink</a>`,
},
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();
});
});