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(new-channels): scroll jankyness, thread stability improvements (#2110)

teo8d92ff12da30
diff --git a/js/app/packages/channel/Channel/Channel.tsx b/js/app/packages/channel/Channel/Channel.tsx
index 6eb466cdae..4453eca0fc 100644
--- a/js/app/packages/channel/Channel/Channel.tsx
+++ b/js/app/packages/channel/Channel/Channel.tsx
@@ -10,7 +10,6 @@ import {
on,
onMount,
Show,
- Suspense,
type Accessor,
} from 'solid-js';
import { useBeforeLeave } from '@solidjs/router';
@@ -67,6 +66,7 @@ import {
useRemoveReactionMutation,
} from '@queries/channel/reaction';
import { resetKeyboardModality } from './util';
+import { DebugSuspense } from '@channel/DebugSuspense';
import { useChannelParticipants } from '@channel/use-channel-participants';
type ChannelProps = {
@@ -251,7 +251,7 @@ export function Channel(props: ChannelProps) {
);
return (
- <Suspense>
+ <DebugSuspense name="Channel.root">
<StaticMarkdownContext>
<ChannelDropZone dragState={dragState}>
<Show when={messages().length > 0}>
@@ -330,7 +330,7 @@ export function Channel(props: ChannelProps) {
/>
</div>
</Show>
- <Suspense>
+ <DebugSuspense name="Channel.input">
<div class="pb-2 w-full flex justify-center" ref={attachInputRef}>
<ChannelInput
input={{
@@ -352,9 +352,9 @@ export function Channel(props: ChannelProps) {
onSend={onSend}
/>
</div>
- </Suspense>
+ </DebugSuspense>
</ChannelDropZone>
</StaticMarkdownContext>
- </Suspense>
+ </DebugSuspense>
);
}
diff --git a/js/app/packages/channel/Channel/ThreadList.tsx b/js/app/packages/channel/Channel/ThreadList.tsx
index 3d1901e0fd..5233e55364 100644
--- a/js/app/packages/channel/Channel/ThreadList.tsx
+++ b/js/app/packages/channel/Channel/ThreadList.tsx
@@ -1,6 +1,10 @@
import { type Accessor, type JSX, createSignal } from 'solid-js';
import { type VirtualizerHandle, Virtualizer } from 'virtua/solid';
import type { ScrollToIndexOpts } from 'virtua/unstable_core';
+import {
+ createScrollIntentTracker,
+ type ScrollDirection,
+} from '@core/util/scroll-intent';
type ScrollAlignment = ScrollToIndexOpts['align'];
@@ -32,6 +36,13 @@ export type ThreadListNavigation = {
navigatePrevious: () => boolean;
navigateNext: () => boolean;
isNearBottom: () => 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;
};
export type ThreadListScrollState = {
@@ -57,15 +68,8 @@ type ThreadListProps = {
const NEAR_TOP_THRESHOLD = 800;
const NEAR_BOTTOM_THRESHOLD = 50;
-const EXPLICIT_SCROLL_INTENT_WINDOW_MS = 250;
const EXPLICIT_SCROLL_DOWN_TRIGGER_DISTANCE = 64;
-type ScrollDirection = 'up' | 'down';
-type ExplicitScrollIntent = {
- direction: ScrollDirection;
- at: number;
-};
-
export const DEFAULT_INITIAL_SCROLL_TARGET: ThreadListScrollTarget = {
tag: 'bottom',
align: 'end',
@@ -74,31 +78,6 @@ export const DEFAULT_INITIAL_SCROLL_TARGET: ThreadListScrollTarget = {
const clamp = (value: number, min: number, max: number) =>
Math.max(min, Math.min(value, max));
-export function isExplicitScrollDown(
- delta: number,
- intent: ExplicitScrollIntent | undefined,
- now = Date.now()
-): boolean {
- if (delta <= 0) return false;
- if (!intent) return false;
- if (intent.direction !== 'down') return false;
- return now - intent.at <= EXPLICIT_SCROLL_INTENT_WINDOW_MS;
-}
-
-export function accumulateExplicitScrollDownDistance(
- previousDistance: number,
- delta: number,
- intent: ExplicitScrollIntent | undefined,
- now = Date.now()
-): number {
- if (!isExplicitScrollDown(delta, intent, now)) return 0;
- return previousDistance + delta;
-}
-
-export function hasExplicitScrollDownGesture(distance: number): boolean {
- return distance >= EXPLICIT_SCROLL_DOWN_TRIGGER_DISTANCE;
-}
-
export function getTargetAlign(
target: ThreadListScrollTarget
): ScrollAlignment {
@@ -123,16 +102,9 @@ export function ThreadList(props: ThreadListProps) {
let nearTopFired = false;
let nearBottomFired = false;
let previousScrollOffset: number | undefined;
- let explicitScrollIntent: ExplicitScrollIntent | undefined;
let explicitScrollDownDistance = 0;
- let previousTouchY: number | undefined;
- const markExplicitScrollIntent = (direction: ScrollDirection) => {
- explicitScrollIntent = {
- direction,
- at: Date.now(),
- };
- };
+ const scrollIntent = createScrollIntentTracker();
const resolveTargetIndex = (target: ThreadListScrollTarget): number => {
const keys = props.keys();
@@ -227,6 +199,8 @@ export function ThreadList(props: ThreadListProps) {
},
isNearBottom,
+
+ markUserIntent: scrollIntent.markUserIntent,
});
function scrollOnMount(handle: VirtualizerHandle) {
@@ -258,28 +232,39 @@ export function ThreadList(props: ThreadListProps) {
if (previousScrollOffset !== undefined) {
const delta = handle.scrollOffset - previousScrollOffset;
- explicitScrollDownDistance = accumulateExplicitScrollDownDistance(
- explicitScrollDownDistance,
- delta,
- explicitScrollIntent
- );
- nextIsScrollingDown = hasExplicitScrollDownGesture(
- explicitScrollDownDistance
- );
+ // 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);
if (!didInitialScroll()) return;
- if (nearTop && !nearTopFired) {
+ // 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();
+
+ if (nearTop && !nearTopFired && hasUserIntent) {
nearTopFired = true;
props.onScrollNearTop?.();
} else if (!nearTop) {
nearTopFired = false;
}
- if (nearBottom && !nearBottomFired) {
+ if (nearBottom && !nearBottomFired && hasUserIntent) {
nearBottomFired = true;
props.onScrollNearBottom?.();
} else if (!nearBottom) {
@@ -290,29 +275,7 @@ export function ThreadList(props: ThreadListProps) {
return (
<div
ref={scrollRef}
- onWheel={(event) => {
- if (event.deltaY === 0) return;
- markExplicitScrollIntent(event.deltaY > 0 ? 'down' : 'up');
- }}
- onTouchStart={(event) => {
- previousTouchY = event.touches.item(0)?.clientY;
- }}
- onTouchMove={(event) => {
- const nextTouchY = event.touches.item(0)?.clientY;
- if (nextTouchY === undefined || previousTouchY === undefined) return;
-
- const deltaY = previousTouchY - nextTouchY;
- if (deltaY !== 0) {
- markExplicitScrollIntent(deltaY > 0 ? 'down' : 'up');
- }
- previousTouchY = nextTouchY;
- }}
- onTouchEnd={() => {
- previousTouchY = undefined;
- }}
- onTouchCancel={() => {
- previousTouchY = undefined;
- }}
+ {...scrollIntent.handlers}
style={{
width: '100%',
'overflow-y': 'auto',
diff --git a/js/app/packages/channel/Channel/create-channel-hotkeys.ts b/js/app/packages/channel/Channel/create-channel-hotkeys.ts
index 1f4de95f33..73465019d8 100644
--- a/js/app/packages/channel/Channel/create-channel-hotkeys.ts
+++ b/js/app/packages/channel/Channel/create-channel-hotkeys.ts
@@ -67,6 +67,7 @@ export function createChannelHotkeys(options: CreateChannelHotkeysOptions) {
keyDownHandler: () => {
const id = options.selection.selectPrevious();
if (id) {
+ options.navigation()?.markUserIntent('up');
options.navigation()?.scrollToId(id, { align: 'nearest' });
}
return true;
@@ -81,6 +82,7 @@ export function createChannelHotkeys(options: CreateChannelHotkeysOptions) {
keyDownHandler: () => {
const id = options.selection.selectNext();
if (id) {
+ options.navigation()?.markUserIntent('down');
options.navigation()?.scrollToId(id, { align: 'nearest' });
} else {
inputEl?.querySelector<HTMLElement>('[contenteditable]')?.focus();
@@ -97,6 +99,7 @@ export function createChannelHotkeys(options: CreateChannelHotkeysOptions) {
options.selection.clear();
const id = options.selection.selectPrevious();
if (!id) return false;
+ options.navigation()?.markUserIntent('down');
options.navigation()?.scrollToId(id, { align: 'end' });
return true;
},
@@ -185,6 +188,7 @@ export function createChannelHotkeys(options: CreateChannelHotkeysOptions) {
keyDownHandler: () => {
const id = options.selection.selectPrevious();
if (id) {
+ options.navigation()?.markUserIntent('up');
options.navigation()?.scrollToId(id, { align: 'nearest' });
messageListEl?.focus();
}
diff --git a/js/app/packages/channel/Channel/tests/create-target-message-controller.test.ts b/js/app/packages/channel/Channel/tests/create-target-message-controller.test.ts
index 0ee54f6223..7574116450 100644
--- a/js/app/packages/channel/Channel/tests/create-target-message-controller.test.ts
+++ b/js/app/packages/channel/Channel/tests/create-target-message-controller.test.ts
@@ -47,6 +47,7 @@ function createController(
navigatePrevious: () => false,
navigateNext: () => false,
isNearBottom: () => true,
+ markUserIntent: () => {},
}
: undefined,
});
diff --git a/js/app/packages/channel/Channel/tests/thread-list-scroll.test.ts b/js/app/packages/channel/Channel/tests/thread-list-scroll.test.ts
index 6fd3cbfc1f..37c54edd3e 100644
--- a/js/app/packages/channel/Channel/tests/thread-list-scroll.test.ts
+++ b/js/app/packages/channel/Channel/tests/thread-list-scroll.test.ts
@@ -1,72 +1,42 @@
import { describe, expect, it } from 'vitest';
-import {
- accumulateExplicitScrollDownDistance,
- hasExplicitScrollDownGesture,
- isExplicitScrollDown,
-} from '../ThreadList';
+import { createScrollIntentTracker } from '@core/util/scroll-intent';
-describe('isExplicitScrollDown', () => {
- it('returns true only for recent explicit down intent', () => {
- expect(
- isExplicitScrollDown(24, { direction: 'down', at: 1000 }, 1100)
- ).toBe(true);
+describe('createScrollIntentTracker', () => {
+ it('is not interacting by default', () => {
+ const tracker = createScrollIntentTracker();
+ expect(tracker.isUserInteracting()).toBe(false);
});
- it('returns false when intent is missing, stale, or not downward', () => {
- expect(isExplicitScrollDown(24, undefined, 1100)).toBe(false);
- expect(isExplicitScrollDown(24, { direction: 'up', at: 1000 }, 1100)).toBe(
- false
- );
- expect(
- isExplicitScrollDown(24, { direction: 'down', at: 1000 }, 1300)
- ).toBe(false);
+ it('is interacting after markUserIntent', () => {
+ const tracker = createScrollIntentTracker();
+ tracker.markUserIntent('down');
+ expect(tracker.isUserInteracting()).toBe(true);
});
- it('returns false when scroll delta is not positive', () => {
- expect(isExplicitScrollDown(0, { direction: 'down', at: 1000 }, 1100)).toBe(
- false
- );
- expect(
- isExplicitScrollDown(-8, { direction: 'down', at: 1000 }, 1100)
- ).toBe(false);
+ it('stops interacting after timeout expires', () => {
+ const tracker = createScrollIntentTracker();
+ tracker.markUserIntent('down');
+ const farFuture = Date.now() + 500;
+ expect(tracker.isUserInteracting(farFuture)).toBe(false);
});
-});
-describe('accumulateExplicitScrollDownDistance', () => {
- it('accumulates distance for recent explicit downward intent', () => {
- expect(
- accumulateExplicitScrollDownDistance(
- 20,
- 16,
- { direction: 'down', at: 1000 },
- 1100
- )
- ).toBe(36);
- });
+ it('tracks last direction from markUserIntent', () => {
+ const tracker = createScrollIntentTracker();
+ expect(tracker.lastDirection()).toBe(undefined);
+
+ tracker.markUserIntent('down');
+ expect(tracker.lastDirection()).toBe('down');
- it('resets when movement is not explicitly downward', () => {
- expect(
- accumulateExplicitScrollDownDistance(
- 20,
- -8,
- { direction: 'down', at: 1000 },
- 1100
- )
- ).toBe(0);
- expect(
- accumulateExplicitScrollDownDistance(
- 20,
- 8,
- { direction: 'up', at: 1000 },
- 1100
- )
- ).toBe(0);
+ tracker.markUserIntent('up');
+ expect(tracker.lastDirection()).toBe('up');
});
-});
-describe('hasExplicitScrollDownGesture', () => {
- it('requires a minimum accumulated downward distance', () => {
- expect(hasExplicitScrollDownGesture(63)).toBe(false);
- expect(hasExplicitScrollDownGesture(64)).toBe(true);
+ it('clears last direction after interaction expires', () => {
+ const tracker = createScrollIntentTracker();
+ tracker.markUserIntent('down');
+ expect(tracker.lastDirection()).toBe('down');
+
+ const farFuture = Date.now() + 500;
+ expect(tracker.lastDirection(farFuture)).toBe(undefined);
});
});
diff --git a/js/app/packages/channel/DebugSuspense.tsx b/js/app/packages/channel/DebugSuspense.tsx
new file mode 100644
index 0000000000..14dc5498d5
--- /dev/null
+++ b/js/app/packages/channel/DebugSuspense.tsx
@@ -0,0 +1,19 @@
+import { Suspense, type JSX } from 'solid-js';
+
+type DebugSuspenseProps = {
+ name: string;
+ children: JSX.Element;
+};
+
+function DebugSuspenseFallback(props: Pick<DebugSuspenseProps, 'name'>) {
+ console.log(`suspense triggers ${props.name}`);
+ return null;
+}
+
+export function DebugSuspense(props: DebugSuspenseProps) {
+ return (
+ <Suspense fallback={<DebugSuspenseFallback name={props.name} />}>
+ {props.children}
+ </Suspense>
+ );
+}
diff --git a/js/app/packages/channel/Thread/ChannelThread.tsx b/js/app/packages/channel/Thread/ChannelThread.tsx
index dbb4c0a8dc..4b2817f09e 100644
--- a/js/app/packages/channel/Thread/ChannelThread.tsx
+++ b/js/app/packages/channel/Thread/ChannelThread.tsx
@@ -1,12 +1,5 @@
import { useThreadRepliesQuery } from '@queries/channel/thread-replies';
-import {
- createEffect,
- createSignal,
- on,
- Show,
- Suspense,
- type Accessor,
-} from 'solid-js';
+import { createEffect, createSignal, on, Show } from 'solid-js';
import { ChannelMessage } from '../Message';
import { MarkMessaageNotifications } from '@notifications/components/MarkMessageNotifications';
import { useUserId } from '@core/context/user';
@@ -23,15 +16,7 @@ import {
} from './utils/thread-reply-indicator-helpers';
import { createMessageSelection } from '../Channel/create-message-selection';
import { createThreadHotkeys } from './create-thread-hotkeys';
-
-function sliceIf<T>(
- val: Array<T>,
- start: number,
- end: number,
- should: boolean
-): Array<T> {
- return should ? val.slice(start, end) : val;
-}
+import { DebugSuspense } from '@channel/DebugSuspense';
export function ChannelThread(props: ThreadProps) {
const userId = useUserId();
@@ -50,21 +35,31 @@ export function ChannelThread(props: ThreadProps) {
fetchRepliesEnabled
);
- const sliceIfNotExpanded =
- <T,>(val: Accessor<Array<T>>) =>
- () =>
- sliceIf(val(), 0, DEFAULT_VISIBLE_REPLY_COUNT, !props.isExpanded());
+ const queryReplies = (): Array<ApiThreadReply> | undefined => {
+ if (repliesQuery.isLoading) return undefined;
+ return repliesQuery.data;
+ };
+
+ const loadedReplies = () => queryReplies() ?? [];
+ const canScrollToTargetReply = () => queryReplies() !== undefined;
- const previewReplies = sliceIfNotExpanded(() => thread().preview ?? []);
- const loadedReplies = () => repliesQuery.data ?? [];
- const fetchedReplies = sliceIfNotExpanded(() => repliesQuery.data ?? []);
- const hasFetchedReplies = () => repliesQuery.data !== undefined;
- const canScrollToTargetReply = () =>
- !repliesQuery.isLoading && hasFetchedReplies();
- const activeReplies = () => {
- const replies = repliesQuery.data;
- if (replies && !repliesQuery.isLoading) return replies;
- return thread().preview ?? [];
+ const activeReplies = (): Array<ApiThreadReply> => {
+ return queryReplies() ?? thread().preview ?? [];
+ };
+
+ const displayReplies = (): Array<ApiThreadReply> => {
+ const preview = thread().preview ?? [];
+ // When collapsed, use preview directly without reading query state.
+ if (!props.isExpanded()) {
+ return preview.length > DEFAULT_VISIBLE_REPLY_COUNT
+ ? preview.slice(0, DEFAULT_VISIBLE_REPLY_COUNT)
+ : preview;
+ }
+
+ // When expanded, prefer fetched data (full reply list).
+ const fetched = queryReplies();
+ if (fetched) return fetched;
+ return preview;
};
// Thread-local reply selection
@@ -92,10 +87,16 @@ export function ChannelThread(props: ThreadProps) {
setIsReplying: (v) => props.setIsReplying(v),
});
+ // NOTE: Intentionally reads from `thread().preview` instead of `activeReplies()`.
+ // `activeReplies()` can access `repliesQuery.data` which triggers Suspense.
+ // Preview data is always available synchronously and is sufficient here
+ // since this only controls the reply rail connector color.
const firstReplyIsNewMessage = () => {
- const first = activeReplies()[0];
+ const preview = thread().preview ?? [];
+ const first = preview[0];
return first ? props.isNewMessage?.(first) : false;
};
+
const collapsedRepliesCount = () =>
getCollapsedRepliesCount(thread().reply_count, DEFAULT_VISIBLE_REPLY_COUNT);
const collapsedRepliesContainsNewMessages = () =>
@@ -112,10 +113,6 @@ export function ChannelThread(props: ThreadProps) {
const [replyListHandle, setReplyListHandle] =
createSignal<ThreadReplyListHandle>();
- const expand = () => {
- props.setIsExpanded(true);
- };
-
createEffect(
on(
[
@@ -146,7 +143,7 @@ export function ChannelThread(props: ThreadProps) {
);
return (
- <Suspense>
+ <DebugSuspense name="ChannelThread.root">
<Thread.Row
message={props.data()}
listMeta={props.listMeta}
@@ -157,62 +154,46 @@ export function ChannelThread(props: ThreadProps) {
messageId={props.data().id}
channelId={props.channelId()}
>
- <ChannelMessage
- channelId={props.channelId()}
- message={props.data()}
- actions={props.getMessageActions?.(props.data())}
- listMeta={props.listMeta}
- messageEditor={props.messageEditor}
- highlighted={
- props.highlighted || (isSelected() && !isThreadFocused())
- }
- selectionState={
- isSelected() && !isThreadFocused()
- ? { isSelected: true }
- : undefined
- }
- />
+ <DebugSuspense name="ChannelThread.message">
+ <ChannelMessage
+ channelId={props.channelId()}
+ message={props.data()}
+ actions={props.getMessageActions?.(props.data())}
+ listMeta={props.listMeta}
+ messageEditor={props.messageEditor}
+ highlighted={
+ props.highlighted || (isSelected() && !isThreadFocused())
+ }
+ selectionState={
+ isSelected() && !isThreadFocused()
+ ? { isSelected: true }
+ : undefined
+ }
+ />
+ </DebugSuspense>
</MarkMessaageNotifications>
<Show when={hasReplies() || props.isReplying()}>
<div class="relative w-full">
- <Thread.ReplyRailDecorations
- isReplying={props.isReplying}
- firstThreadReplyNewMessage={firstReplyIsNewMessage()}
- />
- <Suspense>
+ <DebugSuspense name="ChannelThread.reply-rail">
+ <Thread.ReplyRailDecorations
+ isReplying={props.isReplying}
+ firstThreadReplyNewMessage={firstReplyIsNewMessage()}
+ />
+ </DebugSuspense>
+ <DebugSuspense name="ChannelThread.replies">
<Thread.RepliesContainer>
- <Show
- when={!repliesQuery.isLoading && hasFetchedReplies()}
- fallback={
- <Thread.ReplyList
- channelId={props.channelId()}
- threadId={props.data().id}
- replies={previewReplies()}
- getMessageActions={props.getMessageActions}
- messageEditor={props.messageEditor}
- isNewMessage={props.isNewMessage}
- highlightedReplyId={props.highlightedReplyId}
- onReady={setReplyListHandle}
- selectedReplyId={replySelection.selectedId}
- isThreadFocused={isThreadFocused}
- />
- }
- >
- <Suspense>
- <Thread.ReplyList
- channelId={props.channelId()}
- threadId={props.data().id}
- replies={fetchedReplies()}
- getMessageActions={props.getMessageActions}
- messageEditor={props.messageEditor}
- isNewMessage={props.isNewMessage}
- highlightedReplyId={props.highlightedReplyId}
- onReady={setReplyListHandle}
- selectedReplyId={replySelection.selectedId}
- isThreadFocused={isThreadFocused}
- />
- </Suspense>
- </Show>
+ <Thread.ReplyList
+ channelId={props.channelId()}
+ threadId={props.data().id}
+ replies={displayReplies()}
+ getMessageActions={props.getMessageActions}
+ messageEditor={props.messageEditor}
+ isNewMessage={props.isNewMessage}
+ highlightedReplyId={props.highlightedReplyId}
+ onReady={setReplyListHandle}
+ selectedReplyId={replySelection.selectedId}
+ isThreadFocused={isThreadFocused}
+ />
<Show when={props.isReplying()}>
<div ref={attachReplyInputRef}>
@@ -243,7 +224,7 @@ export function ChannelThread(props: ThreadProps) {
collapsedRepliesCount={collapsedRepliesCount()}
participants={collapsedReplyUsers()}
latestReplyAt={collapsedLatestReplyAt()}
- onClick={expand}
+ onClick={() => props.setIsExpanded(true)}
hasNewMessages={collapsedRepliesContainsNewMessages()}
/>
</Show>
@@ -256,11 +237,11 @@ export function ChannelThread(props: ThreadProps) {
</Thread.ActionsFooter>
</Show>
</Thread.RepliesContainer>
- </Suspense>
+ </DebugSuspense>
</div>
</Show>
</div>
</Thread.Row>
- </Suspense>
+ </DebugSuspense>
);
}
diff --git a/js/app/packages/core/util/scroll-intent.ts b/js/app/packages/core/util/scroll-intent.ts
new file mode 100644
index 0000000000..b40a1a0b08
--- /dev/null
+++ b/js/app/packages/core/util/scroll-intent.ts
@@ -0,0 +1,118 @@
+import type { JSX } from 'solid-js';
+
+/** How long after an input event we still consider the user to be interacting.
+ * 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;
+
+export type ScrollDirection = 'up' | 'down';
+
+export type ScrollIntentTracker = {
+ /**
+ * Signal that a user-initiated navigation is about to cause a
+ * programmatic scroll (e.g. hotkey-driven `scrollToId`).
+ */
+ markUserIntent: (direction: ScrollDirection) => void;
+ /** Whether the user is currently in an active scrolling interaction. */
+ isUserInteracting: (now?: number) => boolean;
+ /** The direction of the last user scroll intent, or undefined if the
+ * user is no longer interacting (prevents stale direction reads). */
+ lastDirection: (now?: number) => ScrollDirection | undefined;
+ /**
+ * Event handler props to spread onto the scrollable container element.
+ * Covers pointer (scrollbar drag + touch), wheel, and keyboard scrolling.
+ */
+ handlers: ScrollIntentHandlers;
+};
+
+type ScrollIntentHandlers = {
+ onPointerDown: JSX.EventHandlerUnion<HTMLElement, PointerEvent>;
+ onPointerUp: JSX.EventHandlerUnion<HTMLElement, PointerEvent>;
+ onPointerCancel: JSX.EventHandlerUnion<HTMLElement, PointerEvent>;
+ onWheel: JSX.EventHandlerUnion<HTMLElement, WheelEvent>;
+ onKeyDown: JSX.EventHandlerUnion<HTMLElement, KeyboardEvent>;
+};
+
+const SCROLL_UP_KEYS = new Set(['ArrowUp', 'PageUp', 'Home']);
+const SCROLL_DOWN_KEYS = new Set(['ArrowDown', 'PageDown', 'End', ' ']);
+
+/**
+ * Creates a scroll-intent tracker that distinguishes user-initiated scroll
+ * events from programmatic / virtualizer-driven ones.
+ *
+ * User interaction is detected via:
+ * - `pointerdown` / `pointerup` — covers scrollbar drag and touch drag
+ * - `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`)
+ *
+ * Usage:
+ * ```tsx
+ * const scrollIntent = createScrollIntentTracker();
+ *
+ * <div {...scrollIntent.handlers}>
+ * ...scrollable content...
+ * </div>
+ *
+ * function onScroll() {
+ * if (scrollIntent.isUserInteracting()) {
+ * // user-initiated scroll — safe to paginate
+ * }
+ * }
+ * ```
+ */
+export function createScrollIntentTracker(): ScrollIntentTracker {
+ let isPointerDown = false;
+ let activeUntil = 0;
+ let direction: ScrollDirection | undefined;
+
+ const markUserIntent = (dir: ScrollDirection) => {
+ direction = dir;
+ activeUntil = Math.max(activeUntil, Date.now() + INTERACTION_TIMEOUT_MS);
+ };
+
+ const isUserInteracting = (now = Date.now()) =>
+ isPointerDown || now < activeUntil;
+
+ const lastDirection = (now?: number) =>
+ isUserInteracting(now) ? direction : undefined;
+
+ const endPointer = () => {
+ if (!isPointerDown) return;
+ isPointerDown = false;
+ activeUntil = Math.max(activeUntil, Date.now() + INTERACTION_TIMEOUT_MS);
+ };
+
+ const handlers: ScrollIntentHandlers = {
+ onPointerDown: (event) => {
+ // Touch interactions always indicate scroll intent (finger drag)
+ if (event.pointerType === 'touch') {
+ isPointerDown = true;
+ return;
+ }
+ // For mouse/pen, only track scrollbar drags. Scrollbar clicks
+ // target the container element itself, while clicks on child
+ // elements (messages, buttons, text selection) have a different
+ // target. This prevents false positives from normal click
+ // interactions within the scroll container.
+ if (event.target === event.currentTarget) {
+ isPointerDown = true;
+ }
+ },
+ onPointerUp: endPointer,
+ onPointerCancel: endPointer,
+ onWheel: (event) => {
+ if (event.deltaY === 0) return;
+ markUserIntent(event.deltaY > 0 ? 'down' : 'up');
+ },
+ onKeyDown: (event) => {
+ if (SCROLL_UP_KEYS.has(event.key)) {
+ markUserIntent('up');
+ } else if (SCROLL_DOWN_KEYS.has(event.key)) {
+ markUserIntent('down');
+ }
+ },
+ };
+
+ return { markUserIntent, isUserInteracting, lastDirection, handlers };
+}