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.

feat(channels): migrate to tanstack virtual (#6226)

teof60bbcdaf7ff
diff --git a/apps/web/package.json b/apps/web/package.json
index db66e7e71f..a6872735c3 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -92,7 +92,7 @@
"@tailwindcss/vite": "^4.2.4",
"@tanstack/pacer": "^0.17.3",
"@tanstack/solid-query": "5.90.3",
- "@tanstack/solid-virtual": "^3.13.13",
+ "@tanstack/solid-virtual": "3.13.37",
"@tauri-apps/api": "^2.8.0",
"@tauri-apps/plugin-haptics": "~2",
"@tauri-apps/plugin-http": "~2.5.8",
diff --git a/apps/web/src/features/channel/Channel/Channel.tsx b/apps/web/src/features/channel/Channel/Channel.tsx
index f8f170a179..1f3f3dd692 100644
--- a/apps/web/src/features/channel/Channel/Channel.tsx
+++ b/apps/web/src/features/channel/Channel/Channel.tsx
@@ -73,7 +73,6 @@ import { queryClient } from '@queries/client';
import { ChannelTypeEnum } from '@service-storage/client';
import { useBeforeLeave } from '@solidjs/router';
import {
- type Accessor,
createEffect,
createMemo,
createSignal,
@@ -111,14 +110,11 @@ import {
} from './create-target-message-controller';
import { buildChannelMessageListMeta } from './message-list-meta';
import { ScrollToBottomOverlay } from './ScrollToBottomOverlay';
-import { createStickyScrollEffect } from './sticky-scroll';
import {
- defaultThreadListTargetFromMessage,
ThreadList,
type ThreadListNavigation,
type ThreadListScrollSnapshot,
type ThreadListScrollState,
- type ThreadListScrollTarget,
} from './ThreadList';
import {
createThreadManager,
@@ -199,8 +195,7 @@ export function Channel(props: ChannelProps) {
initialTargetMessageReplyId: props.targetMessageReplyId,
// changing the array reference is required to trigger the scroll effect
messageKeys: () => [...messageIndex.keys],
- navigation: threadListNavigation,
- didInitialScroll: () => threadListScrollState()?.didInitialScroll ?? false,
+ isReady: () => !!threadListNavigation(),
});
const [channelInputSnapshot, setChannelInputSnapshot] =
@@ -250,15 +245,6 @@ export function Channel(props: ChannelProps) {
const messages = createMemo(() => [...messageIndex.items]);
const messageById = () => messageIndex.byId;
- const keepMountedTargetThreadIndexes = createMemo(() => {
- const threadId = targetMessageController.activeTargetMessageId();
- if (!threadId || !targetMessageController.hasPendingElementScroll())
- return [];
-
- const index = messageIndex.keys.indexOf(threadId);
- return index === -1 ? [] : [index];
- });
-
const participants = useChannelParticipants(() => props.channelId);
const channelBotMentionUsers = useChannelBotMentionUsers(
() => props.channelId
@@ -330,13 +316,6 @@ export function Channel(props: ChannelProps) {
},
});
- const threadListInitialScrollTarget: Accessor<ThreadListScrollTarget> = () =>
- defaultThreadListTargetFromMessage(
- targetMessageController.activeTargetMessageId()
- );
-
- const shift = () => threadPaginator.isShifting();
-
const activityTracker = createActivityTracker({
lastViewedAt: () => activity()?.viewed_at,
userId,
@@ -505,6 +484,7 @@ export function Channel(props: ChannelProps) {
};
const goToMessage: ChannelHandle['goToMessage'] = (messageId, replyId) => {
+ cancelLatestNavigation();
if (replyId) {
clearSelection();
prepareTargetReply(messageId);
@@ -543,52 +523,73 @@ export function Channel(props: ChannelProps) {
isMessageLoaded: (id) => messageIndex.keys.includes(id),
});
- const handleScrollToBottom = () => {
- if (messagesQuery.hasPreviousPage) {
- targetMessageController.reset();
- const defaultKey = getChannelMessagesQueryKey(props.channelId, null);
- queryClient.resetQueries({ queryKey: defaultKey });
- } else {
- threadListNavigation()?.scrollToBottom('end');
- }
+ // A latest request waits for both the query and the rendered list. Keeping
+ // its identity prevents a late response from overriding newer navigation.
+ let pendingLatest: { phase: 'loading' | 'waiting-for-layout' } | undefined;
+ const cancelLatestNavigation = () => {
+ pendingLatest = undefined;
};
+ onCleanup(cancelLatestNavigation);
- const [pendingScrollToLatest, setPendingScrollToLatest] = createSignal(false);
-
- const goToLatest: ChannelHandle['goToLatest'] = () => {
- handleScrollToBottom();
- setPendingScrollToLatest(true);
+ const finishLatestNavigation = () => {
+ if (
+ pendingLatest?.phase !== 'waiting-for-layout' ||
+ messagesQuery.isPending ||
+ messagesQuery.hasPreviousPage
+ )
+ return;
+ // Retained data is usable after a pagination error. Wait only if the query
+ // has no data yet or the message index still contains the old page.
+ const latestMessageId = messagesQuery.data?.pages.find(
+ (page) => page.items.length > 0
+ )?.items[0]?.id;
+ if (
+ latestMessageId !== undefined &&
+ messageIndex.keys.at(-1) === latestMessageId &&
+ threadListNavigation()?.scrollToLatest()
+ )
+ cancelLatestNavigation();
};
- // When handleScrollToBottom resets a mid-history slice, the newest page
- // arrives asynchronously and swaps the message set, so a single scroll can
- // settle mid-list. Keep scrolling until the viewport rests at the bottom of
- // fully loaded data.
- createEffect(() => {
- if (!pendingScrollToLatest()) return;
- // A specific message navigation supersedes scroll-to-latest: once a target
- // scroll is pending, abandon the latest-scroll so it can't yank the view
- // back to the bottom.
- if (targetMessageController.pendingScrollTargetId()) {
- setPendingScrollToLatest(false);
- return;
- }
- const navigation = threadListNavigation();
- const scrollState = threadListScrollState();
- if (!navigation || !scrollState?.didInitialScroll) return;
- if (messageIndex.keys.length === 0) return;
- if (messagesQuery.isFetching || messagesQuery.hasPreviousPage) return;
- if (scrollState.isNearBottom) {
- setPendingScrollToLatest(false);
- return;
+ const goToLatest: ChannelHandle['goToLatest'] = async () => {
+ const request: NonNullable<typeof pendingLatest> = { phase: 'loading' };
+ pendingLatest = request;
+ try {
+ const needsLatestPage =
+ messagesQuery.hasPreviousPage ||
+ !!targetMessageController.loadAroundMessageId();
+ targetMessageController.reset();
+ if (needsLatestPage) {
+ await queryClient.resetQueries(
+ { queryKey: getChannelMessagesQueryKey(props.channelId, null) },
+ { throwOnError: true }
+ );
+ }
+ if (pendingLatest !== request) return;
+ request.phase = 'waiting-for-layout';
+ finishLatestNavigation();
+ } catch {
+ // The query presents the error; the failed request must not scroll later.
+ if (pendingLatest === request) cancelLatestNavigation();
}
- navigation.scrollToBottom('end');
- });
+ };
+
+ const onThreadListScroll = (
+ state: ThreadListScrollState,
+ snapshot: ThreadListScrollSnapshot | undefined
+ ) => {
+ setThreadListScrollState(state);
+ if (snapshot) setThreadListScrollSnapshot(snapshot);
+ finishLatestNavigation();
+ };
const { messageListScopeId, attachMessageListRef, attachInputRef } =
createChannelHotkeys({
selection,
- navigation: threadListNavigation,
+ scrollToMessage: (id, options) => {
+ cancelLatestNavigation();
+ return threadListNavigation()?.scrollToMessage(id, options) ?? false;
+ },
messageById,
getMessageActions,
userId,
@@ -596,18 +597,11 @@ export function Channel(props: ChannelProps) {
isInputEmpty: () =>
(channelInputSnapshot()?.value.trim().length ?? 0) === 0,
onOpenFindBar: findBar.open,
- onGoToBottom: handleScrollToBottom,
+ onGoToBottom: goToLatest,
});
- createStickyScrollEffect({
- isNearBottom: () => threadListScrollState()?.isNearBottom ?? false,
- hasMoreBelow: () => threadPaginator.hasMorePrepend(),
- messages,
- scrollToBottom: () => threadListNavigation()?.scrollToBottom(),
- });
-
createChannelKeyboardHandler({
- navigation: threadListNavigation,
+ scrollToLatest: () => threadListNavigation()?.scrollToLatest(),
isNearBottom: () => threadListScrollState()?.isNearBottom ?? false,
// The unified input's current binding — the edited message (the edit
// face covers the reply face), else the reply target.
@@ -692,24 +686,24 @@ export function Channel(props: ChannelProps) {
);
};
- const isChannelReady = () => {
- return (
- messagesQuery.isFetched &&
- threadListNavigation() &&
- threadListScrollState()?.didInitialScroll
- );
+ const onThreadListReady = (navigation: ThreadListNavigation) => {
+ setThreadListNavigation(navigation);
+ finishLatestNavigation();
+ return () =>
+ setThreadListNavigation((current) =>
+ current === navigation ? undefined : current
+ );
};
- createEffect(
- on(isChannelReady, () => {
- if (props.onHandleReady)
- props.onHandleReady({
- goToMessage,
- goToLatest,
- getMessagesStateSnapshot,
- });
- })
- );
+ // Channel commands can queue before rows exist. Publish them on mount so
+ // empty channels also support navigation and saving their input/thread state.
+ onMount(() => {
+ props.onHandleReady?.({
+ goToMessage,
+ goToLatest,
+ getMessagesStateSnapshot,
+ });
+ });
return (
<EntityLoadGate
@@ -750,24 +744,33 @@ export function Channel(props: ChannelProps) {
triggerBehavior="spring-back"
>
<ThreadList
- channelId={props.channelId}
keys={() => messageIndex.keys}
- initialScrollTarget={threadListInitialScrollTarget()}
- initialScrollHandledByTargetElement={targetMessageController.hasPendingElementScroll()}
- keepMounted={keepMountedTargetThreadIndexes}
- fullFrameScrollInsets={threadListScrollInsets}
- shift={shift}
- prepend={threadPaginator.isPrepending}
+ targetId={
+ targetMessageController.hasPendingElementScroll()
+ ? targetMessageController.activeTargetMessageId()
+ : undefined
+ }
+ insets={threadListScrollInsets()}
+ followOnAppend={!messagesQuery.hasPreviousPage}
onScrollNearTop={threadPaginator.shiftPaginate}
onScrollNearBottom={threadPaginator.prependPaginate}
- onNavigationReady={setThreadListNavigation}
- onScrollStateChange={setThreadListScrollState}
- initialScrollSnapshot={
- props.targetMessageId
- ? undefined
+ onReady={onThreadListReady}
+ onScroll={onThreadListScroll}
+ onUserNavigation={cancelLatestNavigation}
+ initialPosition={
+ targetMessageController.activeTargetMessageId()
+ ? {
+ type: 'element',
+ id: targetMessageController.activeTargetMessageId()!,
+ }
: props.initialMessagesStateSnapshot?.scroll
+ ? {
+ type: 'restore',
+ snapshot:
+ props.initialMessagesStateSnapshot.scroll,
+ }
+ : { type: 'latest' }
}
- onScrollSnapshotChange={setThreadListScrollSnapshot}
>
{(item) => {
const message = () => messageById().get(item.id);
@@ -799,13 +802,8 @@ export function Channel(props: ChannelProps) {
: targetMessageController.pendingTargetReplyId(),
activeTargetReplyId:
targetMessageController.activeTargetMessageReplyId,
- positionTarget: (
- threadRow,
- targetElement
- ) =>
- threadListNavigation()?.scrollToElementInItem(
- item.id,
- threadRow,
+ positionTarget: (_, targetElement) =>
+ threadListNavigation()?.scrollToElement(
targetElement
) ?? false,
onTargetMessageScrolled:
@@ -857,7 +855,7 @@ export function Channel(props: ChannelProps) {
<Show when={!findBar.isOpen()}>
<ScrollToBottomOverlay
scrollState={threadListScrollState}
- onScrollToBottom={handleScrollToBottom}
+ onScrollToBottom={goToLatest}
class="touch:top-[calc(var(--mobile-content-inset-top,0)+1rem)]"
/>
</Show>
diff --git a/apps/web/src/features/channel/Channel/ThreadList.tsx b/apps/web/src/features/channel/Channel/ThreadList.tsx
index 41583530e3..75a686e573 100644
--- a/apps/web/src/features/channel/Channel/ThreadList.tsx
+++ b/apps/web/src/features/channel/Channel/ThreadList.tsx
@@ -1,64 +1,51 @@
-import { watchTouchDrag } from '@channel/touch-drag';
import { CustomScrollbar } from '@core/component/CustomScrollbar';
import {
createScrollIntentTracker,
type ScrollDirection,
} from '@core/util/scroll-intent';
-import { type Accessor, createSignal, type JSX, onCleanup } from 'solid-js';
-import { Virtualizer, type VirtualizerHandle } from 'virtua/solid';
-import type { CacheSnapshot, ScrollToIndexOpts } from 'virtua/unstable_core';
+import { Key } from '@solid-primitives/keyed';
+import {
+ createVirtualizer,
+ defaultRangeExtractor,
+ elementScroll,
+ measureElement,
+ observeElementOffset,
+ observeElementRect,
+ type Range,
+ type ScrollToOptions,
+ type VirtualItem,
+} from '@tanstack/solid-virtual';
+import {
+ type Accessor,
+ createEffect,
+ createMemo,
+ createSignal,
+ type JSX,
+ on,
+ onCleanup,
+ onMount,
+} from 'solid-js';
import { NEAR_BOTTOM_THRESHOLD } from './constants';
+import { createScrollLifecycle } from './create-scroll-lifecycle';
-const BASE_ITEM_SIZE = 96;
-const BASE_BUFFER_SIZE = 500;
-
-type ScrollAlignment = ScrollToIndexOpts['align'];
-
-export type ThreadListScrollTarget =
- | { tag: 'top'; align?: ScrollAlignment }
- | { tag: 'bottom'; align?: ScrollAlignment }
- | { tag: 'index'; index: number; align?: ScrollAlignment }
- | { tag: 'id'; id: string; align?: ScrollAlignment };
+type ScrollAlignment = NonNullable<ScrollToOptions['align']>;
-type InitialScrollTarget =
- | ThreadListScrollTarget
- | { tag: 'offset'; scrollOffset: number };
+const BASE_ITEM_SIZE = 96;
+const OVERSCAN = 6;
-export function defaultThreadListTargetFromMessage(
- targetMessageId: string | undefined
-): ThreadListScrollTarget {
- if (targetMessageId) {
- return {
- tag: 'id',
- id: targetMessageId,
- };
- }
- return DEFAULT_INITIAL_SCROLL_TARGET;
-}
+export type ThreadListInitialPosition =
+ | { type: 'latest' }
+ | { type: 'element'; id: string }
+ | { type: 'restore'; snapshot: ThreadListScrollSnapshot };
export type ThreadListNavigation = {
- scrollTo: (target: ThreadListScrollTarget) => boolean;
- scrollToIndex: (index: number, opts?: { align?: ScrollAlignment }) => boolean;
- scrollByDelta: (delta: number, opts?: { align?: ScrollAlignment }) => boolean;
- scrollToTop: (align?: ScrollAlignment) => boolean;
- scrollToBottom: (align?: ScrollAlignment) => boolean;
- scrollToId: (id: string, opts?: { align?: ScrollAlignment }) => boolean;
- navigatePrevious: () => boolean;
- navigateNext: () => boolean;
- isNearBottom: () => boolean;
- /** Position a descendant using Virtua's measured coordinate space. */
- scrollToElementInItem: (
+ scrollToLatest: () => boolean;
+ scrollToMessage: (
id: string,
- itemElement: HTMLElement,
- targetElement: HTMLElement
+ options?: { align?: ScrollAlignment; userIntent?: ScrollDirection }
) => boolean;
- /**
- * Signal that a user-initiated navigation is about to cause a
- * programmatic scroll. Call this before `scrollToId` etc. from
- * hotkey handlers so the resulting scroll is treated as user-driven
- * for pagination purposes.
- */
- markUserIntent: (direction: ScrollDirection) => void;
+ /** Center a mounted message or reply inside the unobscured viewport. */
+ scrollToElement: (element: HTMLElement) => boolean;
};
export type ThreadListScrollState = {
@@ -72,11 +59,11 @@ export type ThreadListScrollState = {
export type ThreadListScrollSnapshot = {
scrollOffset: number;
- virtualCache?: CacheSnapshot;
+ measurements?: VirtualItem[];
isNearBottom: boolean;
};
-export type FullFrameThreadListScrollInsets = {
+type ScrollInsets = {
/** Space reserved before the first message (e.g. status bar + floating header). */
start: number;
/** Space reserved after the last message (e.g. floating input + dock). */
@@ -84,737 +71,432 @@ 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;
+ initialPosition?: ThreadListInitialPosition;
onScrollNearTop?: () => void;
onScrollNearBottom?: () => void;
- onNavigationReady?: (navigation: ThreadListNavigation) => void;
- onScrollStateChange?: (state: ThreadListScrollState) => void;
- initialScrollSnapshot?: ThreadListScrollSnapshot;
- onScrollSnapshotChange?: (snapshot: ThreadListScrollSnapshot) => void;
- shift?: Accessor<boolean>;
- prepend?: Accessor<boolean>;
- /** Item indexes that must remain mounted during nested-message navigation. */
- keepMounted?: Accessor<readonly number[]>;
+ /** Physical gestures and keyboard navigation supersede pending page jumps. */
+ onUserNavigation?: () => void;
+ /** Called after initial layout; its optional cleanup releases the handle. */
+ onReady?: (navigation: ThreadListNavigation) => void | (() => void);
+ /** State and snapshot describe the same committed position. */
+ onScroll?: (
+ state: ThreadListScrollState,
+ snapshot: ThreadListScrollSnapshot | undefined
+ ) => void;
+ /** Follow live messages only when the loaded window includes the latest page. */
+ followOnAppend?: boolean;
+ /** Keep this thread mounted while its message or reply is being positioned. */
+ targetId?: string;
/**
* 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
- * virtua via `startMargin` + per-align scroll offsets.
+ * scrolls behind the floating chrome. Included in virtual measurements and navigation.
*/
- fullFrameScrollInsets?: Accessor<FullFrameThreadListScrollInsets>;
+ insets?: ScrollInsets;
};
const NEAR_TOP_THRESHOLD = 800;
const EXPLICIT_SCROLL_DOWN_TRIGGER_DISTANCE = 64;
-// After an imperative scroll-to-bottom, hold the viewport at the true bottom for
-// this long. virtua targets a scroll offset from its cached item sizes and stops
-// correcting ~150ms after the last measurement, and the scroller runs with
-// `overflow-anchor: none`, so a last message that grows afterwards (a loading
-// image or video, a new reaction, an opening reply input) is left cut off. The
-// re-pin window absorbs that late growth so a single action lands fully down.
-const SCROLL_TO_BOTTOM_SETTLE_MS = 1000;
-
-// How long the kept-mounted target row gets to put the target on screen before
-// the virtualizer positions it instead. Longer than the target scroller's
-// retry budget for a measured viewport, so the precise element scroll always
-// wins when it can run at all. While the viewport is still unmeasured the
-// fallback re-arms instead of firing: the scroller is legitimately waiting for
-// a box, and an index scroll would be computed against the same zero viewport.
-const TARGET_ELEMENT_FALLBACK_MS = 1500;
-
-export const DEFAULT_INITIAL_SCROLL_TARGET: ThreadListScrollTarget = {
- tag: 'bottom',
- align: 'end',
-};
-
const clamp = (value: number, min: number, max: number) =>
Math.max(min, Math.min(value, max));
-export function getTargetAlign(
- target: ThreadListScrollTarget
-): ScrollAlignment {
- if (target.align) return target.align;
- switch (target.tag) {
- case 'top':
- return 'start';
- case 'bottom':
- return 'end';
- case 'index':
- case 'id':
- return 'center';
- }
-}
-
-const NO_SCROLL_INSETS: FullFrameThreadListScrollInsets = { start: 0, end: 0 };
+const NO_SCROLL_INSETS: ScrollInsets = { start: 0, end: 0 };
export function ThreadList(props: ThreadListProps) {
- const [virtualHandle, setVirtualHandle] = createSignal<VirtualizerHandle>();
- const [isNearBottom, setIsNearBottom] = createSignal(true);
- const [didInitialScroll, setDidInitialScroll] = createSignal(false);
- const [scrollEl, setScrollEl] = createSignal<HTMLDivElement>();
-
- const insets = () => props.fullFrameScrollInsets?.() ?? NO_SCROLL_INSETS;
-
- /**
- * Correction so alignment targets the inset-adjusted usable viewport
- * (below the floating header, above the floating bottom chrome) instead
- * of the physical scroll viewport. Derived against virtua's scrollToIndex
- * math with `startMargin = insets().start`.
- */
- const insetAlignOffset = (align: ScrollAlignment): number => {
- const { start, end } = insets();
- switch (align) {
- case 'start':
- return -start;
- case 'end':
- return end;
- case 'center':
- return (end - start) / 2;
- default:
- return 0;
- }
- };
-
+ // Publish the ref on mount: Solid template nodes can still belong to an
+ // inert document (no defaultView) when the ref callback runs.
let scrollRef: HTMLDivElement | undefined;
+ let contentRef: HTMLDivElement | undefined;
+ const [scrollEl, setScrollEl] = createSignal<HTMLDivElement>();
+ const [viewportSize, setViewportSize] = createSignal(0);
+ const insets = () => props.insets ?? NO_SCROLL_INSETS;
+ // Capture each key array so the previous virtualizer options still describe
+ // the previous page while TanStack resolves its prepend anchor.
+ const getItemKey = createMemo(() => {
+ const keys = [...props.keys()];
+ return (index: number) => keys[index];
+ });
+ const scrollIntent = createScrollIntentTracker(() => {
+ lifecycle.send('user-scroll');
+ props.onUserNavigation?.();
+ });
+ const initialPosition = props.initialPosition ?? { type: 'latest' };
+ const snapshot =
+ initialPosition.type === 'restore' ? initialPosition.snapshot : undefined;
+ // Seed the first range with cached sizes too: tall saved rows can put the
+ // actual end far beyond the default estimate, before any DOM is measured.
+ const initialSizes = new Map(
+ snapshot?.measurements?.map(({ key, size }) => [key, size])
+ );
+ let programmaticOffset: number | undefined;
+ let userScrollActive = false;
+ let stateQueued = false;
let nearTopFired = false;
let nearBottomFired = false;
- let previousScrollOffset: number | undefined;
+ let previousScrollOffset = snapshot?.scrollOffset ?? 0;
let explicitScrollDownDistance = 0;
- let cancelPinToBottom: (() => void) | undefined;
-
- const scrollIntent = createScrollIntentTracker();
-
- let initialScrollStarted = false;
- let initialScrollRetried = false;
- let initialScrollTarget: InitialScrollTarget = DEFAULT_INITIAL_SCROLL_TARGET;
- let targetElementFallbackTimer: number | undefined;
-
- const clearTargetElementFallback = () => {
- if (targetElementFallbackTimer === undefined) return;
- window.clearTimeout(targetElementFallbackTimer);
- targetElementFallbackTimer = undefined;
- };
-
- const resetInitialScroll = () => {
- initialScrollStarted = false;
- initialScrollRetried = false;
- initialScrollTarget = DEFAULT_INITIAL_SCROLL_TARGET;
- clearTargetElementFallback();
+ let releaseNavigation: void | (() => void);
+
+ // Publish after Solid has committed the virtual rows and spacer height.
+ // Geometry notifications also cover reactions, streamed content and resizes
+ // that do not produce a browser scroll event.
+ const scheduleScrollState = () => {
+ if (stateQueued) return;
+ stateQueued = true;
+ queueMicrotask(() => {
+ stateQueued = false;
+ if (!lifecycle.isDisposed()) emitScrollState();
+ });
};
- const resolveTargetIndex = (target: ThreadListScrollTarget): number => {
- const keys = props.keys();
- const maxIndex = keys.length - 1;
- if (maxIndex < 0) return -1;
-
- switch (target.tag) {
- case 'top':
- return 0;
- case 'bottom':
- return maxIndex;
- case 'index':
- return clamp(target.index, 0, maxIndex);
- case 'id': {
- const idx = keys.indexOf(target.id);
- return idx === -1 ? -1 : idx;
+ const lifecycle = createScrollLifecycle({
+ hasLayout: () => viewportSize() > 0 && props.keys().length > 0,
+ waitForElement: initialPosition.type === 'element',
+ positionInitial: () => {
+ // Restored history has already been positioned by initialOffset. Replaying
+ // its offset here would undo corrections for rows measured during mount.
+ if (!snapshot || snapshot.isNearBottom) {
+ virtualizer.scrollToEnd();
}
- }
- };
-
- const scrollToTarget = (
- handle: VirtualizerHandle,
- target: ThreadListScrollTarget,
- options: { cancelPin?: boolean } = {}
- ): boolean => {
- const index = resolveTargetIndex(target);
- if (index < 0) return false;
- // A deliberate navigation to a specific target aborts an in-flight
- // pinToBottom settle loop, which would otherwise yank the view back to the
- // bottom frame-by-frame and strand the target (e.g. opening a channel at
- // latest, then clicking a message/thread row within its settle window).
- // pinToBottom opts out so it doesn't cancel the loop it is establishing.
- if (options.cancelPin !== false) cancelPinToBottom?.();
- const align = getTargetAlign(target);
- handle.scrollToIndex(index, { align, offset: insetAlignOffset(align) });
- return true;
- };
-
- const scrollToInitialTarget = (
- handle: VirtualizerHandle,
- target: InitialScrollTarget
- ): boolean => {
- if (target.tag !== 'offset') return scrollToTarget(handle, target);
-
- handle.scrollTo(target.scrollOffset);
- return true;
- };
-
- // DOM-based so the scroll insets are accounted for — virtua's scrollSize
- // only covers its own items, not the inset padding around them.
- const getDistanceFromBottom = (handle: VirtualizerHandle): number => {
- if (scrollRef) {
- return Math.max(
- 0,
- scrollRef.scrollHeight - scrollRef.clientHeight - scrollRef.scrollTop
- );
- }
- return handle.scrollSize - handle.viewportSize - handle.scrollOffset;
- };
-
- const isScrollPositionCorrect = (
- handle: VirtualizerHandle,
- target: InitialScrollTarget
- ): boolean => {
- switch (target.tag) {
- case 'offset':
- return Math.abs(handle.scrollOffset - target.scrollOffset) <= 1;
- case 'bottom':
- return getDistanceFromBottom(handle) <= NEAR_BOTTOM_THRESHOLD;
- case 'top':
- return handle.scrollOffset <= NEAR_BOTTOM_THRESHOLD;
- case 'id':
- case 'index': {
- const targetIndex = resolveTargetIndex(target);
- if (targetIndex < 0) return true; // target gone, nothing to verify
- // Correct when the target item intersects the usable viewport.
- // Comparing item indexes against the top-of-viewport item breaks for
- // center/end alignment — a target near the end of the list rests in
- // the lower half of the viewport, so a fixed index distance from the
- // top item reports a perfect landing as a miss.
- const itemTop = handle.getItemOffset(targetIndex);
- const itemBottom = itemTop + handle.getItemSize(targetIndex);
- const viewportTop = handle.scrollOffset + insets().start;
- const viewportBottom =
- handle.scrollOffset + handle.viewportSize - insets().end;
- return itemBottom > viewportTop && itemTop < viewportBottom;
+ },
+ positionFallback: () => {
+ if (
+ initialPosition.type === 'element' &&
+ !scrollToMessage(initialPosition.id)
+ ) {
+ virtualizer.scrollToEnd();
}
- }
- };
-
- const getCurrentIndex = (handle: VirtualizerHandle): number => {
- const itemCount = props.keys().length;
- if (!itemCount) return -1;
- return clamp(
- handle.findItemIndex(handle.scrollOffset + insets().start),
- 0,
- itemCount - 1
- );
- };
-
- const emitScrollState = (
- handle: VirtualizerHandle,
- isScrollingDown: boolean
- ) => {
- if (!props.onScrollStateChange) return;
- const distanceFromTop = handle.scrollOffset;
- const distanceFromBottom = getDistanceFromBottom(handle);
- props.onScrollStateChange({
- didInitialScroll: didInitialScroll(),
- isNearBottom: distanceFromBottom <= NEAR_BOTTOM_THRESHOLD,
- isScrollingDown,
- distanceFromTop,
- distanceFromBottom,
- viewportSize: handle.viewportSize,
- });
- };
-
- /** Mark the initial scroll as complete and broadcast the scroll state. */
- const completeInitialScroll = (handle: VirtualizerHandle) => {
- setDidInitialScroll(true);
- emitScrollState(handle, false);
- emitScrollSnapshot(handle);
- };
-
- const emitScrollSnapshot = (handle: VirtualizerHandle) => {
- props.onScrollSnapshotChange?.({
- scrollOffset: handle.scrollOffset,
- virtualCache: handle.cache,
- isNearBottom: getDistanceFromBottom(handle) <= NEAR_BOTTOM_THRESHOLD,
- });
- };
-
- // Scroll to the newest message, then keep re-pinning to the true bottom for a
- // short window so late-settling content can't leave the last message cut off.
- // Aborts on a real scroll gesture (wheel up or touch drag), not on taps.
- const pinToBottom = (handle: VirtualizerHandle): boolean => {
- cancelPinToBottom?.();
-
- const didScroll = scrollToTarget(
- handle,
- { tag: 'bottom', align: 'end' },
- { cancelPin: false }
- );
- const el = scrollRef;
- if (!didScroll || !el) return didScroll;
-
- let rafId = 0;
- const start = performance.now();
- const virtualContent = Array.from(el.children).find(
- (child): child is HTMLElement =>
- child instanceof HTMLElement && child.style.contain.includes('size')
- );
- const resizeObserver = virtualContent
- ? new ResizeObserver(() => {
- if (getDistanceFromBottom(handle) > 1) el.scrollTop = el.scrollHeight;
- })
- : undefined;
- if (virtualContent) resizeObserver?.observe(virtualContent);
-
- const stop = () => {
- if (rafId) cancelAnimationFrame(rafId);
- resizeObserver?.disconnect();
- el.removeEventListener('wheel', onWheel);
- unwatchDrag();
- if (cancelPinToBottom === stop) cancelPinToBottom = undefined;
- };
-
- function onWheel(event: WheelEvent) {
- if (event.deltaY < 0) stop();
- }
-
- el.addEventListener('wheel', onWheel, { passive: true });
- // A press on a message, reply button, or reaction is not a scroll and must
- // not cancel pinning. Only a wheel-up or a touch drag is the user scrolling.
- const unwatchDrag = watchTouchDrag(el, stop);
- cancelPinToBottom = stop;
+ },
+ onReady: () => {
+ releaseNavigation = props.onReady?.(navigation);
+ },
+ });
- const tick = () => {
- if (getDistanceFromBottom(handle) > 1) el.scrollTop = el.scrollHeight;
- if (performance.now() - start >= SCROLL_TO_BOTTOM_SETTLE_MS) {
- stop();
- return;
+ const virtualizer = createVirtualizer<HTMLDivElement, HTMLDivElement>({
+ // Do not consume initialOffset against an empty query result. Enabling
+ // with the first page lets TanStack render the latest rows immediately.
+ get enabled() {
+ return props.keys().length > 0;
+ },
+ get count() {
+ return props.keys().length;
+ },
+ getScrollElement: () => scrollEl() ?? null,
+ get getItemKey() {
+ return getItemKey();
+ },
+ estimateSize: () => BASE_ITEM_SIZE,
+ overscan: OVERSCAN,
+ // A restored snapshot or a newly remounted message can have a different
+ // height. The default sync path returns cached sizes, exposing the old
+ // layout until ResizeObserver fires. Read mounted rows before first paint.
+ measureElement: (element, entry, instance) =>
+ entry ? measureElement(element, entry, instance) : element.offsetHeight,
+ // Measure outside ResizeObserver delivery: committing row/sizer geometry
+ // inside its callback can leave undelivered notifications in WebKit.
+ useAnimationFrameWithResizeObserver: true,
+ useScrollendEvent: true,
+ anchorTo: 'end',
+ get followOnAppend() {
+ return lifecycle.isReady() && (props.followOnAppend ?? true);
+ },
+ scrollEndThreshold: NEAR_BOTTOM_THRESHOLD,
+ get paddingStart() {
+ return insets().start;
+ },
+ get paddingEnd() {
+ return insets().end;
+ },
+ get scrollPaddingStart() {
+ return insets().start;
+ },
+ get scrollPaddingEnd() {
+ return insets().end;
+ },
+ initialMeasurementsCache: snapshot?.measurements,
+ initialOffset: () =>
+ snapshot && !snapshot.isNearBottom
+ ? snapshot.scrollOffset
+ : initialPosition.type === 'latest' || (snapshot?.isNearBottom ?? false)
+ ? props
+ .keys()
+ .reduce(
+ (total, key) =>
+ total + (initialSizes.get(key) ?? BASE_ITEM_SIZE),
+ insets().start + insets().end
+ )
+ : 0,
+ get rangeExtractor() {
+ const index =
+ props.targetId === undefined
+ ? -1
+ : props.keys().indexOf(props.targetId);
+ return (range: Range) => {
+ const indexes = defaultRangeExtractor(range);
+ if (index < 0 || index >= range.count || indexes.includes(index))
+ return indexes;
+ return [...indexes, index].sort((a, b) => a - b);
+ };
+ },
+ scrollToFn: (offset, options, instance) => {
+ // Size corrections happen before the Solid adapter publishes its new
+ // total. Commit the sizer first so the browser cannot clamp the requested
+ // scroll to the old range (especially with padding below a growing row).
+ if (contentRef) {
+ contentRef.style.height = `${Math.max(viewportSize(), instance.getTotalSize())}px`;
}
- rafId = requestAnimationFrame(tick);
- };
- rafId = requestAnimationFrame(tick);
-
- return true;
- };
-
- const createNavigation = (
- handle: VirtualizerHandle
- ): ThreadListNavigation => ({
- scrollTo: (target) => scrollToTarget(handle, target),
-
- scrollToIndex: (index, opts = {}) =>
- scrollToTarget(handle, { tag: 'index', index, align: opts.align }),
-
- scrollByDelta: (delta, opts = {}) => {
- const current = getCurrentIndex(handle);
- if (current < 0) return false;
- return scrollToTarget(handle, {
- tag: 'index',
- index: current + delta,
- align: opts.align,
- });
+ // A deferred prepend has already advanced the logical offset while
+ // the DOM is still at the old position. Positive corrections in that
+ // state must start at the DOM offset; normal corrections (including
+ // shrink clamping) still use TanStack's requested offset.
+ const domOffset = instance.scrollElement?.scrollTop ?? offset;
+ const deferredPrepend =
+ (options.adjustments ?? 0) > 0 &&
+ offset > domOffset + 1.5 &&
+ (userScrollActive || scrollIntent.isUserInteracting());
+ elementScroll(deferredPrepend ? domOffset : offset, options, instance);
+ programmaticOffset =
+ options.behavior === 'smooth'
+ ? undefined
+ : instance.scrollElement?.scrollTop;
},
+ observeElementOffset: (instance, callback) =>
+ observeElementOffset(instance, (offset, isScrolling) => {
+ // An instant navigation/correction is not touch momentum. Reporting
+ // its scroll event as momentum makes iOS defer size compensation and
+ // replay it after scrollToIndex has already reconciled the same sizes.
+ const isOwnScroll =
+ programmaticOffset !== undefined &&
+ Math.abs(offset - programmaticOffset) < 1.5;
+ programmaticOffset = undefined;
+ if (isScrolling && !isOwnScroll) userScrollActive = true;
+ callback(offset, isScrolling && !isOwnScroll);
+ // Keep the gesture active while the end callback flushes any deferred
+ // correction, including momentum lasting past the input-event timeout.
+ if (!isScrolling || isOwnScroll) userScrollActive = false;
+ }),
+ observeElementRect: (instance, callback) =>
+ observeElementRect(instance, (rect) => {
+ const previousHeight = instance.scrollRect?.height ?? 0;
+ const wasAtEnd =
+ instance.getTotalSize() -
+ previousHeight -
+ (instance.scrollOffset ?? 0) <=
+ NEAR_BOTTOM_THRESHOLD;
+ callback(rect);
+ setViewportSize(rect.height);
+ scheduleScrollState();
+ // The core anchors item resizes; viewport resizes (composer, keyboard,
+ // split pane) need an explicit end scroll when previously pinned.
+ if (previousHeight > 0 && previousHeight !== rect.height && wasAtEnd) {
+ instance.scrollToEnd();
+ }
+ }),
+ onChange: scheduleScrollState,
+ });
- scrollToTop: (align = 'start') =>
- scrollToTarget(handle, { tag: 'top', align }),
-
- scrollToBottom: () => pinToBottom(handle),
+ const shortListOffset = () =>
+ Math.max(0, viewportSize() - virtualizer.getTotalSize());
+ // The adapter mutates its store by index. Snapshot those values and let Key
+ // own each row's accessor by message ID, including while a row is removed.
+ // A lookup into a shared map can disappear before queued row effects run.
+ const virtualItems = createMemo(() =>
+ virtualizer.getVirtualItems().map((item) => ({ ...item }))
+ );
- scrollToId: (id, opts = {}) =>
- scrollToTarget(handle, { tag: 'id', id, align: opts.align }),
+ const scrollToMessage = (
+ id: string,
+ align: ScrollAlignment = 'center'
+ ): boolean => {
+ const index = props.keys().indexOf(id);
+ if (index < 0) return false;
+ virtualizer.scrollToIndex(index, { align });
+ scheduleScrollState();
+ return true;
+ };
- navigatePrevious: () => {
- const current = getCurrentIndex(handle);
- if (current <= 0) return false;
- return scrollToTarget(handle, { tag: 'index', index: current - 1 });
+ const canNavigate = () =>
+ lifecycle.isReady() &&
+ scrollEl()?.isConnected &&
+ (scrollEl()?.clientHeight ?? 0) > 0;
+
+ const navigation: ThreadListNavigation = {
+ scrollToLatest: () => {
+ if (!canNavigate() || !props.keys().length) return false;
+ lifecycle.send('navigate');
+ virtualizer.scrollToEnd();
+ scheduleScrollState();
+ return true;
},
-
- navigateNext: () => {
- const current = getCurrentIndex(handle);
- if (current < 0) return false;
- return scrollToTarget(handle, { tag: 'index', index: current + 1 });
+ scrollToMessage: (id, options) => {
+ if (!canNavigate() || !props.keys().includes(id)) return false;
+ lifecycle.send('navigate');
+ if (options?.userIntent) scrollIntent.markUserIntent(options.userIntent);
+ return scrollToMessage(id, options?.align);
},
-
- isNearBottom,
-
- scrollToElementInItem: (id, itemElement, targetElement) => {
- const index = props.keys().indexOf(id);
- if (index === -1) return false;
- // Nothing has been measured yet (an app launched into a squished
- // viewport). Every offset below would be computed against a zero
- // viewport, so report failure instead of moving to a meaningless place.
- if (handle.viewportSize <= 0) return false;
-
- cancelPinToBottom?.();
- const itemRect = itemElement.getBoundingClientRect();
+ scrollToElement: (targetElement) => {
+ const el = scrollEl();
+ if (!canNavigate() || !el || !el.contains(targetElement)) return false;
+ lifecycle.send('navigate');
+ // Both rects come from the same committed layout, including short-list
+ // bottom alignment and floating chrome. No stale estimate is involved.
const targetRect = targetElement.getBoundingClientRect();
- const targetCenter =
- handle.getItemOffset(index) +
- (targetRect.top - itemRect.top) +
- targetRect.height / 2;
+ const scrollRect = el.getBoundingClientRect();
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(
+ const targetCenter =
+ el.scrollTop + targetRect.top - scrollRect.top + targetRect.height / 2;
+ virtualizer.scrollToOffset(
clamp(
- targetCenter - usableViewportCenter,
+ targetCenter - (start + (el.clientHeight - start - end) / 2),
0,
- Math.max(0, maxScrollOffset)
+ Math.max(0, el.scrollHeight - el.clientHeight)
)
);
+ scheduleScrollState();
return true;
},
-
- markUserIntent: scrollIntent.markUserIntent,
- });
-
- function beginInitialTargetScroll(
- handle: VirtualizerHandle,
- target: InitialScrollTarget
- ) {
- initialScrollTarget = target;
-
- console.debug('ThreadList: scrollOnMount', {
- target,
- itemCount: props.keys().length,
- scrollOffset: handle.scrollOffset,
- scrollSize: handle.scrollSize,
- viewportSize: handle.viewportSize,
- });
-
- const didScroll =
- target.tag === 'bottom'
- ? pinToBottom(handle)
- : scrollToInitialTarget(handle, target);
-
- if (!didScroll) {
- // Empty list or target not found — nothing to verify.
- console.debug(
- 'ThreadList: target not resolvable, completing immediately'
- );
- completeInitialScroll(handle);
- return;
- }
-
- // If no actual scrolling was needed (content fits in viewport),
- // onScrollEnd will never fire. Use a RAF to detect this case and
- // finalize immediately.
- requestAnimationFrame(() => {
- if (didInitialScroll()) return;
- if (isScrollPositionCorrect(handle, target)) {
- console.debug(
- 'ThreadList: position already correct (RAF fallback), completing'
- );
- completeInitialScroll(handle);
- }
- });
- }
-
- let disposed = false;
-
- // A preview-pane mount can hand over the virtualizer before layout, with a
- // zero-height viewport — the initial scroll then lands wherever and always
- // needs the onScrollEnd retry. Wait (bounded) for a measured viewport.
- function scrollOnMountWhenMeasured(
- handle: VirtualizerHandle,
- framesLeft = 30
- ) {
- if (disposed || initialScrollStarted) return;
- if (handle.viewportSize > 0 || framesLeft <= 0) {
- scrollOnMount(handle);
- return;
- }
- requestAnimationFrame(() =>
- scrollOnMountWhenMeasured(handle, framesLeft - 1)
- );
- }
-
- const getInitialScrollTarget = (): InitialScrollTarget => {
- const snapshot = props.initialScrollSnapshot;
- if (snapshot) {
- return snapshot.isNearBottom
- ? DEFAULT_INITIAL_SCROLL_TARGET
- : { tag: 'offset', scrollOffset: snapshot.scrollOffset };
- }
-
- return props.initialScrollTarget ?? DEFAULT_INITIAL_SCROLL_TARGET;
- };
-
- // Virtua publishes its handle before ResizeObserver has populated
- // `viewportSize`. Waiting for that measurement before doing anything leaves
- // an overflowing channel visibly parked at scrollTop=0 for one or more
- // frames. A bottom target is safe to issue immediately: with a zero viewport
- // Virtua overshoots the final offset and the browser clamps it to the DOM's
- // current maximum, putting the first painted frame at the bottom. The normal
- // measured pass below still corrects the exact end alignment afterwards.
- const prepositionInitialBottom = (handle: VirtualizerHandle) => {
- const target = getInitialScrollTarget();
- if (target.tag === 'bottom') pinToBottom(handle);
- };
-
- function scrollOnMount(handle: VirtualizerHandle) {
- if (initialScrollStarted) return;
- initialScrollStarted = true;
- if (props.initialScrollHandledByTargetElement) {
- // The kept-mounted target row owns the viewport movement, so nothing is
- // scrolled here and the list is still sitting where it mounted — the top
- // of the loaded window. Arm a fallback in case that element scroll never
- // lands (a row that never mounts, a scroller that gives up on an
- // unmeasured viewport): a channel opened at a message must never be left
- // at the top of its history.
- initialScrollTarget = getInitialScrollTarget();
- completeInitialScroll(handle);
- armTargetElementFallback(handle, initialScrollTarget);
- return;
- }
- beginInitialTargetScroll(handle, getInitialScrollTarget());
- }
-
- /**
- * Positions the initial target through the virtualizer if the target element
- * has not put it on screen by `TARGET_ELEMENT_FALLBACK_MS`. Deliberately
- * coarse: landing on the target's row beats staying at the top.
- */
- function armTargetElementFallback(
- handle: VirtualizerHandle,
- target: InitialScrollTarget
- ) {
- clearTargetElementFallback();
- if (target.tag !== 'id' && target.tag !== 'index') return;
- targetElementFallbackTimer = window.setTimeout(() => {
- targetElementFallbackTimer = undefined;
- if (disposed) return;
- // The target is no longer pending: it either landed or the user took the
- // scroll over (a drag releases it). Either way there is nothing to
- // rescue, and moving the viewport now would be a yank.
- if (!props.initialScrollHandledByTargetElement) return;
- if (scrollIntent.isUserInteracting()) return;
- // No viewport to position against yet. The element scroller is still
- // waiting for one (it holds the target for longer than this), and an
- // index scroll here would land against the same zero viewport — so wait
- // for a box rather than move somewhere meaningless.
- if (handle.viewportSize <= 0) {
- armTargetElementFallback(handle, target);
- return;
- }
- if (resolveTargetIndex(target) < 0) {
- // The target never made it into the loaded window. No scroll can reach it, and staying where
- // the list mounted means the top of history, so show the latest
- // instead — the same answer the missing-message path gives.
- console.debug(
- 'ThreadList: target never loaded, falling back to latest',
- {
- target,
- scrollOffset: handle.scrollOffset,
- }
- );
- pinToBottom(handle);
- return;
- }
- if (isScrollPositionCorrect(handle, target)) return;
- console.debug('ThreadList: target element never landed, falling back', {
- target,
- scrollOffset: handle.scrollOffset,
- viewportSize: handle.viewportSize,
- });
- scrollToTarget(handle, target);
- }, TARGET_ELEMENT_FALLBACK_MS);
- }
-
- const handleScrollEnd = () => {
- if (didInitialScroll()) return;
-
- const handle = virtualHandle();
- if (!handle) return;
-
- if (isScrollPositionCorrect(handle, initialScrollTarget)) {
- console.debug('ThreadList: onScrollEnd confirmed position, completing', {
- scrollOffset: handle.scrollOffset,
- distanceFromBottom: getDistanceFromBottom(handle),
- });
- completeInitialScroll(handle);
- return;
- }
-
- if (!initialScrollRetried) {
- initialScrollRetried = true;
- console.debug('ThreadList: initial scroll missed target, retrying', {
- target: initialScrollTarget,
- scrollOffset: handle.scrollOffset,
- scrollSize: handle.scrollSize,
- viewportSize: handle.viewportSize,
- distanceFromBottom: getDistanceFromBottom(handle),
- });
- requestAnimationFrame(() => {
- const offsetBeforeRetry = handle.scrollOffset;
- const retryScrolled =
- initialScrollTarget.tag === 'bottom'
- ? pinToBottom(handle)
- : scrollToInitialTarget(handle, initialScrollTarget);
- if (!retryScrolled) {
- // Target disappeared between mount and retry — finalize now since
- // no scroll events will fire to trigger another onScrollEnd.
- completeInitialScroll(handle);
- return;
- }
- // A retry that lands on the current position moves nothing, so no
- // scroll events (and no onScrollEnd) follow. Finalize on the next
- // frame or `didInitialScroll` stays false for the life of the mount,
- // deadlocking everything gated on it (target navigation, scroll
- // pagination, goToLatest).
- requestAnimationFrame(() => {
- if (didInitialScroll()) return;
- if (handle.scrollOffset !== offsetBeforeRetry) return;
- console.debug(
- 'ThreadList: retry did not move the scroll, completing'
- );
- completeInitialScroll(handle);
- });
- });
- return;
- }
- console.warn(
- 'ThreadList: initial scroll did not reach target after retry',
- {
- target: initialScrollTarget,
- scrollOffset: handle.scrollOffset,
- scrollSize: handle.scrollSize,
- viewportSize: handle.viewportSize,
- distanceFromBottom: getDistanceFromBottom(handle),
- }
- );
- completeInitialScroll(handle);
};
- const handleScroll = () => {
- const handle = virtualHandle();
- if (!handle) {
- console.warn(
- 'Channel.ThreadList: handle scroll but the handle is undefined'
- );
- return;
- }
-
- const distanceFromTop = handle.scrollOffset;
- const distanceFromBottom = getDistanceFromBottom(handle);
-
+ function emitScrollState() {
+ const el = scrollEl();
+ if (!el) return;
+ // This microtask runs after synchronous row measurements, before paint.
+ lifecycle.send('layout');
+ const distanceFromTop = el.scrollTop;
+ const distanceFromBottom = virtualizer.getDistanceFromEnd();
const nearTop = distanceFromTop <= NEAR_TOP_THRESHOLD;
const nearBottom = distanceFromBottom <= NEAR_BOTTOM_THRESHOLD;
-
- setIsNearBottom(nearBottom);
- let nextIsScrollingDown = false;
-
- if (previousScrollOffset !== undefined) {
- const delta = handle.scrollOffset - previousScrollOffset;
- // Accumulate downward scroll distance only during user interaction
- // and only when the user is scrolling down. Used by the scroll-to-bottom overlay.
- if (
- scrollIntent.isUserInteracting() &&
- delta > 0 &&
- scrollIntent.lastDirection() === 'down'
- ) {
- explicitScrollDownDistance += delta;
- } else {
- explicitScrollDownDistance = 0;
- }
- nextIsScrollingDown =
- explicitScrollDownDistance >= EXPLICIT_SCROLL_DOWN_TRIGGER_DISTANCE;
- }
- previousScrollOffset = handle.scrollOffset;
- emitScrollState(handle, nextIsScrollingDown);
- emitScrollSnapshot(handle);
-
- if (!didInitialScroll()) return;
-
- // Only trigger pagination callbacks when the user is actively
- // interacting with the scroll surface. This prevents synthetic
- // scroll events from the virtualizer (content resizes, layout
- // reflows, shift adjustments) from incorrectly loading more pages.
const hasUserIntent = scrollIntent.isUserInteracting();
-
+ const delta = distanceFromTop - previousScrollOffset;
+ if (delta !== 0) {
+ explicitScrollDownDistance =
+ hasUserIntent && delta > 0 && scrollIntent.lastDirection() === 'down'
+ ? explicitScrollDownDistance + delta
+ : 0;
+ }
+ previousScrollOffset = distanceFromTop;
+ const state: ThreadListScrollState = {
+ didInitialScroll: lifecycle.isReady(),
+ isNearBottom: nearBottom,
+ isScrollingDown:
+ explicitScrollDownDistance >= EXPLICIT_SCROLL_DOWN_TRIGGER_DISTANCE,
+ distanceFromTop,
+ distanceFromBottom,
+ viewportSize: el.clientHeight,
+ };
+ // Capture both before invoking callers, which may synchronously navigate.
+ const snapshot = state.didInitialScroll
+ ? {
+ scrollOffset: distanceFromTop,
+ measurements: virtualizer.takeSnapshot(),
+ isNearBottom: nearBottom,
+ }
+ : undefined;
+ props.onScroll?.(state, snapshot);
+ if (!lifecycle.isReady()) return;
if (nearTop && !nearTopFired && hasUserIntent) {
nearTopFired = true;
props.onScrollNearTop?.();
- } else if (!nearTop) {
- nearTopFired = false;
- }
-
+ } else if (!nearTop) nearTopFired = false;
if (nearBottom && !nearBottomFired && hasUserIntent) {
nearBottomFired = true;
props.onScrollNearBottom?.();
- } else if (!nearBottom) {
- nearBottomFired = false;
- }
- };
+ } else if (!nearBottom) nearBottomFired = false;
+ }
+
+ // Floating chrome can resize without resizing the scroll viewport. Compare
+ // against the old content extent before following the new inset to latest.
+ createEffect(
+ on(insets, (current, previous) => {
+ if (!previous || !lifecycle.isReady()) return;
+ const delta = current.start + current.end - previous.start - previous.end;
+ const previousDistance =
+ virtualizer.getTotalSize() -
+ delta -
+ viewportSize() -
+ (virtualizer.scrollOffset ?? 0);
+ if (delta !== 0 && previousDistance <= NEAR_BOTTOM_THRESHOLD) {
+ virtualizer.scrollToEnd();
+ }
+ scheduleScrollState();
+ })
+ );
+ onMount(() => {
+ // Suspense can construct a channel in an inert template document and
+ // insert it in a later task. Bind only after adoption into the live DOM.
+ const attachmentObserver = new MutationObserver(connect);
+ function connect() {
+ if (!scrollRef?.isConnected) return;
+ attachmentObserver.disconnect();
+ setScrollEl(scrollRef);
+ scheduleScrollState();
+ }
+ attachmentObserver.observe(document, { childList: true, subtree: true });
+ connect();
+ onCleanup(() => attachmentObserver.disconnect());
+ });
onCleanup(() => {
- disposed = true;
- cancelPinToBottom?.();
- clearTargetElementFallback();
+ lifecycle.send('dispose');
+ releaseNavigation?.();
});
return (
<>
<div
- ref={(el) => {
- scrollRef = el;
- setScrollEl(el);
- }}
+ ref={scrollRef}
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 px-2"
{...scrollIntent.handlers}
+ onScroll={scheduleScrollState}
style={{
width: '100%',
+ height: '100%',
'overflow-y': 'auto',
'overflow-anchor': 'none',
- height: '100%',
- display: 'flex',
- 'flex-direction': 'column',
}}
>
- {/* Spacer div for full-frame inset. */}
<div
- aria-hidden
- style={{ height: `${insets().start}px`, 'flex-shrink': 0 }}
- />
- <div style="flex-grow: 1" />
- <Virtualizer
- cache={props.initialScrollSnapshot?.virtualCache}
- ref={(ref) => {
- if (!ref) return;
- setVirtualHandle(ref);
- if (props.onNavigationReady) {
- props.onNavigationReady(createNavigation(ref));
- }
- resetInitialScroll();
- prepositionInitialBottom(ref);
- scrollOnMountWhenMeasured(ref);
+ ref={contentRef}
+ style={{
+ position: 'relative',
+ width: '100%',
+ height: `${Math.max(viewportSize(), virtualizer.getTotalSize())}px`,
}}
- scrollRef={scrollRef}
- startMargin={insets().start}
- itemSize={BASE_ITEM_SIZE}
- bufferSize={BASE_BUFFER_SIZE}
- keepMounted={props.keepMounted?.()}
- data={props.keys()}
- onScroll={handleScroll}
- onScrollEnd={handleScrollEnd}
- shift={props.shift?.() ?? false}
>
- {(key) => props.children({ id: key })}
- </Virtualizer>
- {/* Spacer div for full-frame inset. */}
- <div
- aria-hidden
- style={{ height: `${insets().end}px`, 'flex-shrink': 0 }}
- />
+ <Key each={virtualItems()} by="key">
+ {(item) => {
+ const id = String(item().key);
+ let row: HTMLDivElement | undefined;
+ createEffect(
+ on(
+ () => item().index,
+ () => {
+ if (row) virtualizer.measureElement(row);
+ }
+ )
+ );
+ return (
+ <div
+ ref={row}
+ data-index={item().index}
+ style={{
+ position: 'absolute',
+ top: 0,
+ left: 0,
+ width: '100%',
+ transform: `translateY(${item().start + shortListOffset()}px)`,
+ 'overflow-anchor': 'none',
+ }}
+ >
+ {props.children({ id })}
+ </div>
+ );
+ }}
+ </Key>
+ </div>
</div>
<CustomScrollbar scrollContainer={scrollEl} />
</>
diff --git a/apps/web/src/features/channel/Channel/create-channel-hotkeys.ts b/apps/web/src/features/channel/Channel/create-channel-hotkeys.ts
index f96eca0ef3..9eeecaf993 100644
--- a/apps/web/src/features/channel/Channel/create-channel-hotkeys.ts
+++ b/apps/web/src/features/channel/Channel/create-channel-hotkeys.ts
@@ -10,7 +10,7 @@ import type { ThreadListNavigation } from './ThreadList';
type CreateChannelHotkeysOptions = {
selection: MessageSelection;
- navigation: Accessor<ThreadListNavigation | undefined>;
+ scrollToMessage: ThreadListNavigation['scrollToMessage'];
messageById: Accessor<Map<string, ApiChannelMessage>>;
getMessageActions: (message: MessageData) => MessageActions | undefined;
userId: Accessor<string | undefined>;
@@ -74,8 +74,7 @@ export function createChannelHotkeys(options: CreateChannelHotkeysOptions) {
keyDownHandler: () => {
const id = options.selection.selectPrevious();
if (id) {
- options.navigation()?.markUserIntent('up');
- options.navigation()?.scrollToId(id, { align: 'nearest' });
+ options.scrollToMessage(id, { align: 'auto', userIntent: 'up' });
}
return true;
},
@@ -89,8 +88,7 @@ export function createChannelHotkeys(options: CreateChannelHotkeysOptions) {
keyDownHandler: () => {
const id = options.selection.selectNext();
if (id) {
- options.navigation()?.markUserIntent('down');
- options.navigation()?.scrollToId(id, { align: 'nearest' });
+ options.scrollToMessage(id, { align: 'auto', userIntent: 'down' });
} else {
inputEl?.querySelector<HTMLElement>('[contenteditable]')?.focus();
}
@@ -104,7 +102,6 @@ export function createChannelHotkeys(options: CreateChannelHotkeysOptions) {
description: 'Go to latest message',
keyDownHandler: () => {
options.selection.clear();
- options.navigation()?.markUserIntent('down');
options.onGoToBottom();
return true;
},
@@ -201,8 +198,7 @@ export function createChannelHotkeys(options: CreateChannelHotkeysOptions) {
keyDownHandler: () => {
const id = options.selection.selectPrevious();
if (id) {
- options.navigation()?.markUserIntent('up');
- options.navigation()?.scrollToId(id, { align: 'nearest' });
+ options.scrollToMessage(id, { align: 'auto', userIntent: 'up' });
messageListEl?.focus();
}
return true;
diff --git a/apps/web/src/features/channel/Channel/create-channel-keyboard-handler.ts b/apps/web/src/features/channel/Channel/create-channel-keyboard-handler.ts
index b84522933a..889979373b 100644
--- a/apps/web/src/features/channel/Channel/create-channel-keyboard-handler.ts
+++ b/apps/web/src/features/channel/Channel/create-channel-keyboard-handler.ts
@@ -1,18 +1,11 @@
import { FloatRegions } from '@components/app/mobile/float-regions/float-region-state';
import { virtualKeyboardHeight } from '@core/mobile/virtualKeyboard';
import { isPlatform } from '@core/util/platform';
-import {
- type Accessor,
- createEffect,
- createSignal,
- on,
- onCleanup,
-} from 'solid-js';
+import { type Accessor, createMemo, onCleanup, onMount } from 'solid-js';
import { scrollMessageAboveKeyboard } from '../scroll-utils';
-import type { ThreadListNavigation } from './ThreadList';
type CreateChannelKeyboardHandlerOptions = {
- navigation: Accessor<ThreadListNavigation | undefined>;
+ scrollToLatest: () => void;
/**
* Whether the user is near the bottom of the message list. ThreadList
* re-emits this on viewport resizes, so it stays fresh across keyboard
@@ -49,23 +42,20 @@ export function createChannelKeyboardHandler(
): void {
if (!isPlatform('ios')) return;
- // The pending reveal mirrors the binding (rather than being requested by
- // each bind site): new bind flows get the reveal for free, an unbind
- // clears any not-yet-consumed request, and — because the mirror is
- // synchronous — a consumed request is always the current binding.
- const [pendingTargetReveal, setPendingTargetReveal] = createSignal<string>();
- createEffect(
- on(options.boundMessageId, (messageId) => setPendingTargetReveal(messageId))
- );
+ // Each binding gets one keyboard reveal. The memo provides identity for a
+ // new binding, including unbind/rebind, without an effect mirroring its ID.
+ const binding = createMemo(() => ({ messageId: options.boundMessageId() }));
+ let revealedBinding: ReturnType<typeof binding> | undefined;
/**
* Consume a pending reveal. Returns whether the reveal owned this keyboard
* appearance (even if the bound message was already fully visible).
*/
const revealPendingTarget = (): boolean => {
- const messageId = pendingTargetReveal();
- if (!messageId) return false;
- setPendingTargetReveal(undefined);
+ const current = binding();
+ const messageId = current.messageId;
+ if (!messageId || current === revealedBinding) return false;
+ revealedBinding = current;
scrollMessageAboveKeyboard(
messageId,
virtualKeyboardHeight() + FloatRegions.hostHeight()
@@ -73,11 +63,11 @@ export function createChannelKeyboardHandler(
return true;
};
- createEffect(() => {
+ onMount(() => {
const handleKeyboardWillShow = () => {
// A bound-target reveal owns the scroll for this keyboard appearance.
if (revealPendingTarget()) return;
- if (options.isNearBottom()) options.navigation()?.scrollToBottom();
+ if (options.isNearBottom()) options.scrollToLatest();
};
window.addEventListener('keyboardWillShow', handleKeyboardWillShow);
onCleanup(() => {
diff --git a/apps/web/src/features/channel/Channel/create-scroll-lifecycle.ts b/apps/web/src/features/channel/Channel/create-scroll-lifecycle.ts
new file mode 100644
index 0000000000..cb966a8e2f
--- /dev/null
+++ b/apps/web/src/features/channel/Channel/create-scroll-lifecycle.ts
@@ -0,0 +1,64 @@
+import { createSignal } from 'solid-js';
+import { match } from 'ts-pattern';
+
+type ScrollPhase =
+ | 'waiting-for-layout'
+ | 'waiting-for-element'
+ | 'ready'
+ | 'disposed';
+type ScrollEvent =
+ | 'layout'
+ | 'navigate'
+ | 'user-scroll'
+ | 'timeout'
+ | 'dispose';
+
+/** Owns initial positioning and its cancellation; geometry stays in TanStack. */
+export function createScrollLifecycle(options: {
+ hasLayout: () => boolean;
+ waitForElement: boolean;
+ positionInitial: () => void;
+ positionFallback: () => void;
+ onReady: () => void;
+}) {
+ const [phase, setPhase] = createSignal<ScrollPhase>('waiting-for-layout');
+ let fallback: ReturnType<typeof setTimeout> | undefined;
+
+ const transition = (next: ScrollPhase) => {
+ clearTimeout(fallback);
+ fallback = undefined;
+ setPhase(next);
+ };
+
+ const send = (event: ScrollEvent): void => {
+ if (phase() === 'disposed') return;
+ match(event)
+ .with('layout', () => {
+ if (phase() !== 'waiting-for-layout' || !options.hasLayout()) return;
+ if (options.waitForElement) {
+ transition('waiting-for-element');
+ fallback = setTimeout(() => send('timeout'), 1500);
+ } else {
+ transition('ready');
+ options.positionInitial();
+ }
+ options.onReady();
+ })
+ .with('navigate', 'user-scroll', () => {
+ if (phase() === 'waiting-for-element') transition('ready');
+ })
+ .with('timeout', () => {
+ if (phase() !== 'waiting-for-element') return;
+ transition('ready');
+ options.positionFallback();
+ })
+ .with('dispose', () => transition('disposed'))
+ .exhaustive();
+ };
+
+ return {
+ send,
+ isReady: () => phase() === 'ready' || phase() === 'waiting-for-element',
+ isDisposed: () => phase() === 'disposed',
+ };
+}
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 f3dc8bd5e6..0f8815fd4b 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
@@ -5,7 +5,6 @@ import {
import { queryClient } from '@queries/client';
import { type Accessor, createEffect, on, onCleanup } from 'solid-js';
import { createStore } from 'solid-js/store';
-import type { ThreadListNavigation } from './ThreadList';
/**
* How long a navigation target keeps its accent highlight after its scroll
@@ -20,16 +19,8 @@ type CreateTargetMessageControllerOptions = {
initialTargetMessageId?: string | undefined;
initialTargetMessageReplyId?: string | undefined;
messageKeys: Accessor<string[]>;
- navigation: Accessor<ThreadListNavigation | undefined>;
- /**
- * Whether the ThreadList has completed its initial scroll.
- *
- * The controller defers pending scroll execution until this returns `true`
- * so that a `goToMessage` call that fires while the initial scroll is still
- * in progress does not get overridden by the initial-scroll retry logic
- * inside ThreadList.
- */
- didInitialScroll: Accessor<boolean>;
+ /** The list publishes its handle after initial layout and positioning. */
+ isReady: Accessor<boolean>;
};
export type TargetMessageController = ReturnType<
@@ -138,23 +129,14 @@ export function createTargetMessageController(
createEffect(
on(
[
- options.navigation,
+ options.isReady,
() => targetMessageData['pendingScrollTargetId'],
options.messageKeys,
- options.didInitialScroll,
],
- ([navigation, pendingTargetId, , didInitialScroll]) => {
- if (!navigation || !pendingTargetId) return;
+ ([isReady, pendingTargetId]) => {
+ if (!isReady || !pendingTargetId) return;
if (!hasMessageLoaded(pendingTargetId)) return;
- // Defer the scroll until the ThreadList has completed its initial
- // scroll. This prevents a goToMessage call from being overridden by
- // the initial-scroll retry logic in ThreadList's handleScrollEnd,
- // which validates position against the *original* scroll target.
- // The pending target stays queued; once didInitialScroll flips to
- // true the effect re-fires and executes the scroll.
- if (!didInitialScroll) 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
diff --git a/apps/web/src/features/channel/Channel/sticky-scroll.tsx b/apps/web/src/features/channel/Channel/sticky-scroll.tsx
deleted file mode 100644
index 51aabeafa2..0000000000
--- a/apps/web/src/features/channel/Channel/sticky-scroll.tsx
+++ /dev/null
@@ -1,46 +0,0 @@
-import type { ApiChannelMessage } from '@service-storage/generated/schemas/apiChannelMessage';
-import { type Accessor, createEffect, on } from 'solid-js';
-
-function isNearTrueBottom(
- isNearBottom: boolean,
- hasMoreBelow: boolean
-): boolean {
- return isNearBottom && !hasMoreBelow;
-}
-
-function didInsertMessageOnBottom(
- currentMessages: Array<ApiChannelMessage>,
- previousMessages: Array<ApiChannelMessage> | undefined
-): boolean {
- if (!previousMessages) return false;
- const lastCurrentMessage = currentMessages.at(-1);
- const lastPreviousMessage = previousMessages.at(-1);
- if (!lastCurrentMessage || !lastPreviousMessage) return false;
- return lastCurrentMessage.id !== lastPreviousMessage.id;
-}
-
-export type StickyScrollerProps = {
- isNearBottom: Accessor<boolean>;
- hasMoreBelow: Accessor<boolean>;
- messages: Accessor<Array<ApiChannelMessage>>;
- scrollToBottom: () => void;
-};
-
-export function createStickyScrollEffect(props: StickyScrollerProps) {
- createEffect(
- on(
- props.messages,
- (currentMessages, previousMessage) => {
- if (
- didInsertMessageOnBottom(currentMessages, previousMessage) &&
- isNearTrueBottom(props.isNearBottom(), props.hasMoreBelow())
- ) {
- props.scrollToBottom();
- }
- },
- {
- defer: true,
- }
- )
- );
-}
diff --git a/apps/web/src/features/channel/Channel/tests/create-channel-hotkeys.test.tsx b/apps/web/src/features/channel/Channel/tests/create-channel-hotkeys.test.tsx
index c14c29ca1e..8707c6701c 100644
--- a/apps/web/src/features/channel/Channel/tests/create-channel-hotkeys.test.tsx
+++ b/apps/web/src/features/channel/Channel/tests/create-channel-hotkeys.test.tsx
@@ -58,7 +58,7 @@ function ChannelEditHarness(props: {
selectPrevious: vi.fn(),
selectNext: vi.fn(),
},
- navigation: () => undefined,
+ scrollToMessage: () => false,
messageById: () =>
new Map([[originalMessage.id, originalMessage as ApiChannelMessage]]),
getMessageActions: () => ({
diff --git a/apps/web/src/features/channel/Channel/tests/create-scroll-lifecycle.test.ts b/apps/web/src/features/channel/Channel/tests/create-scroll-lifecycle.test.ts
new file mode 100644
index 0000000000..7d9f661f06
--- /dev/null
+++ b/apps/web/src/features/channel/Channel/tests/create-scroll-lifecycle.test.ts
@@ -0,0 +1,30 @@
+import { createRoot } from 'solid-js';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { createScrollLifecycle } from '../create-scroll-lifecycle';
+
+afterEach(() => vi.useRealTimers());
+
+describe('initial scroll lifecycle', () => {
+ it.each(['navigate', 'user-scroll', 'dispose'] as const)(
+ '%s permanently cancels a pending element fallback',
+ (event) => {
+ vi.useFakeTimers();
+ createRoot((dispose) => {
+ const positionFallback = vi.fn();
+ const lifecycle = createScrollLifecycle({
+ hasLayout: () => true,
+ waitForElement: true,
+ positionInitial: vi.fn(),
+ positionFallback,
+ onReady: vi.fn(),
+ });
+ lifecycle.send('layout');
+ lifecycle.send(event);
+ vi.advanceTimersByTime(2000);
+ lifecycle.send('layout');
+ expect(positionFallback).not.toHaveBeenCalled();
+ dispose();
+ });
+ }
+ );
+});
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 a243b18491..3690ee60b4 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
@@ -27,7 +27,6 @@ function createController(
initialTargetMessageId: string;
initialTargetMessageReplyId: string;
messageKeys: string[];
- scrollToId: (messageId: string) => boolean;
withNavigation: boolean;
didInitialScroll: boolean;
}>
@@ -37,34 +36,12 @@ function createController(
input?.didInitialScroll ?? false
);
- const scrollToId =
- input?.scrollToId ??
- (() => {
- return true;
- });
-
const controller = createTargetMessageController({
channelId: () => input?.channelId ?? 'channel-1',
initialTargetMessageId: input?.initialTargetMessageId,
initialTargetMessageReplyId: input?.initialTargetMessageReplyId,
messageKeys,
- navigation: () =>
- input?.withNavigation
- ? {
- scrollTo: () => false,
- scrollToIndex: () => false,
- scrollByDelta: () => false,
- scrollToTop: () => false,
- scrollToBottom: () => false,
- scrollToId,
- navigatePrevious: () => false,
- navigateNext: () => false,
- isNearBottom: () => true,
- scrollToElementInItem: () => true,
- markUserIntent: () => {},
- }
- : undefined,
- didInitialScroll,
+ isReady: () => !!input?.withNavigation && didInitialScroll(),
});
return {
@@ -107,7 +84,6 @@ 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>;
@@ -117,7 +93,6 @@ describe('createTargetMessageController', () => {
initialTargetMessageId: 'message-1',
initialTargetMessageReplyId: 'reply-4',
messageKeys: ['message-1'],
- scrollToId,
withNavigation: true,
didInitialScroll: true,
}).controller;
@@ -125,7 +100,6 @@ describe('createTargetMessageController', () => {
await Promise.resolve();
- expect(scrollToId).not.toHaveBeenCalled();
expect(controller!.pendingScrollTargetId()).toBeUndefined();
expect(controller!.pendingTargetReplyId()).toBe('reply-4');
// The outer row is acknowledged early so the reply can scroll itself, but
@@ -140,7 +114,6 @@ describe('createTargetMessageController', () => {
});
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>;
@@ -149,7 +122,6 @@ describe('createTargetMessageController', () => {
controller = createController({
initialTargetMessageId: 'message-1',
messageKeys: ['message-1'],
- scrollToId,
withNavigation: true,
didInitialScroll: true,
}).controller;
@@ -157,7 +129,6 @@ describe('createTargetMessageController', () => {
await Promise.resolve();
- expect(scrollToId).not.toHaveBeenCalled();
expect(controller!.pendingScrollTargetId()).toBe('message-1');
controller!.completePendingScroll('message-1');
diff --git a/apps/web/src/features/channel/Channel/tests/thread-list-scroll.test.ts b/apps/web/src/features/channel/Channel/tests/thread-list-scroll.test.ts
index f42a0dd0b8..6440b41f65 100644
--- a/apps/web/src/features/channel/Channel/tests/thread-list-scroll.test.ts
+++ b/apps/web/src/features/channel/Channel/tests/thread-list-scroll.test.ts
@@ -1,7 +1,45 @@
import { createScrollIntentTracker } from '@core/util/scroll-intent';
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
+
+function scrollSurface(onUserIntent: () => void) {
+ const tracker = createScrollIntentTracker(onUserIntent);
+ const element = document.createElement('div');
+ for (const [name, handler] of Object.entries(tracker.handlers)) {
+ element.addEventListener(
+ name.slice(2).toLowerCase(),
+ handler as EventListener
+ );
+ }
+ const dispatch = (type: string, properties: Record<string, unknown> = {}) =>
+ element.dispatchEvent(Object.assign(new Event(type), properties));
+ return { tracker, dispatch };
+}
describe('createScrollIntentTracker', () => {
+ it('does not cancel navigation for a touch tap with small finger movement', () => {
+ const onUserIntent = vi.fn();
+ const { dispatch } = scrollSurface(onUserIntent);
+ dispatch('pointerdown', { pointerType: 'touch', clientY: 100 });
+ dispatch('touchmove', { touches: [{ clientY: 98 }] });
+ dispatch('pointerup', { pointerType: 'touch' });
+ dispatch('touchend');
+ expect(onUserIntent).not.toHaveBeenCalled();
+ });
+
+ it('tracks a native touch drag after the browser cancels pointer events', () => {
+ const onUserIntent = vi.fn();
+ const { tracker, dispatch } = scrollSurface(onUserIntent);
+ dispatch('pointerdown', { pointerType: 'touch', clientY: 100 });
+ // Native panning cancels Pointer Events; Touch Events continue until lift.
+ dispatch('pointercancel', { pointerType: 'touch' });
+ dispatch('touchmove', { touches: [{ clientY: 75 }] });
+ expect(onUserIntent).toHaveBeenCalledOnce();
+ expect(tracker.lastDirection()).toBe('down');
+ expect(tracker.isUserInteracting(Date.now() + 1000)).toBe(true);
+ dispatch('touchend');
+ expect(tracker.isUserInteracting(Date.now() + 1000)).toBe(false);
+ });
+
it('is not interacting by default', () => {
const tracker = createScrollIntentTracker();
expect(tracker.isUserInteracting()).toBe(false);
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
index 3ba077f608..12bc8b261e 100644
--- a/apps/web/src/features/channel/Thread/create-target-reply-scroller.ts
+++ b/apps/web/src/features/channel/Thread/create-target-reply-scroller.ts
@@ -212,7 +212,7 @@ export function createTargetReplyScroller(options: {
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
+ // observers is not a safe contract. Defer to a microtask so the virtualizer's
// sibling observer has applied the new item geometry before we position
// against it, while still correcting before the browser can paint.
if (!measurementMicrotaskQueued) {
@@ -232,7 +232,7 @@ export function createTargetReplyScroller(options: {
measurementTimerId = undefined;
}
- // Virtua may commit a corrected item range in the first frame after a
+ // The virtualizer 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(() => {
diff --git a/apps/web/src/features/channel/docs/sticky-scrolling.md b/apps/web/src/features/channel/docs/sticky-scrolling.md
index 0fa31e7a1c..3ce15ed85d 100644
--- a/apps/web/src/features/channel/docs/sticky-scrolling.md
+++ b/apps/web/src/features/channel/docs/sticky-scrolling.md
@@ -1,9 +1,54 @@
-# Sticky Scrolling
+# Channel scrolling
-"Sticky Scrolling" in channels is a mechanism that should keep the content relating to the bottom-most (no remaining pagination) of a channel in view.
+`Channel/ThreadList.tsx` uses TanStack Solid Virtual with `anchorTo: 'end'` and
+stable message IDs. The virtualizer owns prepend anchoring, following new rows,
+and compensation when measured messages grow or shrink. `followOnAppend` is
+only enabled when the query includes the newest page. Reading older history
+must never be interrupted by incoming messages.
-The following are cases where sticky scrolling should be applied.
+The list exposes three navigation operations: `scrollToLatest`, `scrollToMessage`,
+and `scrollToElement`. Message navigation can include keyboard intent for pagination.
+`initialPosition` chooses latest, a mounted target, or a saved snapshot; these are mutually exclusive. `onReady` publishes the handle after the
+first measured layout and can return a cleanup to release it on unmount.
-1. I am at the bottom of a channel (approximately) within some threshold. I receive a new message, either from myself or from another user, that message should be in view. To accomplish this we need to scroll down to the newest message.
-2. I am at the bottom of a channel, I or anyone else in the channel react to the latest message, I should be scrolled slightly so that reaction is in view.
-3. I am at the bottom of a channel, I hit "reply" on the latest message. The entirety of the reply input box should be visible to me.
+`createScrollLifecycle` owns initial positioning: waiting for layout → waiting for
+an element or ready → disposed. Layout notifications advance it in the measurement
+microtask. Element positioning, a newer navigation, or a user scroll cancels the
+fallback permanently. There is no effect watching an initial-scroll boolean.
+`Channel` keeps one pending latest request while the query loads and the rendered
+list catches up. A message navigation or user scroll cancels it; stale request
+completions cannot move the viewport. A pagination error still permits navigation
+within retained messages. `onScroll` publishes state and a snapshot captured
+together before callers can start another navigation, and attempts the pending
+latest request against that layout.
+The remaining list effects bridge changing insets and row indexes to DOM measurement.
+
+The virtualizer stays disabled while the message index is empty, so it evaluates
+the initial bottom offset against the first loaded page instead of caching zero.
+Saved sizes also seed that offset, keeping the first rendered range at latest in
+channels whose measured rows are much taller than the default estimate.
+Mounted rows read their current DOM height synchronously, including when restoring
+saved measurements. Initial navigation to latest runs after those measurements in
+a microtask before paint. Using cached heights until ResizeObserver fires exposes
+the wrong bottom position, even when the scrollbar is already at its end. History
+uses `initialOffset`; replaying the saved offset after measuring would discard the
+anchor corrections for changed rows.
+
+Rows are positioned inside one sizer that includes the floating header/composer
+insets. Short conversations are bottom aligned. Before TanStack writes a scroll
+correction, `scrollToFn` synchronously commits the current total to the sizer;
+otherwise a growing last row can clamp the scroll against the old DOM extent.
+Viewport and inset changes explicitly scroll to the end only if previously pinned.
+The offset observer distinguishes instant programmatic scrolls from user scrolling,
+so iOS does not replay deferred momentum adjustments after a navigation has already
+accounted for those measurements. Actual touch/momentum deferral remains in the core.
+
+Message IDs also key Solid's rendered components, preserving editors and expanded
+threads across pagination. `Key` owns each row's virtual-item accessor; a shared
+map lookup can disappear while a queued measurement effect is still running.
+Measurement effects track index changes only, leaving size changes to ResizeObserver.
+`targetId` keeps the pending thread mounted for precise navigation to nested replies;
+only the list translates that ID into a virtual index. Snapshot
+restoration pairs the offset with `takeSnapshot()`.
+Pagination callbacks require user scroll intent; measurement corrections alone
+must not fetch more history.
diff --git a/apps/web/src/lib/core/util/scroll-intent.ts b/apps/web/src/lib/core/util/scroll-intent.ts
index a46154a843..25be124633 100644
--- a/apps/web/src/lib/core/util/scroll-intent.ts
+++ b/apps/web/src/lib/core/util/scroll-intent.ts
@@ -4,6 +4,7 @@ import type { JSX } from 'solid-js';
* 300 ms gives async virtualizer scrolls (e.g. from hotkey-driven `scrollToId`)
* enough time to fire, even on slower devices or busy main threads. */
const INTERACTION_TIMEOUT_MS = 300;
+const TOUCH_DRAG_THRESHOLD_PX = 6;
export type ScrollDirection = 'up' | 'down';
@@ -29,6 +30,9 @@ type ScrollIntentHandlers = {
onPointerDown: JSX.EventHandlerUnion<HTMLElement, PointerEvent>;
onPointerUp: JSX.EventHandlerUnion<HTMLElement, PointerEvent>;
onPointerCancel: JSX.EventHandlerUnion<HTMLElement, PointerEvent>;
+ onTouchMove: JSX.EventHandlerUnion<HTMLElement, TouchEvent>;
+ onTouchEnd: JSX.EventHandlerUnion<HTMLElement, TouchEvent>;
+ onTouchCancel: JSX.EventHandlerUnion<HTMLElement, TouchEvent>;
onWheel: JSX.EventHandlerUnion<HTMLElement, WheelEvent>;
onKeyDown: JSX.EventHandlerUnion<HTMLElement, KeyboardEvent>;
};
@@ -41,7 +45,8 @@ const SCROLL_DOWN_KEYS = new Set(['ArrowDown', 'PageDown', 'End', ' ']);
* events from programmatic / virtualizer-driven ones.
*
* User interaction is detected via:
- * - `pointerdown` / `pointerup` — covers scrollbar drag and touch drag
+ * - Pointer events — covers scrollbar drag
+ * - Touch movement — covers finger drag without treating taps as navigation
* - `wheel` — covers mouse wheel / trackpad
* - `keydown` — covers native browser keyboard scrolling (Arrow, Page, Home/End, Space)
* - `markUserIntent()` — for external callers (e.g. hotkey-driven `scrollToId`)
@@ -61,14 +66,18 @@ const SCROLL_DOWN_KEYS = new Set(['ArrowDown', 'PageDown', 'End', ' ']);
* }
* ```
*/
-export function createScrollIntentTracker(): ScrollIntentTracker {
+export function createScrollIntentTracker(
+ onUserIntent?: () => void
+): ScrollIntentTracker {
let isPointerDown = false;
+ let touchY: number | undefined;
let activeUntil = 0;
let direction: ScrollDirection | undefined;
const markUserIntent = (dir: ScrollDirection) => {
direction = dir;
activeUntil = Math.max(activeUntil, Date.now() + INTERACTION_TIMEOUT_MS);
+ onUserIntent?.();
};
const isUserInteracting = (now = Date.now()) =>
@@ -78,6 +87,7 @@ export function createScrollIntentTracker(): ScrollIntentTracker {
isUserInteracting(now) ? direction : undefined;
const endPointer = () => {
+ touchY = undefined;
if (!isPointerDown) return;
isPointerDown = false;
activeUntil = Math.max(activeUntil, Date.now() + INTERACTION_TIMEOUT_MS);
@@ -85,9 +95,9 @@ export function createScrollIntentTracker(): ScrollIntentTracker {
const handlers: ScrollIntentHandlers = {
onPointerDown: (event) => {
- // Touch interactions always indicate scroll intent (finger drag)
if (event.pointerType === 'touch') {
isPointerDown = true;
+ touchY = event.clientY;
return;
}
// For mouse/pen, only track scrollbar drags. Scrollbar clicks
@@ -97,10 +107,24 @@ export function createScrollIntentTracker(): ScrollIntentTracker {
// interactions within the scroll container.
if (event.target === event.currentTarget) {
isPointerDown = true;
+ onUserIntent?.();
}
},
onPointerUp: endPointer,
- onPointerCancel: endPointer,
+ onPointerCancel: (event) => {
+ // Native touch scrolling cancels pointer events before the drag ends.
+ if (event.pointerType !== 'touch') endPointer();
+ },
+ onTouchMove: (event) => {
+ const touch = event.touches[0];
+ if (touchY === undefined || !touch) return;
+ const delta = touchY - touch.clientY;
+ if (Math.abs(delta) < TOUCH_DRAG_THRESHOLD_PX) return;
+ touchY = touch.clientY;
+ markUserIntent(delta > 0 ? 'down' : 'up');
+ },
+ onTouchEnd: endPointer,
+ onTouchCancel: endPointer,
onWheel: (event) => {
if (event.deltaY === 0) return;
markUserIntent(event.deltaY > 0 ? 'down' : 'up');
diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json
index b258f77517..dcf03cd754 100644
--- a/apps/web/tsconfig.json
+++ b/apps/web/tsconfig.json
@@ -47,12 +47,6 @@
"@sandbox-sizes": [
"../../crates/agent_harness/sandbox_sizes.json"
],
- "loro-crdt": [
- "../../node_modules/loro-crdt"
- ],
- "loro-crdt/*": [
- "../../node_modules/loro-crdt/*"
- ],
"@graphql-cache/*": [
"./src/lib/graphql-cache/*"
],
diff --git a/apps/web/vite.base.ts b/apps/web/vite.base.ts
index 06b6be950b..1d1ac78f12 100644
--- a/apps/web/vite.base.ts
+++ b/apps/web/vite.base.ts
@@ -180,6 +180,9 @@ export const createAppViteConfig = (): UserConfigFn => {
// NIX_TAURI_ALIAS
],
dedupe: [
+ // Keep Loro resolution here: tsconfig path aliases cache a versioned
+ // URL that goes stale when Vite rebuilds dependencies, splitting the
+ // app and workspace packages across separate WASM instances.
'loro-crdt',
'solid-js',
'@codingame/monaco-vscode-api',
diff --git a/bun.lock b/bun.lock
index a3144152f5..8801c3bb01 100644
--- a/bun.lock
+++ b/bun.lock
@@ -67,7 +67,7 @@
"@tailwindcss/vite": "^4.2.4",
"@tanstack/pacer": "^0.17.3",
"@tanstack/solid-query": "5.90.3",
- "@tanstack/solid-virtual": "^3.13.13",
+ "@tanstack/solid-virtual": "3.13.37",
"@tauri-apps/api": "^2.8.0",
"@tauri-apps/plugin-haptics": "~2",
"@tauri-apps/plugin-http": "~2.5.8",
@@ -1545,11 +1545,11 @@
"@tanstack/solid-query": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/query-core": "5.90.2" }, "peerDependencies": { "solid-js": "^1.6.0" } }, "sha512-XEP+fzZYes+GLA4HSvmitj2NCC7o9iwMvwdkI5R7YSQD08jd1rA9p4KUYWvcu8VfMD+jodOCn/iMHmPz8zV3qw=="],
- "@tanstack/solid-virtual": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/virtual-core": "3.17.7" }, "peerDependencies": { "solid-js": "^1.3.0" } }, "sha512-9x4Eg3M+t7cY0/lswB6JnK1C/3YcsdBttUYQgSre+5zcwVJMZnp0Gy3mT++jeSN1bi7M5pxUPnAVoD1YE9DuLQ=="],
+ "@tanstack/solid-virtual": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/virtual-core": "3.17.8" }, "peerDependencies": { "solid-js": "^1.3.0" } }, "sha512-RxJC8n/6nnFHcPvDGMg7ZkqSzCVUco4JNw3ctIChj1HjoKs5I9wt5nsU+DUVtMVEiMfizUxOAx4TPIN8SHjxUQ=="],
"@tanstack/store": ["@tanstack/[email protected]", "", {}, "sha512-PtOisLjUZPz5VyPRSCGjNOlwTvabdTBQ2K80DpVL1chGVr35WRxfeavAPdNq6pm/t7F8GhoR2qtmkkqtCEtHYw=="],
- "@tanstack/virtual-core": ["@tanstack/[email protected]", "", {}, "sha512-bp+v10y65sp2H7WpWfIMyxTNfl8ZVfxFTLRjPIFRryi6FV/J33z4IS53WO4pTk36KlvJ4iLiQz+oaydDC1xbcA=="],
+ "@tanstack/virtual-core": ["@tanstack/[email protected]", "", {}, "sha512-BfEvehNpOT75r5Ksc5xW6NZuXujTfb7nlSEyVu4XHG3gdxNg1KqXruWbDewXOUaUYIo4oRbSfkjIajz4MAT8tA=="],
"@tauri-apps/api": ["@tauri-apps/[email protected]", "", {}, "sha512-M2FPuYND2m+wh5hfW9ZpSdxMPdEJovPBWwoHJmwUpysTYNHaOkVFN419m/K0LIgjb/7KU2vBgsUepJWugQCvAA=="],
diff --git a/docs/AGENT_GUIDE/channels.md b/docs/AGENT_GUIDE/channels.md
index 1513e03144..47f1c7ef8d 100644
--- a/docs/AGENT_GUIDE/channels.md
+++ b/docs/AGENT_GUIDE/channels.md
@@ -46,6 +46,26 @@ an agent session; follow-up
Agent replies may contain mention chips (`<m-document-mention>`) that render like any
other channel mention.
+## Message scrolling and navigation
+
+Channels open at the latest message, with short conversations aligned above the
+composer. Incoming messages and growing replies stay in view while the channel is
+at the bottom. Scrolling up leaves the viewport on the history being read; loading
+older messages preserves that message's position.
+
+Message and reply links reveal the target inside its thread. Keyboard message
+navigation scrolls only when the selected message is outside the usable viewport.
+Returning through split navigation restores the saved message position and expanded
+threads. Switching channel tabs currently opens Messages at latest. The `Scroll to bottom` control appears when scrolling down through history;
+it returns to the latest page even after opening a link into old history.
+The jump waits for that page to reach the rendered list.
+A newer message navigation cancels a pending jump to latest. Scrolling manually
+or choosing another destination also cancels the initial target's delayed fallback.
+A touch tap leaves pending navigation intact; a vertical finger drag cancels it.
+
+The `[data-channel-scroll]` element is the scroll surface. Its virtualized rows are
+keyed by message ID; offscreen rows are normally absent from the DOM.
+
## Channel tabs
Radio group at the top of the channel pane: `Messages` / `Attachments` / `Participants`,
diff --git a/nix-support/node_modules-hashes.json b/nix-support/node_modules-hashes.json
index 64ee753ebe..22293fc4d9 100644
--- a/nix-support/node_modules-hashes.json
+++ b/nix-support/node_modules-hashes.json
@@ -1,6 +1,6 @@
{
"nodeModules": {
- "aarch64-darwin": "sha256-NXjiNsnz379tBD66IOcU8Mp01Aq/lVPTPfVsg2Yfmlk=",
- "x86_64-linux": "sha256-OtORVfsX/AToOwqELPlXFtsfH51Styrf0LiX1Ehe3cA="
+ "aarch64-darwin": "sha256-ohCQ11PshvU/hmw6O7yUOZtNJsphatspcyBC8HIJVKM=",
+ "x86_64-linux": "sha256-VJwakjUe4C5jZhfwEvecmuyGuX/c/7ZriEMIUD1gV2A="
}
}