Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(channels): deeply nested thread scrolling (#4993)

teoe2098348275c
diff --git a/apps/web/playwright.config.ts b/apps/web/playwright.config.ts
index 2e45ed6b5d..9c8f74af6e 100644
--- a/apps/web/playwright.config.ts
+++ b/apps/web/playwright.config.ts
@@ -139,6 +139,10 @@ export default defineConfig({
testIgnore: 'tests/e2e/pdf/inputs/*',
/* Run tests in files in parallel */
fullyParallel: true,
+ // Local E2E shares one seeded stack and one authenticated user. Running the
+ // full app in several UI-mode workers can leave background channel layouts
+ // unmeasured, so keep this harness serial and deterministic.
+ workers: isLocalE2E ? 1 : undefined,
/* Fail the build on CI if you accidentally left test.only in the source code. */
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 1 : 0,
diff --git a/apps/web/src/features/channel/Channel/Channel.tsx b/apps/web/src/features/channel/Channel/Channel.tsx
index adbc3c5cb8..cd535e3e22 100644
--- a/apps/web/src/features/channel/Channel/Channel.tsx
+++ b/apps/web/src/features/channel/Channel/Channel.tsx
@@ -53,6 +53,7 @@ import {
useAddReactionMutation,
useRemoveReactionMutation,
} from '@queries/channel/reaction';
+import { threadRepliesQueryOptions } from '@queries/channel/thread-replies';
import { usePostTypingUpdateMutation } from '@queries/channel/typing';
import { queryClient } from '@queries/client';
import { useBeforeLeave } from '@solidjs/router';
@@ -220,6 +221,16 @@ export function Channel(props: ChannelProps) {
const messages = createMemo(() => [...messageIndex.items]);
const messageById = () => messageIndex.byId;
+ const keepMountedTargetThreadIndexes = createMemo(() => {
+ const threadId = targetMessageController.activeTargetMessageId();
+ const hasPendingElementScroll =
+ targetMessageController.pendingScrollTargetId() !== undefined ||
+ targetMessageController.pendingTargetReplyId() !== undefined;
+ if (!threadId || !hasPendingElementScroll) return [];
+
+ const index = messageIndex.keys.indexOf(threadId);
+ return index === -1 ? [] : [index];
+ });
const participants = useChannelParticipants(() => props.channelId);
@@ -259,6 +270,22 @@ export function Channel(props: ChannelProps) {
const threadManager = createThreadManager(
props.initialMessagesStateSnapshot?.threads
);
+
+ const prepareTargetReply = (threadId: string) => {
+ // Expand before the virtualized row mounts so navigation never presents a
+ // collapsed parent and then grows it in the viewport.
+ threadManager.getOrCreateThreadState(threadId).setIsExpanded(true);
+ // Reply data and the load-around message window can load in parallel. The
+ // mounted query reuses this request and remains the owner of render state.
+ void queryClient.prefetchQuery(
+ threadRepliesQueryOptions(props.channelId, threadId)
+ );
+ };
+
+ if (props.targetMessageId && props.targetMessageReplyId) {
+ prepareTargetReply(props.targetMessageId);
+ }
+
const threadPaginator = createThreadPaginator(messagesQuery);
const messageEditor = createMessageEditor({
channelId: () => props.channelId,
@@ -422,6 +449,7 @@ export function Channel(props: ChannelProps) {
const goToMessage: ChannelHandle['goToMessage'] = (messageId, replyId) => {
if (replyId) {
clearSelection();
+ prepareTargetReply(messageId);
} else {
selectMessage(messageId);
}
@@ -613,8 +641,14 @@ export function Channel(props: ChannelProps) {
triggerBehavior="spring-back"
>
<ThreadList
+ channelId={props.channelId}
keys={() => messageIndex.keys}
initialScrollTarget={threadListInitialScrollTarget()}
+ initialScrollHandledByTargetElement={
+ targetMessageController.pendingScrollTargetId() !==
+ undefined
+ }
+ keepMounted={keepMountedTargetThreadIndexes}
fullFrameScrollInsets={threadListScrollInsets}
shift={shift}
prepend={threadPaginator.isPrepending}
@@ -645,16 +679,39 @@ export function Channel(props: ChannelProps) {
channelId={() => props.channelId}
isNewestThread={isNewestThread()}
getMessageActions={getMessageActions}
- targetThreadId={targetMessageController.activeTargetMessageId()}
- targetReplyId={targetMessageController.pendingTargetReplyId()}
- activeTargetReplyId={targetMessageController.activeTargetMessageReplyId()}
- unifiedReplyTarget={unifiedInput.replyTarget()}
- onTargetReplyScrolled={(replyId) => {
- targetMessageController.completePendingReplyScroll(
- m().id,
- replyId
- );
+ targetNavigation={{
+ targetThreadId:
+ targetMessageController.activeTargetMessageId,
+ targetMessageId: () =>
+ !targetMessageController.pendingTargetReplyId()
+ ? targetMessageController.pendingScrollTargetId()
+ : undefined,
+ targetReplyId: () =>
+ targetMessageController.pendingScrollTargetId()
+ ? undefined
+ : targetMessageController.pendingTargetReplyId(),
+ activeTargetReplyId:
+ targetMessageController.activeTargetMessageReplyId,
+ positionTarget: (
+ threadRow,
+ targetElement
+ ) =>
+ threadListNavigation()?.scrollToElementInItem(
+ item.id,
+ threadRow,
+ targetElement
+ ) ?? false,
+ onTargetMessageScrolled:
+ targetMessageController.completePendingScroll,
+ onTargetReplyScrolled: (replyId) => {
+ targetMessageController.completePendingReplyScroll(
+ item.id,
+ replyId
+ );
+ },
+ onClearTarget: releaseSelectionAndTarget,
}}
+ unifiedReplyTarget={unifiedInput.replyTarget()}
isExpanded={state.isExpanded}
setIsExpanded={state.setIsExpanded}
isReplying={state.isReplying}
@@ -680,7 +737,6 @@ export function Channel(props: ChannelProps) {
selectedMessageId={selection.selectedId}
onSelectMessage={selectMessage}
onClearSelection={clearSelection}
- onClearTarget={releaseSelectionAndTarget}
messageListScopeId={messageListScopeId}
/>
)}
diff --git a/apps/web/src/features/channel/Channel/ThreadList.tsx b/apps/web/src/features/channel/Channel/ThreadList.tsx
index a9839abf07..d258ecab61 100644
--- a/apps/web/src/features/channel/Channel/ThreadList.tsx
+++ b/apps/web/src/features/channel/Channel/ThreadList.tsx
@@ -45,6 +45,12 @@ export type ThreadListNavigation = {
navigatePrevious: () => boolean;
navigateNext: () => boolean;
isNearBottom: () => boolean;
+ /** Position a descendant using Virtua's measured coordinate space. */
+ scrollToElementInItem: (
+ id: string,
+ itemElement: HTMLElement,
+ targetElement: HTMLElement
+ ) => boolean;
/**
* Signal that a user-initiated navigation is about to cause a
* programmatic scroll. Call this before `scrollToId` etc. from
@@ -77,9 +83,13 @@ export type FullFrameThreadListScrollInsets = {
};
type ThreadListProps = {
+ /** Identifies the channel scroll surface when multiple splits are mounted. */
+ channelId?: string;
keys: Accessor<string[]>;
children: (item: { id: string }) => JSX.Element;
initialScrollTarget?: ThreadListScrollTarget;
+ /** A kept-mounted descendant owns the targeted initial viewport movement. */
+ initialScrollHandledByTargetElement?: boolean;
onScrollNearTop?: () => void;
onScrollNearBottom?: () => void;
onNavigationReady?: (navigation: ThreadListNavigation) => void;
@@ -88,6 +98,8 @@ type ThreadListProps = {
onScrollSnapshotChange?: (snapshot: ThreadListScrollSnapshot) => void;
shift?: Accessor<boolean>;
prepend?: Accessor<boolean>;
+ /** Item indexes that must remain mounted during nested-message navigation. */
+ keepMounted?: Accessor<readonly number[]>;
/**
* For full-frame insets where the scroll surface spans the whole screen and content
* scrolls behind the floating chrome. Rendered as scroll-content padding and fed to
@@ -412,6 +424,35 @@ export function ThreadList(props: ThreadListProps) {
isNearBottom,
+ scrollToElementInItem: (id, itemElement, targetElement) => {
+ const index = props.keys().indexOf(id);
+ if (index === -1) return false;
+
+ cancelPinToBottom?.();
+ const itemRect = itemElement.getBoundingClientRect();
+ const targetRect = targetElement.getBoundingClientRect();
+ const targetCenter =
+ handle.getItemOffset(index) +
+ (targetRect.top - itemRect.top) +
+ targetRect.height / 2;
+ const { start, end } = insets();
+ const usableViewportCenter =
+ start + (handle.viewportSize - start - end) / 2;
+ // The DOM scroll range includes the full-frame inset spacers; Virtua's
+ // scrollSize only covers its own items.
+ const maxScrollOffset = scrollRef
+ ? scrollRef.scrollHeight - scrollRef.clientHeight
+ : handle.scrollSize - handle.viewportSize;
+ handle.scrollTo(
+ clamp(
+ targetCenter - usableViewportCenter,
+ 0,
+ Math.max(0, maxScrollOffset)
+ )
+ );
+ return true;
+ },
+
markUserIntent: scrollIntent.markUserIntent,
});
@@ -502,6 +543,10 @@ export function ThreadList(props: ThreadListProps) {
function scrollOnMount(handle: VirtualizerHandle) {
if (initialScrollStarted) return;
initialScrollStarted = true;
+ if (props.initialScrollHandledByTargetElement) {
+ completeInitialScroll(handle);
+ return;
+ }
beginInitialTargetScroll(handle, getInitialScrollTarget());
}
@@ -644,6 +689,9 @@ export function ThreadList(props: ThreadListProps) {
setScrollEl(el);
}}
data-channel-scroll
+ data-channel-id={props.channelId}
+ data-channel-scroll-inset-start={insets().start}
+ data-channel-scroll-inset-end={insets().end}
class="scrollbar-hidden"
{...scrollIntent.handlers}
style={{
@@ -677,6 +725,7 @@ export function ThreadList(props: ThreadListProps) {
startMargin={insets().start}
itemSize={BASE_ITEM_SIZE}
bufferSize={BASE_BUFFER_SIZE}
+ keepMounted={props.keepMounted?.()}
data={props.keys()}
onScroll={handleScroll}
onScrollEnd={handleScrollEnd}
diff --git a/apps/web/src/features/channel/Channel/create-target-message-controller.ts b/apps/web/src/features/channel/Channel/create-target-message-controller.ts
index 92aa1c616c..c047158f5f 100644
--- a/apps/web/src/features/channel/Channel/create-target-message-controller.ts
+++ b/apps/web/src/features/channel/Channel/create-target-message-controller.ts
@@ -106,7 +106,11 @@ export function createTargetMessageController(
// true the effect re-fires and executes the scroll.
if (!didInitialScroll) return;
- if (!navigation.scrollToId(pendingTargetId)) return;
+ // Channel keeps a pending target's row mounted. Scrolling the whole
+ // row first can land on the wrong part of a tall thread and creates a
+ // visible intermediate position, so the measured root/reply element
+ // performs the only viewport movement.
+ const nestedTarget = !!targetMessageData['pendingTargetReplyId'];
const restoredDefaultPagination =
restoreDefaultChannelPaginationAfterTargetLoad(
@@ -116,7 +120,10 @@ export function createTargetMessageController(
if (restoredDefaultPagination) {
setTargetMessageData('loadAroundMessageId', undefined);
}
- completePendingScroll(pendingTargetId);
+ // Nested replies acknowledge the outer row immediately so their own
+ // measured-element scroll can begin. Root messages stay pending until
+ // ChannelThread positions the message inside its potentially tall row.
+ if (nestedTarget) completePendingScroll(pendingTargetId);
}
)
);
diff --git a/apps/web/src/features/channel/Channel/tests/create-target-message-controller.test.ts b/apps/web/src/features/channel/Channel/tests/create-target-message-controller.test.ts
index be62c2dd6d..7b90be369c 100644
--- a/apps/web/src/features/channel/Channel/tests/create-target-message-controller.test.ts
+++ b/apps/web/src/features/channel/Channel/tests/create-target-message-controller.test.ts
@@ -23,6 +23,7 @@ function createController(
input?: Partial<{
channelId: string;
initialTargetMessageId: string;
+ initialTargetMessageReplyId: string;
messageKeys: string[];
scrollToId: (messageId: string) => boolean;
withNavigation: boolean;
@@ -43,6 +44,7 @@ function createController(
const controller = createTargetMessageController({
channelId: () => input?.channelId ?? 'channel-1',
initialTargetMessageId: input?.initialTargetMessageId,
+ initialTargetMessageReplyId: input?.initialTargetMessageReplyId,
messageKeys,
navigation: () =>
input?.withNavigation
@@ -56,6 +58,7 @@ function createController(
navigatePrevious: () => false,
navigateNext: () => false,
isNearBottom: () => true,
+ scrollToElementInItem: () => true,
markUserIntent: () => {},
}
: undefined,
@@ -101,6 +104,57 @@ describe('createTargetMessageController', () => {
});
});
+ it('lets a nested reply perform the only viewport scroll', async () => {
+ const scrollToId = vi.fn(() => true);
+ let dispose = () => {};
+ let controller: ReturnType<typeof createTargetMessageController>;
+
+ createRoot((rootDispose) => {
+ dispose = rootDispose;
+ controller = createController({
+ initialTargetMessageId: 'message-1',
+ initialTargetMessageReplyId: 'reply-4',
+ messageKeys: ['message-1'],
+ scrollToId,
+ withNavigation: true,
+ didInitialScroll: true,
+ }).controller;
+ });
+
+ await Promise.resolve();
+
+ expect(scrollToId).not.toHaveBeenCalled();
+ expect(controller!.pendingScrollTargetId()).toBeUndefined();
+ expect(controller!.pendingTargetReplyId()).toBe('reply-4');
+ dispose();
+ });
+
+ it('keeps a root target pending until its element is positioned within the row', async () => {
+ const scrollToId = vi.fn(() => true);
+ let dispose = () => {};
+ let controller: ReturnType<typeof createTargetMessageController>;
+
+ createRoot((rootDispose) => {
+ dispose = rootDispose;
+ controller = createController({
+ initialTargetMessageId: 'message-1',
+ messageKeys: ['message-1'],
+ scrollToId,
+ withNavigation: true,
+ didInitialScroll: true,
+ }).controller;
+ });
+
+ await Promise.resolve();
+
+ expect(scrollToId).not.toHaveBeenCalled();
+ expect(controller!.pendingScrollTargetId()).toBe('message-1');
+
+ controller!.completePendingScroll('message-1');
+ expect(controller!.pendingScrollTargetId()).toBeUndefined();
+ dispose();
+ });
+
it('copies around-target query data into the default query key', () => {
const aroundData = {
pageParams: [null],
diff --git a/apps/web/src/features/channel/Thread/ChannelThread.tsx b/apps/web/src/features/channel/Thread/ChannelThread.tsx
index 372c49f36a..e534bde28b 100644
--- a/apps/web/src/features/channel/Thread/ChannelThread.tsx
+++ b/apps/web/src/features/channel/Thread/ChannelThread.tsx
@@ -5,10 +5,19 @@ import { tryMacroId, useDisplayName } from '@core/user';
import { MarkMessageNotifications } from '@notifications/components/MarkMessageNotifications';
import { useThreadRepliesQuery } from '@queries/channel/thread-replies';
import type { ApiThreadReply } from '@service-storage/generated/schemas/apiThreadReply';
-import { createEffect, createSignal, on, Show, untrack } from 'solid-js';
+import {
+ createEffect,
+ createSignal,
+ on,
+ onCleanup,
+ Show,
+ untrack,
+} from 'solid-js';
import { createMessageSelection } from '../Channel/create-message-selection';
import { ChannelMessage } from '../Message';
import { isUnifiedInputMode } from '../unified-input-mode';
+import { createTargetReplyNavigationController } from './create-target-reply-navigation-controller';
+import { createTargetReplyScroller } from './create-target-reply-scroller';
import { createThreadHotkeys } from './create-thread-hotkeys';
import { Thread } from './Thread';
import type { ThreadReplyListHandle } from './ThreadReplyList';
@@ -29,7 +38,8 @@ export function ChannelThread(props: ThreadProps) {
const thread = () => props.data().thread;
const hasReplies = () => thread().reply_count > 0;
const fetchRepliesEnabled = () =>
- (!!props.targetReplyId && props.targetThreadId === props.data().id) ||
+ (!!props.targetNavigation?.targetReplyId() &&
+ props.targetNavigation.targetThreadId() === props.data().id) ||
props.isExpanded() ||
(hasReplies() && thread().reply_count > DEFAULT_VISIBLE_REPLY_COUNT);
@@ -101,15 +111,15 @@ export function ChannelThread(props: ThreadProps) {
// Channel navigation landed on this root message (and not on one of its
// replies).
const isRootNavTargeted = () =>
- !!props.targetThreadId &&
- props.targetThreadId === props.data().id &&
- !props.activeTargetReplyId;
+ !!props.targetNavigation?.targetThreadId() &&
+ props.targetNavigation.targetThreadId() === props.data().id &&
+ !props.targetNavigation.activeTargetReplyId();
const selectThreadMessage = () => {
// Clicking the navigation-targeted message releases the target instead
// of toggling selection.
if (isRootNavTargeted()) {
- props.onClearTarget?.(props.data().id);
+ props.targetNavigation?.onClearTarget(props.data().id);
return;
}
// On touch devices, we want to block "click to select"
@@ -126,8 +136,8 @@ export function ChannelThread(props: ThreadProps) {
const selectReply = (replyId: string) => {
// Clicking the navigation-targeted reply releases the target instead of
// toggling selection.
- if (props.activeTargetReplyId === replyId) {
- props.onClearTarget?.(props.data().id);
+ if (props.targetNavigation?.activeTargetReplyId() === replyId) {
+ props.targetNavigation.onClearTarget(props.data().id);
return;
}
// On touch devices, we want to block "click to select"
@@ -195,12 +205,37 @@ export function ChannelThread(props: ThreadProps) {
!shouldShowCollapsedIndicator();
const [replyListHandle, setReplyListHandle] =
createSignal<ThreadReplyListHandle>();
+ const [threadRowElement, setThreadRowElement] = createSignal<HTMLElement>();
+ const targetMessageScroller = createTargetReplyScroller({
+ getTarget: () =>
+ threadRowElement()?.querySelector<HTMLElement>(
+ `[data-message-id="${props.data().id}"]`
+ ) ?? undefined,
+ positionTarget: props.targetNavigation?.positionTarget,
+ });
+
+ createEffect(
+ on(
+ [() => props.targetNavigation?.targetMessageId(), threadRowElement],
+ ([targetMessageId]) => {
+ if (!targetMessageId || targetMessageId !== props.data().id) {
+ targetMessageScroller.cancel();
+ return;
+ }
+ targetMessageScroller.scrollToIndex(0, () => {
+ props.targetNavigation?.onTargetMessageScrolled(targetMessageId);
+ });
+ }
+ )
+ );
+
+ onCleanup(targetMessageScroller.dispose);
createEffect(
on(
[
- () => props.activeTargetReplyId,
- () => props.targetReplyId,
+ () => props.targetNavigation?.activeTargetReplyId(),
+ () => props.targetNavigation?.targetReplyId(),
loadedReplies,
],
([activeTargetReplyId, _targetReplyId, replies]) => {
@@ -219,52 +254,42 @@ export function ChannelThread(props: ThreadProps) {
)
);
- createEffect(
- on(
- [() => props.targetReplyId, displayReplies, props.isExpanded],
- ([targetReplyId, rendered, isExpanded]) => {
- if (!targetReplyId || isExpanded) return;
- if (rendered.some((r) => r.id === targetReplyId)) return;
- props.setIsExpanded(true);
- }
- )
- );
-
- // this stops re-scrolling to the same target
- let lastScrolledReplyId: string | undefined;
+ const targetReplyNavigation = createTargetReplyNavigationController();
createEffect(
on(
[
- () => props.targetReplyId,
+ () => props.targetNavigation?.targetReplyId(),
replyListHandle,
canScrollToTargetReply,
props.isExpanded,
],
([targetReplyId, handle, canScroll, isExpanded]) => {
- if (!targetReplyId) {
- lastScrolledReplyId = undefined;
- return;
- }
- if (lastScrolledReplyId === targetReplyId) return;
- if (!canScroll || !handle) return;
-
// Untracked: channel-message reconciles must not re-fire scroll.
- const replies = isExpanded
- ? untrack(loadedReplies)
- : untrack(displayReplies);
- const index = replies.findIndex((r) => r.id === targetReplyId);
- if (index === -1) return;
-
- if (!handle.scrollToIndex(index)) return;
- lastScrolledReplyId = targetReplyId;
- props.onTargetReplyScrolled?.(targetReplyId);
+ const replies =
+ targetReplyId && canScroll && handle
+ ? isExpanded
+ ? untrack(loadedReplies)
+ : untrack(displayReplies)
+ : [];
+ targetReplyNavigation.update({
+ targetReplyId,
+ handle,
+ canScroll,
+ replies,
+ getCurrentTargetReplyId: () =>
+ props.targetNavigation?.targetReplyId(),
+ onScrolled: props.targetNavigation?.onTargetReplyScrolled,
+ });
}
)
);
+ onCleanup(targetReplyNavigation.dispose);
+
return (
<DebugSuspense name="ChannelThread.root">
<Thread.Row
+ ref={setThreadRowElement}
channelId={props.channelId()}
message={props.data()}
listMeta={props.listMeta}
@@ -315,9 +340,10 @@ export function ChannelThread(props: ThreadProps) {
participants={props.participants}
isNewMessage={props.isNewMessage}
onReady={setReplyListHandle}
+ positionTarget={props.targetNavigation?.positionTarget}
selectedReplyId={replySelection.selectedId}
targetedReplyId={() =>
- props.activeTargetReplyId ??
+ props.targetNavigation?.activeTargetReplyId() ??
unifiedReplyBinding()?.boundReplyId
}
isThreadFocused={isThreadFocused}
diff --git a/apps/web/src/features/channel/Thread/ThreadReplyList.tsx b/apps/web/src/features/channel/Thread/ThreadReplyList.tsx
index cc2f001fcd..dff7da3b72 100644
--- a/apps/web/src/features/channel/Thread/ThreadReplyList.tsx
+++ b/apps/web/src/features/channel/Thread/ThreadReplyList.tsx
@@ -1,7 +1,7 @@
import type { IUser } from '@core/user/types';
import { MarkMessageNotifications } from '@notifications/components/MarkMessageNotifications';
import type { ApiThreadReply } from '@service-storage/generated/schemas/apiThreadReply';
-import { type Accessor, createMemo, For, onMount } from 'solid-js';
+import { type Accessor, createMemo, For, onCleanup, onMount } from 'solid-js';
import type { MessageEditor } from '../Channel/create-message-editor';
import type { NewMessageCheckable } from '../Channel/util';
import {
@@ -9,21 +9,15 @@ import {
type MessageActions,
type MessageData,
} from '../Message';
+import { createTargetReplyScroller } from './create-target-reply-scroller';
import { buildThreadReplyListMeta } from './reply-list-meta';
import { ThreadRail } from './ThreadRail';
export type ThreadReplyListHandle = {
- scrollToIndex: (index: number) => boolean;
+ scrollToIndex: (index: number, onSettled: () => void) => boolean;
+ cancelScroll: () => void;
};
-function getReplyElementAtIndex(
- elements: Array<HTMLElement | undefined>,
- index: number
-): HTMLElement | undefined {
- if (index < 0) return undefined;
- return elements[index];
-}
-
export function ThreadReplyList(props: {
channelId: string;
threadId: string;
@@ -33,6 +27,10 @@ export function ThreadReplyList(props: {
participants?: Accessor<IUser[]>;
isNewMessage?: (message: NewMessageCheckable) => boolean;
onReady?: (handle: ThreadReplyListHandle) => void;
+ positionTarget?: (
+ threadRow: HTMLElement,
+ targetReply: HTMLElement
+ ) => boolean;
selectedReplyId?: Accessor<string | undefined>;
/**
* Reply targeted by channel navigation or bound to the unified input's reply (quote-reply).
@@ -45,21 +43,20 @@ export function ThreadReplyList(props: {
buildThreadReplyListMeta(props.replies, props.isNewMessage)
);
const replyElements: Array<HTMLElement | undefined> = [];
-
- const scrollToIndex = (index: number): boolean => {
- const element = getReplyElementAtIndex(replyElements, index);
- if (!element) return false;
- // NOTE: this rAF helps prevent situations where the deeply nested thread element is unmounted
- requestAnimationFrame(() => element.scrollIntoView({ block: 'center' }));
- return true;
- };
+ const targetReplyScroller = createTargetReplyScroller({
+ getTarget: (index) => replyElements[index],
+ positionTarget: props.positionTarget,
+ });
onMount(() => {
props.onReady?.({
- scrollToIndex,
+ scrollToIndex: targetReplyScroller.scrollToIndex,
+ cancelScroll: targetReplyScroller.cancel,
});
});
+ onCleanup(targetReplyScroller.dispose);
+
return (
<For each={props.replies}>
{(reply, index) => {
diff --git a/apps/web/src/features/channel/Thread/ThreadRow.tsx b/apps/web/src/features/channel/Thread/ThreadRow.tsx
index 587248c5c6..1d3a344aa6 100644
--- a/apps/web/src/features/channel/Thread/ThreadRow.tsx
+++ b/apps/web/src/features/channel/Thread/ThreadRow.tsx
@@ -9,6 +9,7 @@ import {
import { ThreadRail } from './ThreadRail';
type ThreadRowProps = ParentProps & {
+ ref?: (element: HTMLDivElement) => void;
/** Present only in channel threads; other consumers (calls, PRs, comments) omit it. */
channelId?: string;
message: ApiChannelMessage;
@@ -23,7 +24,11 @@ export function ThreadRow(props: ThreadRowProps) {
: undefined;
return (
- <div class="w-full flex justify-center">
+ <div
+ ref={(element) => props.ref?.(element)}
+ data-channel-thread-row
+ class="w-full flex justify-center"
+ >
<div class="macro-message-width w-full relative">
<Show when={channelCreatedId()}>
{(id) => <ChannelCreatedIndicator channelId={id()} />}
diff --git a/apps/web/src/features/channel/Thread/create-target-reply-navigation-controller.ts b/apps/web/src/features/channel/Thread/create-target-reply-navigation-controller.ts
new file mode 100644
index 0000000000..94728b2a9d
--- /dev/null
+++ b/apps/web/src/features/channel/Thread/create-target-reply-navigation-controller.ts
@@ -0,0 +1,75 @@
+import type { ThreadReplyListHandle } from './ThreadReplyList';
+
+type Reply = { id: string };
+
+type TargetReplyNavigation = {
+ targetReplyId?: string;
+ handle?: ThreadReplyListHandle;
+ canScroll: boolean;
+ replies: readonly Reply[];
+ getCurrentTargetReplyId: () => string | undefined;
+ onScrolled?: (replyId: string) => void;
+};
+
+/** Coordinates one-shot reply navigation across async target changes. */
+export function createTargetReplyNavigationController() {
+ let lastScrolledReplyId: string | undefined;
+ let inFlightReplyId: string | undefined;
+ let inFlightHandle: ThreadReplyListHandle | undefined;
+
+ const clearInFlight = () => {
+ inFlightReplyId = undefined;
+ inFlightHandle = undefined;
+ };
+
+ const cancelInFlight = () => {
+ inFlightHandle?.cancelScroll();
+ clearInFlight();
+ };
+
+ const update = ({
+ targetReplyId,
+ handle,
+ canScroll,
+ replies,
+ getCurrentTargetReplyId,
+ onScrolled,
+ }: TargetReplyNavigation) => {
+ if (inFlightReplyId && inFlightReplyId !== targetReplyId) {
+ cancelInFlight();
+ }
+
+ if (!targetReplyId) {
+ if (inFlightHandle) cancelInFlight();
+ else handle?.cancelScroll();
+ lastScrolledReplyId = undefined;
+ return;
+ }
+ if (lastScrolledReplyId === targetReplyId) return;
+ if (!canScroll || !handle) return;
+
+ const index = replies.findIndex((reply) => reply.id === targetReplyId);
+ if (index === -1) return;
+
+ if (inFlightHandle && inFlightHandle !== handle) cancelInFlight();
+ inFlightReplyId = targetReplyId;
+ inFlightHandle = handle;
+ const started = handle.scrollToIndex(index, () => {
+ if (inFlightReplyId === targetReplyId && inFlightHandle === handle) {
+ clearInFlight();
+ }
+ if (getCurrentTargetReplyId() !== targetReplyId) return;
+ lastScrolledReplyId = targetReplyId;
+ onScrolled?.(targetReplyId);
+ });
+ if (
+ !started &&
+ inFlightReplyId === targetReplyId &&
+ inFlightHandle === handle
+ ) {
+ clearInFlight();
+ }
+ };
+
+ return { update, dispose: cancelInFlight };
+}
diff --git a/apps/web/src/features/channel/Thread/create-target-reply-scroller.ts b/apps/web/src/features/channel/Thread/create-target-reply-scroller.ts
new file mode 100644
index 0000000000..d893a6a7e5
--- /dev/null
+++ b/apps/web/src/features/channel/Thread/create-target-reply-scroller.ts
@@ -0,0 +1,249 @@
+const CHANNEL_SCROLL_SELECTOR = '[data-channel-scroll]';
+const CHANNEL_THREAD_ROW_SELECTOR = '[data-channel-thread-row]';
+const TARGET_SCROLL_QUIET_MS = 200;
+const TARGET_SCROLL_TIMEOUT_MS = 1000;
+const TARGET_MEASUREMENT_TIMEOUT_MS = 250;
+const TARGET_VISIBILITY_TOLERANCE_PX = 1;
+
+const SCROLL_KEYS = new Set([
+ 'ArrowUp',
+ 'ArrowDown',
+ 'PageUp',
+ 'PageDown',
+ 'Home',
+ 'End',
+ ' ',
+]);
+
+export type TargetReplyScroller = {
+ scrollToIndex: (index: number, onSettled: () => void) => boolean;
+ cancel: () => void;
+ dispose: () => void;
+};
+
+/**
+ * Keeps a nested reply positioned while the outer channel virtualizer measures
+ * its newly expanded thread row.
+ */
+export function createTargetReplyScroller(options: {
+ getTarget: (index: number) => HTMLElement | undefined;
+ positionTarget?: (
+ threadRow: HTMLElement,
+ targetElement: HTMLElement
+ ) => boolean;
+}): TargetReplyScroller {
+ let cancelCurrentScroll: (() => void) | undefined;
+
+ const cancel = () => cancelCurrentScroll?.();
+
+ const scrollToIndex = (index: number, onSettled: () => void): boolean => {
+ cancel();
+
+ const initialTarget = options.getTarget(index);
+ if (!initialTarget) return false;
+
+ const scrollElement = initialTarget.closest<HTMLElement>(
+ CHANNEL_SCROLL_SELECTOR
+ );
+ if (!scrollElement) return false;
+
+ let completed = false;
+ let positionRafId = 0;
+ let measurementRafId = 0;
+ let completionRafId = 0;
+ let verifyTimerId: number | undefined;
+ let measurementTimerId: number | undefined;
+ let measurementMicrotaskQueued = false;
+ let hasPositioned = false;
+ const startedAt = performance.now();
+ const getThreadRow = () =>
+ options
+ .getTarget(index)
+ ?.closest<HTMLElement>(CHANNEL_THREAD_ROW_SELECTOR);
+ const threadRow = getThreadRow();
+ const virtualItem = threadRow?.parentElement;
+
+ const resizeObserver = threadRow
+ ? new ResizeObserver(() => schedulePositionAfterMeasurement())
+ : undefined;
+ // Measuring an earlier virtual item can change this wrapper's absolute
+ // offset without resizing the target row. Observe that position update so
+ // the correction runs in the mutation microtask checkpoint before paint.
+ const positionObserver = virtualItem
+ ? new MutationObserver(() => {
+ if (!completed) positionTarget();
+ })
+ : undefined;
+
+ const cleanup = () => {
+ if (positionRafId) cancelAnimationFrame(positionRafId);
+ if (measurementRafId) cancelAnimationFrame(measurementRafId);
+ if (completionRafId) cancelAnimationFrame(completionRafId);
+ if (verifyTimerId !== undefined) window.clearTimeout(verifyTimerId);
+ if (measurementTimerId !== undefined)
+ window.clearTimeout(measurementTimerId);
+ resizeObserver?.disconnect();
+ positionObserver?.disconnect();
+ scrollElement.removeEventListener('wheel', handleUserScroll);
+ scrollElement.removeEventListener('pointerdown', handlePointerDown);
+ scrollElement.removeEventListener('keydown', handleKeyDown);
+ if (cancelCurrentScroll === abort) cancelCurrentScroll = undefined;
+ };
+
+ const abort = () => {
+ if (completed) return;
+ completed = true;
+ cleanup();
+ };
+
+ const complete = () => {
+ if (completed) return;
+ completed = true;
+ cleanup();
+ onSettled();
+ };
+
+ const isTargetPositioned = () => {
+ const target = options.getTarget(index);
+ if (!target?.isConnected || !scrollElement.isConnected) return false;
+
+ const targetRect = target.getBoundingClientRect();
+ const scrollRect = scrollElement.getBoundingClientRect();
+ if (targetRect.height <= scrollRect.height) {
+ return (
+ targetRect.top >= scrollRect.top - TARGET_VISIBILITY_TOLERANCE_PX &&
+ targetRect.bottom <=
+ scrollRect.bottom + TARGET_VISIBILITY_TOLERANCE_PX
+ );
+ }
+
+ return (
+ targetRect.top <= scrollRect.top + TARGET_VISIBILITY_TOLERANCE_PX &&
+ targetRect.bottom >= scrollRect.bottom - TARGET_VISIBILITY_TOLERANCE_PX
+ );
+ };
+
+ const scheduleVerification = () => {
+ if (verifyTimerId !== undefined) window.clearTimeout(verifyTimerId);
+ verifyTimerId = window.setTimeout(() => {
+ verifyTimerId = undefined;
+ if (isTargetPositioned()) {
+ complete();
+ return;
+ }
+
+ if (performance.now() - startedAt < TARGET_SCROLL_TIMEOUT_MS) {
+ schedulePosition();
+ return;
+ }
+
+ // Do one final correction before releasing the one-shot target.
+ options.getTarget(index)?.scrollIntoView({ block: 'center' });
+ completionRafId = requestAnimationFrame(() => {
+ completionRafId = 0;
+ complete();
+ });
+ }, TARGET_SCROLL_QUIET_MS);
+ };
+
+ const positionTarget = () => {
+ const target = options.getTarget(index);
+ if (!target?.isConnected) {
+ scheduleVerification();
+ return;
+ }
+ const currentThreadRow = getThreadRow();
+ const positionedByVirtualizer =
+ currentThreadRow && options.positionTarget?.(currentThreadRow, target);
+ if (!positionedByVirtualizer) {
+ target.scrollIntoView({ block: 'center' });
+ }
+ hasPositioned = true;
+ scheduleVerification();
+ };
+
+ function schedulePosition() {
+ if (completed || positionRafId) return;
+ positionRafId = requestAnimationFrame(() => {
+ positionRafId = 0;
+ positionTarget();
+ });
+ }
+
+ function schedulePositionAfterMeasurement() {
+ if (completed) return;
+ // ResizeObserver callbacks run before paint, but callback order between
+ // observers is not a safe contract. Defer to a microtask so Virtua's
+ // sibling observer has applied the new item geometry before we position
+ // against it, while still correcting before the browser can paint.
+ if (!measurementMicrotaskQueued) {
+ measurementMicrotaskQueued = true;
+ queueMicrotask(() => {
+ measurementMicrotaskQueued = false;
+ if (!completed) positionTarget();
+ });
+ }
+ if (!hasPositioned && positionRafId) {
+ cancelAnimationFrame(positionRafId);
+ positionRafId = 0;
+ }
+ if (measurementRafId) cancelAnimationFrame(measurementRafId);
+ if (measurementTimerId !== undefined) {
+ window.clearTimeout(measurementTimerId);
+ measurementTimerId = undefined;
+ }
+
+ // Virtua may commit a corrected item range in the first frame after a
+ // row measurement. Position in the following frame against that DOM.
+ measurementRafId = requestAnimationFrame(() => {
+ measurementRafId = requestAnimationFrame(() => {
+ measurementRafId = 0;
+ positionTarget();
+ });
+ });
+ }
+
+ function handleUserScroll() {
+ complete();
+ }
+
+ function handlePointerDown(event: PointerEvent) {
+ if (event.pointerType === 'touch') complete();
+ }
+
+ function handleKeyDown(event: KeyboardEvent) {
+ if (SCROLL_KEYS.has(event.key)) complete();
+ }
+
+ scrollElement.addEventListener('wheel', handleUserScroll, {
+ passive: true,
+ });
+ scrollElement.addEventListener('pointerdown', handlePointerDown, {
+ passive: true,
+ });
+ scrollElement.addEventListener('keydown', handleKeyDown);
+ if (threadRow) resizeObserver?.observe(threadRow);
+ if (virtualItem) {
+ positionObserver?.observe(virtualItem, {
+ attributes: true,
+ attributeFilter: ['style'],
+ });
+ }
+ cancelCurrentScroll = abort;
+
+ // Wait for the outer row's initial measurement before the first visible
+ // movement. ResizeObserver delivers an initial notification on observe;
+ // the timeout is only a defensive fallback for disconnected/mocked DOM.
+ measurementTimerId = window.setTimeout(() => {
+ measurementTimerId = undefined;
+ if (!hasPositioned) schedulePosition();
+ }, TARGET_MEASUREMENT_TIMEOUT_MS);
+ return true;
+ };
+
+ return {
+ scrollToIndex,
+ cancel,
+ dispose: cancel,
+ };
+}
diff --git a/apps/web/src/features/channel/Thread/index.ts b/apps/web/src/features/channel/Thread/index.ts
index cfc9da6fb6..b565ea2148 100644
--- a/apps/web/src/features/channel/Thread/index.ts
+++ b/apps/web/src/features/channel/Thread/index.ts
@@ -1,4 +1,9 @@
export { ChannelThread } from './ChannelThread';
export { Thread } from './Thread';
export { ThreadTypingIndicator } from './ThreadTypingIndicator';
-export type { ThreadActions, ThreadProps, ThreadState } from './types';
+export type {
+ ThreadActions,
+ ThreadProps,
+ ThreadState,
+ ThreadTargetNavigation,
+} from './types';
diff --git a/apps/web/src/features/channel/Thread/tests/create-target-reply-navigation-controller.test.ts b/apps/web/src/features/channel/Thread/tests/create-target-reply-navigation-controller.test.ts
new file mode 100644
index 0000000000..31a5c420b4
--- /dev/null
+++ b/apps/web/src/features/channel/Thread/tests/create-target-reply-navigation-controller.test.ts
@@ -0,0 +1,51 @@
+import { describe, expect, it, vi } from 'vitest';
+import { createTargetReplyNavigationController } from '../create-target-reply-navigation-controller';
+import type { ThreadReplyListHandle } from '../ThreadReplyList';
+
+function createHandle() {
+ let settle = () => {};
+ const handle: ThreadReplyListHandle = {
+ scrollToIndex: vi.fn((_index, onSettled) => {
+ settle = onSettled;
+ return true;
+ }),
+ cancelScroll: vi.fn(),
+ };
+ return { handle, settle: () => settle() };
+}
+
+describe('createTargetReplyNavigationController', () => {
+ it('cancels target A before returning while target B is unavailable', () => {
+ const controller = createTargetReplyNavigationController();
+ const first = createHandle();
+ const onScrolled = vi.fn();
+ let currentTargetReplyId: string | undefined = 'reply-a';
+
+ controller.update({
+ targetReplyId: currentTargetReplyId,
+ handle: first.handle,
+ canScroll: true,
+ replies: [{ id: 'reply-a' }],
+ getCurrentTargetReplyId: () => currentTargetReplyId,
+ onScrolled,
+ });
+ expect(first.handle.scrollToIndex).toHaveBeenCalledWith(
+ 0,
+ expect.any(Function)
+ );
+
+ currentTargetReplyId = 'reply-b';
+ controller.update({
+ targetReplyId: currentTargetReplyId,
+ handle: first.handle,
+ canScroll: false,
+ replies: [],
+ getCurrentTargetReplyId: () => currentTargetReplyId,
+ onScrolled,
+ });
+
+ expect(first.handle.cancelScroll).toHaveBeenCalledOnce();
+ first.settle();
+ expect(onScrolled).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/src/features/channel/Thread/tests/create-target-reply-scroller.test.ts b/apps/web/src/features/channel/Thread/tests/create-target-reply-scroller.test.ts
new file mode 100644
index 0000000000..2ecc9eaf42
--- /dev/null
+++ b/apps/web/src/features/channel/Thread/tests/create-target-reply-scroller.test.ts
@@ -0,0 +1,239 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createTargetReplyScroller } from '../create-target-reply-scroller';
+
+class ResizeObserverMock {
+ static instances: ResizeObserverMock[] = [];
+
+ readonly observe = vi.fn();
+ readonly unobserve = vi.fn();
+ readonly disconnect = vi.fn();
+
+ constructor(private readonly callback: ResizeObserverCallback) {
+ ResizeObserverMock.instances.push(this);
+ }
+
+ trigger() {
+ this.callback([], this as unknown as ResizeObserver);
+ }
+}
+
+const rect = (top: number, bottom: number): DOMRect =>
+ ({
+ x: 0,
+ y: top,
+ width: 500,
+ height: bottom - top,
+ top,
+ right: 500,
+ bottom,
+ left: 0,
+ toJSON: () => ({}),
+ }) as DOMRect;
+
+describe('createTargetReplyScroller', () => {
+ let animationFrames: Map<number, FrameRequestCallback>;
+ let nextAnimationFrameId: number;
+
+ const flushAnimationFrame = () => {
+ const callbacks = [...animationFrames.values()];
+ animationFrames.clear();
+ for (const callback of callbacks) callback(performance.now());
+ };
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ ResizeObserverMock.instances = [];
+ animationFrames = new Map();
+ nextAnimationFrameId = 1;
+
+ vi.stubGlobal('ResizeObserver', ResizeObserverMock);
+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {
+ const id = nextAnimationFrameId++;
+ animationFrames.set(id, callback);
+ return id;
+ });
+ vi.stubGlobal('cancelAnimationFrame', (id: number) => {
+ animationFrames.delete(id);
+ });
+ });
+
+ afterEach(() => {
+ document.body.replaceChildren();
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ });
+
+ const createFixture = () => {
+ const scrollElement = document.createElement('div');
+ scrollElement.dataset.channelScroll = '';
+ const virtualItem = document.createElement('div');
+ const threadRow = document.createElement('div');
+ threadRow.dataset.channelThreadRow = '';
+ const target = document.createElement('div');
+ threadRow.append(target);
+ virtualItem.append(threadRow);
+ scrollElement.append(virtualItem);
+ document.body.append(scrollElement);
+
+ let targetRect = rect(1000, 1050);
+ vi.spyOn(scrollElement, 'getBoundingClientRect').mockReturnValue(
+ rect(0, 600)
+ );
+ vi.spyOn(target, 'getBoundingClientRect').mockImplementation(
+ () => targetRect
+ );
+ const scrollIntoView = vi.fn(() => {
+ targetRect = rect(275, 325);
+ });
+ target.scrollIntoView = scrollIntoView;
+
+ return {
+ scrollElement,
+ virtualItem,
+ threadRow,
+ target,
+ scrollIntoView,
+ setTargetRect: (next: DOMRect) => {
+ targetRect = next;
+ },
+ };
+ };
+
+ it('waits for the expanded thread row measurement before positioning', async () => {
+ const fixture = createFixture();
+ const onSettled = vi.fn();
+ const scroller = createTargetReplyScroller({
+ getTarget: () => fixture.target,
+ });
+
+ expect(scroller.scrollToIndex(0, onSettled)).toBe(true);
+ flushAnimationFrame();
+ expect(fixture.scrollIntoView).not.toHaveBeenCalled();
+
+ ResizeObserverMock.instances[0].trigger();
+ await Promise.resolve();
+ expect(fixture.scrollIntoView).toHaveBeenCalledTimes(1);
+ flushAnimationFrame();
+ flushAnimationFrame();
+ expect(fixture.scrollIntoView).toHaveBeenCalledTimes(2);
+
+ fixture.setTargetRect(rect(1000, 1050));
+ ResizeObserverMock.instances[0].trigger();
+ await Promise.resolve();
+ expect(fixture.scrollIntoView).toHaveBeenCalledTimes(3);
+ flushAnimationFrame();
+ flushAnimationFrame();
+ expect(fixture.scrollIntoView).toHaveBeenCalledTimes(4);
+
+ vi.advanceTimersByTime(200);
+ expect(onSettled).toHaveBeenCalledOnce();
+ expect(ResizeObserverMock.instances[0].disconnect).toHaveBeenCalledOnce();
+ });
+
+ it('positions through the outer virtualizer after sibling resize observers', async () => {
+ const fixture = createFixture();
+ let virtualizerMeasurementApplied = false;
+ const positionTarget = vi.fn(() => virtualizerMeasurementApplied);
+ const scroller = createTargetReplyScroller({
+ getTarget: () => fixture.target,
+ positionTarget,
+ });
+
+ expect(scroller.scrollToIndex(0, vi.fn())).toBe(true);
+ ResizeObserverMock.instances[0].trigger();
+ expect(positionTarget).not.toHaveBeenCalled();
+ // Simulate Virtua's ResizeObserver running later in the same delivery.
+ virtualizerMeasurementApplied = true;
+ await Promise.resolve();
+ flushAnimationFrame();
+ flushAnimationFrame();
+
+ expect(positionTarget).toHaveBeenCalledWith(
+ fixture.threadRow,
+ fixture.target
+ );
+ expect(fixture.scrollIntoView).not.toHaveBeenCalled();
+ });
+
+ it('repositions before paint when an earlier item changes the target offset', async () => {
+ const fixture = createFixture();
+ const scroller = createTargetReplyScroller({
+ getTarget: () => fixture.target,
+ });
+
+ expect(scroller.scrollToIndex(0, vi.fn())).toBe(true);
+ ResizeObserverMock.instances[0].trigger();
+ await Promise.resolve();
+ expect(fixture.scrollIntoView).toHaveBeenCalledTimes(1);
+
+ fixture.setTargetRect(rect(4300, 4350));
+ fixture.virtualItem.style.top = '4240px';
+ await Promise.resolve();
+
+ expect(fixture.scrollIntoView).toHaveBeenCalledTimes(2);
+ });
+
+ it('uses the current reply element after a virtualized remount', async () => {
+ const fixture = createFixture();
+ let currentTarget = fixture.target;
+ const scroller = createTargetReplyScroller({
+ getTarget: () => currentTarget,
+ });
+
+ expect(scroller.scrollToIndex(0, vi.fn())).toBe(true);
+ ResizeObserverMock.instances[0].trigger();
+ await Promise.resolve();
+ flushAnimationFrame();
+ flushAnimationFrame();
+
+ const remountedTarget = document.createElement('div');
+ const remountedScrollIntoView = vi.fn();
+ remountedTarget.scrollIntoView = remountedScrollIntoView;
+ fixture.target.remove();
+ fixture.threadRow.append(remountedTarget);
+ currentTarget = remountedTarget;
+
+ ResizeObserverMock.instances[0].trigger();
+ await Promise.resolve();
+ flushAnimationFrame();
+ flushAnimationFrame();
+
+ expect(remountedScrollIntoView).toHaveBeenCalledTimes(2);
+ });
+
+ it('disposes pending work without acknowledging the target', () => {
+ const fixture = createFixture();
+ const onSettled = vi.fn();
+ const scroller = createTargetReplyScroller({
+ getTarget: () => fixture.target,
+ });
+
+ expect(scroller.scrollToIndex(0, onSettled)).toBe(true);
+ scroller.dispose();
+ flushAnimationFrame();
+ vi.runAllTimers();
+
+ fixture.scrollElement.dispatchEvent(new WheelEvent('wheel'));
+ ResizeObserverMock.instances[0].trigger();
+ flushAnimationFrame();
+
+ expect(fixture.scrollIntoView).not.toHaveBeenCalled();
+ expect(onSettled).not.toHaveBeenCalled();
+ expect(ResizeObserverMock.instances[0].disconnect).toHaveBeenCalledOnce();
+ });
+
+ it('releases navigation when the user starts scrolling', () => {
+ const fixture = createFixture();
+ const onSettled = vi.fn();
+ const scroller = createTargetReplyScroller({
+ getTarget: () => fixture.target,
+ });
+
+ expect(scroller.scrollToIndex(0, onSettled)).toBe(true);
+ flushAnimationFrame();
+ fixture.scrollElement.dispatchEvent(new WheelEvent('wheel'));
+
+ expect(onSettled).toHaveBeenCalledOnce();
+ expect(ResizeObserverMock.instances[0].disconnect).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/web/src/features/channel/Thread/types.ts b/apps/web/src/features/channel/Thread/types.ts
index afdf9478f9..0f9d10551a 100644
--- a/apps/web/src/features/channel/Thread/types.ts
+++ b/apps/web/src/features/channel/Thread/types.ts
@@ -36,6 +36,21 @@ export type MessageEditState = {
snapshot: InputSnapshot;
};
+/** Reactive contract for positioning and releasing a channel navigation target. */
+export type ThreadTargetNavigation = {
+ targetThreadId: Accessor<string | undefined>;
+ targetMessageId: Accessor<string | undefined>;
+ targetReplyId: Accessor<string | undefined>;
+ activeTargetReplyId: Accessor<string | undefined>;
+ positionTarget: (
+ threadRow: HTMLElement,
+ targetElement: HTMLElement
+ ) => boolean;
+ onTargetMessageScrolled: (messageId: string) => void;
+ onTargetReplyScrolled: (replyId: string) => void;
+ onClearTarget: (threadId: string) => void;
+};
+
export type ThreadProps = {
data: Accessor<ApiChannelMessage>;
channelId: Accessor<string>;
@@ -44,20 +59,13 @@ export type ThreadProps = {
threadActions?: ThreadActions;
messageEditor?: MessageEditor;
participants?: Accessor<IUser[]>;
- targetThreadId?: string;
- /** One-shot scroll target. Caller must clear via `onTargetReplyScrolled`. */
- targetReplyId?: string;
- onTargetReplyScrolled?: (replyId: string) => void;
- /** Navigation target reply */
- activeTargetReplyId?: string;
+ targetNavigation?: ThreadTargetNavigation;
/** The unified input's reply binding */
unifiedReplyTarget?: { threadId: string; replyId?: string };
isNewMessage?: (reply: NewMessageCheckable) => boolean;
selectedMessageId?: Accessor<string | undefined>;
onSelectMessage?: (messageId: string) => void;
onClearSelection?: () => void;
- /** Release the navigation target (clicking the targeted message). */
- onClearTarget?: (threadId: string) => void;
messageListScopeId?: string;
isNewestThread?: boolean;
} & ThreadState;
diff --git a/apps/web/tests/e2e/fixtures/local-e2e-seed.ts b/apps/web/tests/e2e/fixtures/local-e2e-seed.ts
index 16ee7278ef..d693091400 100644
--- a/apps/web/tests/e2e/fixtures/local-e2e-seed.ts
+++ b/apps/web/tests/e2e/fixtures/local-e2e-seed.ts
@@ -17,8 +17,45 @@ type SeedManifest = {
id: string;
name: string;
message: string;
+ navigationLauncherMessageId: string;
+ deepThread: {
+ parentMessageId: string;
+ firstReplyId: string;
+ targetReplyId: string;
+ targetReplyText: string;
+ oversizedReplyId: string;
+ oversizedReplyText: string;
+ };
+ alternateDeepThread: {
+ parentMessageId: string;
+ targetReplyId: string;
+ targetReplyText: string;
+ };
};
};
+ navigation: {
+ genericChannelMention: {
+ sourceChannelId: string;
+ sourceChannelName: string;
+ sourceMessageId: string;
+ };
+ targetedMessageMention: {
+ sourceChannelId: string;
+ sourceChannelName: string;
+ sourceMessageId: string;
+ };
+ unreadMessageNavigation: {
+ sourceChannelId: string;
+ sourceChannelName: string;
+ sourceMessageId: string;
+ parentMessageId: string;
+ cacheWarmerReplyId: string;
+ cacheWarmerReplyText: string;
+ targetReplyId: string;
+ targetReplyText: string;
+ };
+ unreadNotificationId: string;
+ };
};
export type SeedUser = {
@@ -167,5 +204,33 @@ export const localE2ESeed = {
),
`message ${manifest.channels.general.message}`
),
+ generalNavigationLauncherMessageId:
+ manifest.channels.general.navigationLauncherMessageId,
+ generalDeepThread: manifest.channels.general.deepThread,
+ generalAlternateDeepThread: manifest.channels.general.alternateDeepThread,
+ genericMentionSourceChannel: required(
+ channelsById.get(
+ manifest.navigation.genericChannelMention.sourceChannelId
+ ),
+ `channel ${manifest.navigation.genericChannelMention.sourceChannelId}`
+ ),
+ genericMentionSourceMessageId:
+ manifest.navigation.genericChannelMention.sourceMessageId,
+ targetedMentionSourceChannel: required(
+ channelsById.get(
+ manifest.navigation.targetedMessageMention.sourceChannelId
+ ),
+ `channel ${manifest.navigation.targetedMessageMention.sourceChannelId}`
+ ),
+ targetedMentionSourceMessageId:
+ manifest.navigation.targetedMessageMention.sourceMessageId,
+ unreadMessageNavigation: manifest.navigation.unreadMessageNavigation,
+ unreadMentionSourceChannel: required(
+ channelsById.get(
+ manifest.navigation.unreadMessageNavigation.sourceChannelId
+ ),
+ `channel ${manifest.navigation.unreadMessageNavigation.sourceChannelId}`
+ ),
+ unreadChannelNotificationId: manifest.navigation.unreadNotificationId,
},
} as const;
diff --git a/apps/web/tests/e2e/helpers/scroll-presentation.ts b/apps/web/tests/e2e/helpers/scroll-presentation.ts
index eb5db56260..624c33863c 100644
--- a/apps/web/tests/e2e/helpers/scroll-presentation.ts
+++ b/apps/web/tests/e2e/helpers/scroll-presentation.ts
@@ -10,27 +10,222 @@ type BottomPresentationSample = {
distanceFromBottom: number;
};
+type TargetPresentationSample = {
+ time: number;
+ center: number;
+ positioned: boolean;
+ visible: boolean;
+ scrollTop: number;
+ targetHeight: number;
+ targetTop: number;
+ virtualItemTop?: number;
+ virtualItemStyleTop?: string;
+ virtualItemVisibility?: string;
+ usableViewportHeight: number;
+ insetStart: number;
+ insetEnd: number;
+};
+
export type BottomPresentationReport = {
first?: BottomPresentationSample;
firstViolation?: BottomPresentationSample;
violationCount: number;
};
+export type TargetPresentationReport = {
+ first?: TargetPresentationSample;
+ firstPositioned?: TargetPresentationSample;
+ last?: TargetPresentationSample;
+ unpositionedBeforeLandingCount: number;
+ largestShiftAfterPositioned: number;
+ firstPositionLoss?: TargetPresentationSample;
+ positionLossCount: number;
+ lastChangeAt?: number;
+};
+
declare global {
interface Window {
__e2eResizeObserverDelay?: ResizeObserverDelayState;
__e2eBottomPresentation?: BottomPresentationReport;
+ __e2eResetBottomPresentation?: () => void;
+ __e2eTargetPresentation?: TargetPresentationReport;
+ __e2eResetTargetPresentation?: () => void;
+ __e2eStopTargetPresentation?: () => void;
}
}
-/** Delay ResizeObserver callbacks for a DOM subtree to make layout races deterministic. */
+/**
+ * Sample painted target positions. A normal target must fit inside the usable
+ * viewport; a target taller than that viewport must cover it. Insets exclude
+ * floating mobile chrome from the usable viewport. Once the target lands, any
+ * later movement or position loss is a user-visible second-pass correction.
+ */
+export async function observeTargetPresentation(
+ page: Page,
+ scrollSelector: string,
+ targetSelector: string,
+ tolerancePx = 1
+) {
+ await page.addInitScript(
+ ({ scrollSelector, targetSelector, tolerancePx }) => {
+ const createReport = (): TargetPresentationReport => ({
+ unpositionedBeforeLandingCount: 0,
+ largestShiftAfterPositioned: 0,
+ positionLossCount: 0,
+ });
+ let report = createReport();
+ window.__e2eTargetPresentation = report;
+ let stopped = false;
+ let previousSample: TargetPresentationSample | undefined;
+
+ const verify = () => {
+ if (stopped) return;
+
+ const target = document.querySelector<HTMLElement>(targetSelector);
+ const scroller =
+ target?.closest<HTMLElement>(scrollSelector) ??
+ document.querySelector<HTMLElement>(scrollSelector);
+ if (scroller && target) {
+ const scrollRect = scroller.getBoundingClientRect();
+ const targetRect = target.getBoundingClientRect();
+ const insetStart = Number(
+ scroller.dataset.channelScrollInsetStart ?? 0
+ );
+ const insetEnd = Number(scroller.dataset.channelScrollInsetEnd ?? 0);
+ const usableTop = scrollRect.top + insetStart;
+ const usableBottom = scrollRect.bottom - insetEnd;
+ const usableViewportHeight = Math.max(0, usableBottom - usableTop);
+ const virtualItem = target.closest<HTMLElement>(
+ '[data-channel-thread-row]'
+ )?.parentElement;
+ const targetStyle = getComputedStyle(target);
+ const visible =
+ targetStyle.display !== 'none' &&
+ targetStyle.visibility !== 'hidden' &&
+ targetRect.bottom > usableTop &&
+ targetRect.top < usableBottom;
+ const positioned =
+ visible &&
+ (targetRect.height <= usableViewportHeight
+ ? targetRect.top >= usableTop - tolerancePx &&
+ targetRect.bottom <= usableBottom + tolerancePx
+ : targetRect.top <= usableTop + tolerancePx &&
+ targetRect.bottom >= usableBottom - tolerancePx);
+ const sample: TargetPresentationSample = {
+ time: performance.now(),
+ center:
+ targetRect.top +
+ targetRect.height / 2 -
+ (usableTop + usableViewportHeight / 2),
+ positioned,
+ visible,
+ scrollTop: scroller.scrollTop,
+ targetHeight: targetRect.height,
+ targetTop: targetRect.top,
+ virtualItemTop: virtualItem?.getBoundingClientRect().top,
+ virtualItemStyleTop: virtualItem?.style.top,
+ virtualItemVisibility: virtualItem?.style.visibility,
+ usableViewportHeight,
+ insetStart,
+ insetEnd,
+ };
+ report.first ??= sample;
+ report.last = sample;
+
+ if (!report.firstPositioned) {
+ if (sample.positioned) {
+ report.firstPositioned = sample;
+ report.lastChangeAt = sample.time;
+ } else if (sample.visible) {
+ report.unpositionedBeforeLandingCount += 1;
+ }
+ } else {
+ if (
+ !previousSample ||
+ Math.abs(sample.center - previousSample.center) > tolerancePx ||
+ sample.positioned !== previousSample.positioned
+ ) {
+ report.lastChangeAt = sample.time;
+ }
+ report.largestShiftAfterPositioned = Math.max(
+ report.largestShiftAfterPositioned,
+ Math.abs(sample.center - report.firstPositioned.center)
+ );
+ if (!sample.positioned) {
+ report.firstPositionLoss ??= sample;
+ report.positionLossCount += 1;
+ }
+ }
+ previousSample = sample;
+ }
+
+ schedulePostPaintCheck();
+ };
+
+ const schedulePostPaintCheck = () => {
+ requestAnimationFrame(() => window.setTimeout(verify, 0));
+ };
+
+ window.__e2eStopTargetPresentation = () => {
+ stopped = true;
+ };
+ window.__e2eResetTargetPresentation = () => {
+ report = createReport();
+ window.__e2eTargetPresentation = report;
+ previousSample = undefined;
+ };
+ schedulePostPaintCheck();
+ },
+ { scrollSelector, targetSelector, tolerancePx }
+ );
+
+ return {
+ reset: async () => {
+ await page.evaluate(() => window.__e2eResetTargetPresentation?.());
+ },
+ waitForFirstPositioned: async () => {
+ await page.waitForFunction(
+ () => window.__e2eTargetPresentation?.firstPositioned !== undefined,
+ undefined,
+ { timeout: 10_000 }
+ );
+ return page.evaluate(
+ () => window.__e2eTargetPresentation as TargetPresentationReport
+ );
+ },
+ waitForQuietAndRead: async (quietMs = 250) => {
+ await page.waitForFunction(
+ (quiet) => {
+ const report = window.__e2eTargetPresentation;
+ return (
+ report?.firstPositioned !== undefined &&
+ report.lastChangeAt !== undefined &&
+ performance.now() - report.lastChangeAt >= quiet
+ );
+ },
+ quietMs,
+ { timeout: 10_000 }
+ );
+ return page.evaluate(() => {
+ window.__e2eStopTargetPresentation?.();
+ return window.__e2eTargetPresentation as TargetPresentationReport;
+ });
+ },
+ };
+}
+
+/**
+ * Delay ResizeObserver callbacks for a DOM subtree to make layout races deterministic.
+ * When `activateWhenSelector` is set, callbacks remain native until that element exists.
+ */
export async function delayResizeObserverFor(
page: Page,
selector: string,
- delayMs: number
+ delayMs: number,
+ activateWhenSelector?: string
) {
await page.addInitScript(
- ({ selector, delayMs }) => {
+ ({ selector, delayMs, activateWhenSelector }) => {
const NativeResizeObserver = window.ResizeObserver;
const state: ResizeObserverDelayState = { matchedCallbacks: 0 };
window.__e2eResizeObserverDelay = state;
@@ -47,7 +242,10 @@ export async function delayResizeObserverFor(
({ target }) =>
target.matches(selector) || target.closest(selector) !== null
);
- if (!matchesSubtree) {
+ const isActivated =
+ !activateWhenSelector ||
+ document.querySelector(activateWhenSelector) !== null;
+ if (!matchesSubtree || !isActivated) {
callback(entries, this);
return;
}
@@ -90,7 +288,7 @@ export async function delayResizeObserverFor(
window.ResizeObserver = DelayedResizeObserver;
},
- { selector, delayMs }
+ { selector, delayMs, activateWhenSelector }
);
return {
@@ -119,8 +317,13 @@ export async function observeBottomPresentation(
) {
await page.addInitScript(
({ selector, tolerancePx }) => {
- const report: BottomPresentationReport = { violationCount: 0 };
- window.__e2eBottomPresentation = report;
+ let report: BottomPresentationReport;
+ const reset = () => {
+ report = { violationCount: 0 };
+ window.__e2eBottomPresentation = report;
+ };
+ window.__e2eResetBottomPresentation = reset;
+ reset();
const verify = () => {
const scroller = document.querySelector<HTMLElement>(selector);
@@ -163,6 +366,17 @@ export async function observeBottomPresentation(
);
return {
+ reset: () => page.evaluate(() => window.__e2eResetBottomPresentation?.()),
+ waitForSampleAndRead: async () => {
+ await page.waitForFunction(
+ () => window.__e2eBottomPresentation?.first !== undefined,
+ undefined,
+ { timeout: 30_000 }
+ );
+ return page.evaluate(
+ () => window.__e2eBottomPresentation as BottomPresentationReport
+ );
+ },
read: () =>
page.evaluate(
() => window.__e2eBottomPresentation as BottomPresentationReport
diff --git a/apps/web/tests/e2e/local-channel-actions.spec.ts b/apps/web/tests/e2e/local-channel-actions.spec.ts
index beb66607c5..e13d853eb6 100644
--- a/apps/web/tests/e2e/local-channel-actions.spec.ts
+++ b/apps/web/tests/e2e/local-channel-actions.spec.ts
@@ -50,7 +50,7 @@ test.describe('local channel actions', () => {
await openReplyInput(messageRow);
await expect(
- page.locator(`[data-inline-input-container-id="${message.message_id}"]`)
+ page.locator(`[data-input-id="thread-reply-input-${message.message_id}"]`)
).toContainText('Send a reply', { timeout: 10_000 });
});
});
diff --git a/apps/web/tests/e2e/local-channel-thread-navigation.spec.ts b/apps/web/tests/e2e/local-channel-thread-navigation.spec.ts
new file mode 100644
index 0000000000..539a255e21
--- /dev/null
+++ b/apps/web/tests/e2e/local-channel-thread-navigation.spec.ts
@@ -0,0 +1,481 @@
+import { expect, type Page, test } from '@playwright/test';
+
+import { localE2ESeed } from './fixtures/local-e2e-seed';
+import { gotoApp, LOCAL_E2E } from './helpers/local-app';
+import {
+ delayResizeObserverFor,
+ observeBottomPresentation,
+ observeTargetPresentation,
+} from './helpers/scroll-presentation';
+
+const CHANNEL_SCROLL_SELECTOR = '[data-channel-scroll]';
+const BOTTOM_TOLERANCE_PX = 1;
+const MAX_PRESENTED_TARGET_SHIFT_PX = 2;
+const LATEST_MESSAGE_TEXT = 'Scroll fixture message 5000';
+
+test.skip(!LOCAL_E2E, 'requires the seeded local E2E stack');
+test.use({ viewport: { width: 1920, height: 1080 } });
+
+type PresentationObserver = Awaited<
+ ReturnType<typeof observeTargetPresentation>
+>;
+type BottomPresentationObserver = Awaited<
+ ReturnType<typeof observeBottomPresentation>
+>;
+
+function targetSelector(messageId: string) {
+ return `[data-message-id="${messageId}"]`;
+}
+
+function channelScrollSelector(channelId: string) {
+ return `${CHANNEL_SCROLL_SELECTOR}[data-channel-id="${channelId}"]`;
+}
+
+function targetUrl(channelId: string, messageId: string, threadId?: string) {
+ const params = new URLSearchParams({ channel_message_id: messageId });
+ if (threadId) params.set('channel_thread_id', threadId);
+ return `/channel/${channelId}?${params}` as const;
+}
+
+async function expectTargetedMessage(
+ page: Page,
+ messageId: string,
+ text: string
+) {
+ const target = page.locator(targetSelector(messageId));
+ await expect(target).toContainText(text, { timeout: 30_000 });
+ await expect(target).toHaveAttribute('data-targeted', '');
+ return target;
+}
+
+async function expectStableLanding(presentation: PresentationObserver) {
+ const report = await presentation.waitForQuietAndRead();
+ expect(report.firstPositioned, JSON.stringify(report)).toBeDefined();
+ expect(report.unpositionedBeforeLandingCount, JSON.stringify(report)).toBe(0);
+ expect(report.last?.positioned, JSON.stringify(report)).toBe(true);
+ expect(report.positionLossCount, JSON.stringify(report)).toBe(0);
+ expect(
+ report.largestShiftAfterPositioned,
+ JSON.stringify(report)
+ ).toBeLessThanOrEqual(MAX_PRESENTED_TARGET_SHIFT_PX);
+ return report;
+}
+
+async function expectBottomLanding(
+ page: Page,
+ presentation: BottomPresentationObserver,
+ channelId: string
+) {
+ const scroller = page.locator(channelScrollSelector(channelId));
+ await expect(scroller).toBeVisible({ timeout: 30_000 });
+ await expect(
+ scroller.getByText(LATEST_MESSAGE_TEXT, { exact: true })
+ ).toBeInViewport({ timeout: 30_000 });
+
+ const report = await presentation.waitForSampleAndRead();
+ expect(report.first, JSON.stringify(report)).toBeDefined();
+ expect(
+ report.first?.distanceFromBottom,
+ JSON.stringify(report)
+ ).toBeLessThanOrEqual(BOTTOM_TOLERANCE_PX);
+ expect(report.firstViolation, JSON.stringify(report)).toBeUndefined();
+ expect(report.violationCount, JSON.stringify(report)).toBe(0);
+}
+
+async function openChannelFromCommandMenu(page: Page, channelName: string) {
+ const dialog = page.getByRole('dialog');
+ for (let attempt = 0; attempt < 3; attempt += 1) {
+ await page.keyboard.press('Meta+K');
+ if (
+ await dialog
+ .waitFor({ state: 'visible', timeout: 1_000 })
+ .then(() => true)
+ .catch(() => false)
+ ) {
+ break;
+ }
+ }
+ await expect(dialog).toBeVisible({ timeout: 10_000 });
+ await dialog.getByPlaceholder('Search...').fill(channelName);
+ const result = dialog.getByText(channelName, { exact: true }).last();
+ await expect(result).toBeVisible({ timeout: 30_000 });
+ await result.click();
+}
+
+async function replaceActiveSplitWithFiles(page: Page, channelId: string) {
+ await page.getByRole('button', { name: /Files/ }).click();
+ await expect(page.locator('[data-list-view="documents"]')).toBeVisible({
+ timeout: 30_000,
+ });
+ await expect(page.locator(channelScrollSelector(channelId))).toHaveCount(0);
+}
+
+async function clickChannelMention(
+ page: Page,
+ sourceMessageId: string,
+ targetChannelId: string
+) {
+ const sourceMessage = page.locator(targetSelector(sourceMessageId));
+ await expect(sourceMessage).toBeVisible({ timeout: 30_000 });
+ const mention = sourceMessage.locator(
+ `[data-document-mention="true"][data-document-id="${targetChannelId}"]`
+ );
+ await expect(mention).toBeVisible({ timeout: 30_000 });
+ await expect(mention).not.toHaveClass(/opacity-50/, { timeout: 30_000 });
+ await mention.click();
+}
+
+function countChannelMessageRequests(
+ page: Page,
+ channelId: string,
+ loadAroundMessageId: string | null
+) {
+ let count = 0;
+ page.on('request', (request) => {
+ const url = new URL(request.url());
+ if (
+ url.pathname.endsWith(`/channels/${channelId}/messages`) &&
+ url.searchParams.get('load_around_message_id') === loadAroundMessageId
+ ) {
+ count += 1;
+ }
+ });
+ return () => count;
+}
+
+test('opens a channel from the command menu at the bottom cold and warm', async ({
+ page,
+}) => {
+ const channel = localE2ESeed.smoke.generalChannel;
+ const channelName = channel.channel_name ?? 'general';
+ const otherChannel = localE2ESeed.smoke.genericMentionSourceChannel;
+ const latestRequests = countChannelMessageRequests(
+ page,
+ channel.channel_id,
+ null
+ );
+ const presentation = await observeBottomPresentation(
+ page,
+ channelScrollSelector(channel.channel_id),
+ BOTTOM_TOLERANCE_PX
+ );
+
+ await gotoApp(page, '/component/documents');
+ await expect(page.locator('[data-list-view="documents"]')).toBeVisible();
+ await openChannelFromCommandMenu(page, channelName);
+ await expectBottomLanding(page, presentation, channel.channel_id);
+ expect(latestRequests()).toBeGreaterThan(0);
+ const coldRequestCount = latestRequests();
+
+ await openChannelFromCommandMenu(
+ page,
+ otherChannel.channel_name ?? 'announcements'
+ );
+ await presentation.reset();
+ await openChannelFromCommandMenu(page, channelName);
+ await expectBottomLanding(page, presentation, channel.channel_id);
+ expect(latestRequests()).toBe(coldRequestCount);
+});
+
+test('opens a generic channel mention at the bottom cold and warm', async ({
+ page,
+}) => {
+ const target = localE2ESeed.smoke.generalChannel;
+ const source = localE2ESeed.smoke.genericMentionSourceChannel;
+ const sourceName = source.channel_name ?? 'announcements';
+ const latestRequests = countChannelMessageRequests(
+ page,
+ target.channel_id,
+ null
+ );
+ const presentation = await observeBottomPresentation(
+ page,
+ channelScrollSelector(target.channel_id),
+ BOTTOM_TOLERANCE_PX
+ );
+
+ await gotoApp(page, '/component/documents');
+ await expect(page.locator('[data-list-view="documents"]')).toBeVisible();
+ await openChannelFromCommandMenu(page, sourceName);
+ await presentation.reset();
+ await clickChannelMention(
+ page,
+ localE2ESeed.smoke.genericMentionSourceMessageId,
+ target.channel_id
+ );
+ await expectBottomLanding(page, presentation, target.channel_id);
+ expect(latestRequests()).toBeGreaterThan(0);
+ const coldRequestCount = latestRequests();
+
+ await replaceActiveSplitWithFiles(page, target.channel_id);
+ await presentation.reset();
+ await clickChannelMention(
+ page,
+ localE2ESeed.smoke.genericMentionSourceMessageId,
+ target.channel_id
+ );
+ await expectBottomLanding(page, presentation, target.channel_id);
+ expect(latestRequests()).toBe(coldRequestCount);
+});
+
+async function openChannelAtLatest(page: Page) {
+ const channel = localE2ESeed.smoke.generalChannel;
+ const launcherId = localE2ESeed.smoke.generalNavigationLauncherMessageId;
+ await gotoApp(page, `/channel/${channel.channel_id}`);
+ await expect(page.locator(CHANNEL_SCROLL_SELECTOR)).toBeVisible({
+ timeout: 30_000,
+ });
+ const launcher = page.locator(targetSelector(launcherId));
+ await expect(launcher).toBeVisible({ timeout: 30_000 });
+ const mentions = launcher.locator('[data-document-mention="true"]');
+ await expect(mentions).toHaveCount(2);
+ await expect(mentions.nth(0)).not.toHaveClass(/opacity-50/, {
+ timeout: 30_000,
+ });
+ await expect(mentions.nth(1)).not.toHaveClass(/opacity-50/, {
+ timeout: 30_000,
+ });
+ return mentions;
+}
+
+test('lands on a deeply nested reply after the thread expands and measures', async ({
+ page,
+}) => {
+ const channel = localE2ESeed.smoke.generalChannel;
+ const thread = localE2ESeed.smoke.generalDeepThread;
+ const selector = targetSelector(thread.targetReplyId);
+ const resizeDelay = await delayResizeObserverFor(
+ page,
+ CHANNEL_SCROLL_SELECTOR,
+ 150,
+ selector
+ );
+ const presentation = await observeTargetPresentation(
+ page,
+ channelScrollSelector(channel.channel_id),
+ selector
+ );
+
+ await gotoApp(
+ page,
+ targetUrl(channel.channel_id, thread.targetReplyId, thread.parentMessageId)
+ );
+ await expectTargetedMessage(
+ page,
+ thread.targetReplyId,
+ thread.targetReplyText
+ );
+
+ const resizeFault = await resizeDelay.waitForRelease();
+ expect(resizeFault?.matchedCallbacks).toBeGreaterThan(0);
+ await expectStableLanding(presentation);
+});
+
+test('opens a targeted channel mention on its deeply nested reply', async ({
+ page,
+}) => {
+ const channel = localE2ESeed.smoke.generalChannel;
+ const thread = localE2ESeed.smoke.generalDeepThread;
+ const source = localE2ESeed.smoke.targetedMentionSourceChannel;
+ const aroundRequests = countChannelMessageRequests(
+ page,
+ channel.channel_id,
+ thread.parentMessageId
+ );
+ const presentation = await observeTargetPresentation(
+ page,
+ channelScrollSelector(channel.channel_id),
+ targetSelector(thread.targetReplyId)
+ );
+
+ await gotoApp(page, '/component/documents');
+ await openChannelFromCommandMenu(page, source.channel_name ?? 'random');
+ await clickChannelMention(
+ page,
+ localE2ESeed.smoke.targetedMentionSourceMessageId,
+ channel.channel_id
+ );
+
+ await expectTargetedMessage(
+ page,
+ thread.targetReplyId,
+ thread.targetReplyText
+ );
+ await expectStableLanding(presentation);
+ expect(aroundRequests()).toBeGreaterThan(0);
+});
+
+test('the latest target wins while an earlier reply request is still loading', async ({
+ page,
+}) => {
+ const channel = localE2ESeed.smoke.generalChannel;
+ const staleThread = localE2ESeed.smoke.generalAlternateDeepThread;
+ const finalThread = localE2ESeed.smoke.generalDeepThread;
+ const staleRepliesPath = `/channels/${channel.channel_id}/messages/${staleThread.parentMessageId}/replies`;
+ let releaseStaleReplies = () => {};
+ const holdStaleReplies = new Promise<void>((resolve) => {
+ releaseStaleReplies = resolve;
+ });
+ await page.route(`**${staleRepliesPath}*`, async (route) => {
+ await holdStaleReplies;
+ await route.continue();
+ });
+ const presentation = await observeTargetPresentation(
+ page,
+ channelScrollSelector(channel.channel_id),
+ targetSelector(finalThread.targetReplyId)
+ );
+ const mentions = await openChannelAtLatest(page);
+ const splitPanels = page.locator('[data-split-id]');
+ const splitCount = await splitPanels.count();
+ const staleRequest = page.waitForRequest((request) =>
+ new URL(request.url()).pathname.endsWith(staleRepliesPath)
+ );
+ await mentions.nth(0).click({ modifiers: ['Shift'] });
+ await staleRequest;
+
+ // The stale thread's root is mounted before its delayed replies resolve. Its
+ // real channel mention remains interactive while that request is in flight.
+ const staleParent = page.locator(targetSelector(staleThread.parentMessageId));
+ const finalMention = staleParent.locator('[data-document-mention="true"]');
+ await expect(finalMention).toBeVisible();
+ await finalMention.click({ modifiers: ['Shift'] });
+ releaseStaleReplies();
+ await expect(splitPanels).toHaveCount(splitCount);
+
+ await expectTargetedMessage(
+ page,
+ finalThread.targetReplyId,
+ finalThread.targetReplyText
+ );
+ await expect(
+ page.locator(`${targetSelector(staleThread.targetReplyId)}[data-targeted]`)
+ ).toHaveCount(0);
+ await expectStableLanding(presentation);
+});
+
+test('loads and lands on a top-level target outside the initial message window', async ({
+ page,
+}) => {
+ const channel = localE2ESeed.smoke.generalChannel;
+ const thread = localE2ESeed.smoke.generalDeepThread;
+ const presentation = await observeTargetPresentation(
+ page,
+ channelScrollSelector(channel.channel_id),
+ targetSelector(thread.parentMessageId)
+ );
+
+ await gotoApp(page, targetUrl(channel.channel_id, thread.parentMessageId));
+ await expectTargetedMessage(
+ page,
+ thread.parentMessageId,
+ 'Deep thread navigation fixture parent'
+ );
+ await expectStableLanding(presentation);
+});
+
+test('opens an unread channel notification on its specific cached reply', async ({
+ page,
+}) => {
+ const channel = localE2ESeed.smoke.generalChannel;
+ const navigation = localE2ESeed.smoke.unreadMessageNavigation;
+ const source = localE2ESeed.smoke.unreadMentionSourceChannel;
+ const aroundRequests = countChannelMessageRequests(
+ page,
+ channel.channel_id,
+ navigation.parentMessageId
+ );
+ const presentation = await observeTargetPresentation(
+ page,
+ channelScrollSelector(channel.channel_id),
+ targetSelector(navigation.targetReplyId)
+ );
+ // Warming this thread mounts the notified reply, which normally marks the
+ // notification seen. Force the real mutation rollback path so the sidebar
+ // entry remains available for the interaction under test and for repeats.
+ await page.route(
+ '**/notification/user_notifications/bulk/seen',
+ async (route) => {
+ await route.fulfill({
+ status: 500,
+ contentType: 'application/json',
+ body: JSON.stringify({ error: 'preserve seeded unread fixture' }),
+ });
+ }
+ );
+
+ await gotoApp(page, '/component/documents');
+ await openChannelFromCommandMenu(
+ page,
+ source.channel_name ?? navigation.sourceChannelName
+ );
+ await clickChannelMention(
+ page,
+ navigation.sourceMessageId,
+ channel.channel_id
+ );
+ await expectTargetedMessage(
+ page,
+ navigation.cacheWarmerReplyId,
+ navigation.cacheWarmerReplyText
+ );
+ expect(aroundRequests()).toBeGreaterThan(0);
+ const coldRequestCount = aroundRequests();
+
+ const unreadSection = page.locator('section').filter({
+ has: page.getByRole('button', { name: 'Unread', exact: true }),
+ });
+ const unreadChannel = unreadSection.getByRole('button', {
+ name: /general/,
+ });
+ await expect(unreadChannel).toBeVisible({ timeout: 30_000 });
+ await presentation.reset();
+ await unreadChannel.click();
+ await expectTargetedMessage(
+ page,
+ navigation.targetReplyId,
+ navigation.targetReplyText
+ );
+ const report = await expectStableLanding(presentation);
+ expect(report.last?.targetHeight).toBeGreaterThan(
+ report.last?.usableViewportHeight ?? Number.POSITIVE_INFINITY
+ );
+ expect(aroundRequests()).toBe(coldRequestCount);
+});
+
+test.describe('mobile channel viewport', () => {
+ test.use({
+ viewport: { width: 390, height: 844 },
+ hasTouch: true,
+ isMobile: true,
+ });
+
+ test('lands inside the viewport between floating channel chrome', async ({
+ page,
+ }) => {
+ const channel = localE2ESeed.smoke.generalChannel;
+ const thread = localE2ESeed.smoke.generalDeepThread;
+ const presentation = await observeTargetPresentation(
+ page,
+ channelScrollSelector(channel.channel_id),
+ targetSelector(thread.targetReplyId)
+ );
+
+ await gotoApp(
+ page,
+ targetUrl(
+ channel.channel_id,
+ thread.targetReplyId,
+ thread.parentMessageId
+ )
+ );
+ await expectTargetedMessage(
+ page,
+ thread.targetReplyId,
+ thread.targetReplyText
+ );
+ const report = await expectStableLanding(presentation);
+ expect(report.last?.insetStart).toBeGreaterThan(0);
+ expect(report.last?.insetEnd).toBeGreaterThan(0);
+ });
+});
diff --git a/tooling/seed_cli/seed/local_e2e/channel_messages.sql b/tooling/seed_cli/seed/local_e2e/channel_messages.sql
index d99677253e..3c75af4cf5 100644
--- a/tooling/seed_cli/seed/local_e2e/channel_messages.sql
+++ b/tooling/seed_cli/seed/local_e2e/channel_messages.sql
@@ -24,3 +24,308 @@ SELECT
now() + (message_number || ' milliseconds')::interval
FROM local_e2e_channels AS channel
CROSS JOIN generate_series(1, 5000) AS message_number;
+
+INSERT INTO comms_messages (
+ id,
+ channel_id,
+ sender_id,
+ content,
+ created_at,
+ updated_at
+)
+VALUES (
+ '00000000-0000-0000-0003-000000000001'::uuid,
+ '00000000-0000-0000-0000-000000000001'::uuid,
+ 'Deep thread navigation fixture parent',
+ now() - interval '1 day',
+ now() - interval '1 day'
+);
+
+WITH deep_thread_replies AS (
+ SELECT
+ reply_number,
+ (
+ '00000000-0000-0000-0003-'
+ || lpad((reply_number + 1)::text, 12, '0')
+ )::uuid AS id,
+ CASE
+ WHEN reply_number = 5 THEN 'Deep thread target reply'
+ WHEN reply_number = 6 THEN (
+ SELECT 'Oversized target reply' || E'\n\n' || string_agg(
+ format(
+ 'Oversized target paragraph %s. This single reply is intentionally taller than the channel viewport.',
+ paragraph_number
+ ),
+ E'\n\n' ORDER BY paragraph_number
+ )
+ FROM generate_series(1, 80) AS paragraph(paragraph_number)
+ )
+ ELSE (
+ SELECT string_agg(
+ format(
+ 'Tall thread reply %s, paragraph %s. This fixture deliberately occupies enough vertical space to expose reply navigation that races the outer virtualizer measurement.',
+ reply_number,
+ paragraph_number
+ ),
+ E'\n\n' ORDER BY paragraph_number
+ )
+ FROM generate_series(1, 24) AS paragraph(paragraph_number)
+ )
+ END AS content
+ FROM generate_series(1, 6) AS reply(reply_number)
+)
+INSERT INTO comms_messages (
+ id,
+ channel_id,
+ sender_id,
+ content,
+ thread_id,
+ created_at,
+ updated_at
+)
+SELECT
+ id,
+ '00000000-0000-0000-0000-000000000001'::uuid,
+ CASE
+ WHEN reply_number % 2 = 0 THEN 'macro|[email protected]'
+ ELSE 'macro|[email protected]'
+ END,
+ content,
+ '00000000-0000-0000-0003-000000000001'::uuid,
+ now() - interval '1 day' + (reply_number || ' seconds')::interval,
+ now() - interval '1 day' + (reply_number || ' seconds')::interval
+FROM deep_thread_replies;
+
+INSERT INTO comms_messages (
+ id,
+ channel_id,
+ sender_id,
+ content,
+ created_at,
+ updated_at
+)
+VALUES (
+ '00000000-0000-0000-0003-000000000010'::uuid,
+ '00000000-0000-0000-0000-000000000001'::uuid,
+ 'Alternate deep thread navigation fixture parent. Navigate elsewhere: <m-document-mention>{"documentId":"00000000-0000-0000-0000-000000000001","blockName":"channel","documentName":"general","blockParams":{"channel_message_id":"00000000-0000-0000-0003-000000000006","channel_thread_id":"00000000-0000-0000-0003-000000000001"},"collapsed":false}</m-document-mention>',
+ now() - interval '2 days',
+ now() - interval '2 days'
+);
+
+WITH alternate_thread_replies AS (
+ SELECT
+ reply_number,
+ (
+ '00000000-0000-0000-0003-'
+ || lpad((reply_number + 10)::text, 12, '0')
+ )::uuid AS id,
+ CASE
+ WHEN reply_number = 4 THEN 'Alternate deep thread target reply'
+ ELSE (
+ SELECT string_agg(
+ format(
+ 'Alternate tall reply %s, paragraph %s. This fixture keeps a stale reply request in flight while navigation moves elsewhere.',
+ reply_number,
+ paragraph_number
+ ),
+ E'\n\n' ORDER BY paragraph_number
+ )
+ FROM generate_series(1, 24) AS paragraph(paragraph_number)
+ )
+ END AS content
+ FROM generate_series(1, 4) AS reply(reply_number)
+)
+INSERT INTO comms_messages (
+ id,
+ channel_id,
+ sender_id,
+ content,
+ thread_id,
+ created_at,
+ updated_at
+)
+SELECT
+ id,
+ '00000000-0000-0000-0000-000000000001'::uuid,
+ CASE
+ WHEN reply_number % 2 = 0 THEN 'macro|[email protected]'
+ ELSE 'macro|[email protected]'
+ END,
+ content,
+ '00000000-0000-0000-0003-000000000010'::uuid,
+ now() - interval '2 days' + (reply_number || ' seconds')::interval,
+ now() - interval '2 days' + (reply_number || ' seconds')::interval
+FROM alternate_thread_replies;
+
+INSERT INTO comms_messages (
+ id,
+ channel_id,
+ sender_id,
+ content,
+ created_at,
+ updated_at
+)
+VALUES (
+ '00000000-0000-0000-0003-000000000040'::uuid,
+ '00000000-0000-0000-0000-000000000001'::uuid,
+ 'Unread navigation fixture parent',
+ now() - interval '3 days',
+ now() - interval '3 days'
+);
+
+WITH unread_thread_replies AS (
+ SELECT
+ reply_number,
+ (
+ '00000000-0000-0000-0003-'
+ || lpad((reply_number + 40)::text, 12, '0')
+ )::uuid AS id,
+ CASE
+ WHEN reply_number = 4 THEN (
+ SELECT 'Unread cache warmer reply' || E'\n\n' || string_agg(
+ format(
+ 'Unread cache warmer paragraph %s. This reply keeps the notification target outside the viewport before navigation.',
+ paragraph_number
+ ),
+ E'\n\n' ORDER BY paragraph_number
+ )
+ FROM generate_series(1, 80) AS paragraph(paragraph_number)
+ )
+ WHEN reply_number = 5 THEN (
+ SELECT 'Unread oversized target reply' || E'\n\n' || string_agg(
+ format(
+ 'Unread oversized target paragraph %s. This reply must cover more than one channel viewport.',
+ paragraph_number
+ ),
+ E'\n\n' ORDER BY paragraph_number
+ )
+ FROM generate_series(1, 80) AS paragraph(paragraph_number)
+ )
+ ELSE (
+ SELECT string_agg(
+ format(
+ 'Unread tall reply %s, paragraph %s. This fixture spaces the target well beyond the thread root.',
+ reply_number,
+ paragraph_number
+ ),
+ E'\n\n' ORDER BY paragraph_number
+ )
+ FROM generate_series(1, 24) AS paragraph(paragraph_number)
+ )
+ END AS content
+ FROM generate_series(1, 5) AS reply(reply_number)
+)
+INSERT INTO comms_messages (
+ id,
+ channel_id,
+ sender_id,
+ content,
+ thread_id,
+ created_at,
+ updated_at
+)
+SELECT
+ id,
+ '00000000-0000-0000-0000-000000000001'::uuid,
+ CASE
+ WHEN reply_number % 2 = 0 THEN 'macro|[email protected]'
+ ELSE 'macro|[email protected]'
+ END,
+ content,
+ '00000000-0000-0000-0003-000000000040'::uuid,
+ now() - interval '3 days' + (reply_number || ' seconds')::interval,
+ now() - interval '3 days' + (reply_number || ' seconds')::interval
+FROM unread_thread_replies;
+
+INSERT INTO comms_messages (
+ id,
+ channel_id,
+ sender_id,
+ content,
+ created_at,
+ updated_at
+)
+VALUES (
+ '00000000-0000-0000-0003-000000000020'::uuid,
+ '00000000-0000-0000-0000-000000000001'::uuid,
+ 'Navigation race A: <m-document-mention>{"documentId":"00000000-0000-0000-0000-000000000001","blockName":"channel","documentName":"general","blockParams":{"channel_message_id":"00000000-0000-0000-0003-000000000014","channel_thread_id":"00000000-0000-0000-0003-000000000010"},"collapsed":false}</m-document-mention> Navigation target B: <m-document-mention>{"documentId":"00000000-0000-0000-0000-000000000001","blockName":"channel","documentName":"general","blockParams":{"channel_message_id":"00000000-0000-0000-0003-000000000006","channel_thread_id":"00000000-0000-0000-0003-000000000001"},"collapsed":false}</m-document-mention>',
+ now() + interval '2 hours',
+ now() + interval '2 hours'
+);
+
+INSERT INTO comms_messages (
+ id,
+ channel_id,
+ sender_id,
+ content,
+ created_at,
+ updated_at
+)
+VALUES
+(
+ '00000000-0000-0000-0003-000000000030'::uuid,
+ '00000000-0000-0000-0000-000000000002'::uuid,
+ 'Open general at its latest message: <m-document-mention>{"documentId":"00000000-0000-0000-0000-000000000001","blockName":"channel","documentName":"general","blockParams":{},"collapsed":false}</m-document-mention>',
+ now() + interval '3 hours',
+ now() + interval '3 hours'
+),
+(
+ '00000000-0000-0000-0003-000000000031'::uuid,
+ '00000000-0000-0000-0000-000000000003'::uuid,
+ 'Open a specific reply in general: <m-document-mention>{"documentId":"00000000-0000-0000-0000-000000000001","blockName":"channel","documentName":"general","blockParams":{"channel_message_id":"00000000-0000-0000-0003-000000000006","channel_thread_id":"00000000-0000-0000-0003-000000000001"},"collapsed":false}</m-document-mention>',
+ now() + interval '3 hours',
+ now() + interval '3 hours'
+),
+(
+ '00000000-0000-0000-0003-000000000032'::uuid,
+ '00000000-0000-0000-0000-000000000003'::uuid,
+ 'Warm the unread target in general: <m-document-mention>{"documentId":"00000000-0000-0000-0000-000000000001","blockName":"channel","documentName":"general","blockParams":{"channel_message_id":"00000000-0000-0000-0003-000000000044","channel_thread_id":"00000000-0000-0000-0003-000000000040"},"collapsed":false}</m-document-mention>',
+ now() + interval '3 hours 1 minute',
+ now() + interval '3 hours 1 minute'
+);
+
+INSERT INTO notification (
+ id,
+ notification_event_type,
+ event_item_id,
+ event_item_type,
+ service_sender,
+ metadata,
+ sender_id,
+ created_at
+)
+VALUES (
+ '00000000-0000-0000-0004-000000000001'::uuid,
+ 'channel_mention',
+ '00000000-0000-0000-0000-000000000001',
+ 'channel',
+ 'local-e2e',
+ jsonb_build_object(
+ 'channelName', 'general',
+ 'channelType', 'public',
+ 'messageContent', 'Unread oversized target reply',
+ 'messageId', '00000000-0000-0000-0003-000000000045',
+ 'threadId', '00000000-0000-0000-0003-000000000040',
+ 'senderDisplayName', 'Bob'
+ ),
+ now() + interval '4 hours'
+);
+
+INSERT INTO user_notification (
+ user_id,
+ notification_id,
+ created_at
+)
+VALUES (
+ '00000000-0000-0000-0004-000000000001'::uuid,
+ now() + interval '4 hours'
+);
diff --git a/tooling/seed_cli/seed/local_e2e/manifest.json b/tooling/seed_cli/seed/local_e2e/manifest.json
index 01ce6c6f1d..014395da06 100644
--- a/tooling/seed_cli/seed/local_e2e/manifest.json
+++ b/tooling/seed_cli/seed/local_e2e/manifest.json
@@ -12,7 +12,44 @@
"general": {
"id": "00000000-0000-0000-0000-000000000001",
"name": "general",
- "message": "Welcome to the general channel everyone!"
+ "message": "Welcome to the general channel everyone!",
+ "navigationLauncherMessageId": "00000000-0000-0000-0003-000000000020",
+ "deepThread": {
+ "parentMessageId": "00000000-0000-0000-0003-000000000001",
+ "firstReplyId": "00000000-0000-0000-0003-000000000002",
+ "targetReplyId": "00000000-0000-0000-0003-000000000006",
+ "targetReplyText": "Deep thread target reply",
+ "oversizedReplyId": "00000000-0000-0000-0003-000000000007",
+ "oversizedReplyText": "Oversized target reply"
+ },
+ "alternateDeepThread": {
+ "parentMessageId": "00000000-0000-0000-0003-000000000010",
+ "targetReplyId": "00000000-0000-0000-0003-000000000014",
+ "targetReplyText": "Alternate deep thread target reply"
+ }
}
+ },
+ "navigation": {
+ "genericChannelMention": {
+ "sourceChannelId": "00000000-0000-0000-0000-000000000002",
+ "sourceChannelName": "announcements",
+ "sourceMessageId": "00000000-0000-0000-0003-000000000030"
+ },
+ "targetedMessageMention": {
+ "sourceChannelId": "00000000-0000-0000-0000-000000000003",
+ "sourceChannelName": "random",
+ "sourceMessageId": "00000000-0000-0000-0003-000000000031"
+ },
+ "unreadMessageNavigation": {
+ "sourceChannelId": "00000000-0000-0000-0000-000000000003",
+ "sourceChannelName": "random",
+ "sourceMessageId": "00000000-0000-0000-0003-000000000032",
+ "parentMessageId": "00000000-0000-0000-0003-000000000040",
+ "cacheWarmerReplyId": "00000000-0000-0000-0003-000000000044",
+ "cacheWarmerReplyText": "Unread cache warmer reply",
+ "targetReplyId": "00000000-0000-0000-0003-000000000045",
+ "targetReplyText": "Unread oversized target reply"
+ },
+ "unreadNotificationId": "00000000-0000-0000-0004-000000000001"
}
}
diff --git a/tooling/seed_cli/seed/local_e2e/reset.sql b/tooling/seed_cli/seed/local_e2e/reset.sql
index 90bb4309b3..ed66179fa5 100644
--- a/tooling/seed_cli/seed/local_e2e/reset.sql
+++ b/tooling/seed_cli/seed/local_e2e/reset.sql
@@ -1,3 +1,6 @@
+DELETE FROM notification
+WHERE id::text LIKE '00000000-0000-0000-0004-%';
+
DELETE FROM entity_access
WHERE source_id LIKE '00000000-0000-0000-0000-00000000000%'
OR entity_id::text LIKE '00000000-0000-0000-0002-%';