feat(web): add PageUp/PageDown chat navigation (#9315)

This commit is contained in:
Yash Singh authored and GitHub committed 2026-09-02 23:12:15 -05:00
1 parent 1aa44a071f
commit 5f84efa1ec
5 files changed
+685

No files matched your search

+37
View File
@@ -63,6 +63,7 @@ import {
Suspense,
useCallback,
useEffect,
useEffectEvent,
useLayoutEffect,
useMemo,
useRef,
@@ -291,6 +292,7 @@ import {
} from "../state/entities";
import { environmentShell } from "../state/shell";
import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer";
import { createPageScrollController, type PageScrollKey } from "./chat/pageScrollController";
import { DraftHeroHeadline } from "./chat/DraftHeroHeadline";
import { ExpandedImageDialog } from "./chat/ExpandedImageDialog";
import { PullRequestThreadDialog } from "./PullRequestThreadDialog";
@@ -4314,6 +4316,38 @@ function ChatViewContent(props: ChatViewProps) {
},
[composerOverlayHeight],
);
const pageScrollControllerRef = useRef<ReturnType<typeof createPageScrollController> | null>(
null,
);
const handlePageScrollStart = useEffectEvent((key: PageScrollKey) => {
if (key === "PageUp" && timelineRealContentOverflowsViewport()) {
cancelTimelineLiveFollowForUserNavigation();
}
});
useEffect(() => {
const controller = createPageScrollController({
getContainer: () => legendListRef.current?.getScrollableNode() ?? null,
getScrollPaddingBottomPx: () => composerOverlayElement?.getBoundingClientRect().height ?? 0,
onScrollStart: handlePageScrollStart,
});
pageScrollControllerRef.current = controller;
return () => {
controller.dispose();
if (pageScrollControllerRef.current === controller) {
pageScrollControllerRef.current = null;
}
};
}, [composerOverlayElement]);
const onComposerPageScrollKeyDown = useCallback((key: PageScrollKey) => {
pageScrollControllerRef.current?.handleKeyDown(key);
}, []);
const onComposerPageScrollKeyUp = useCallback((key: string) => {
pageScrollControllerRef.current?.handleKeyUp(key);
}, []);
const onComposerPageScrollRelease = useCallback(() => {
pageScrollControllerRef.current?.releaseActiveKey();
}, []);
// Live-follow stays active after send/thread-open until an actual list scroll
// gesture opts out.
const scrollToEnd = useCallback((animated = false) => {
@@ -7637,6 +7671,9 @@ function ChatViewContent(props: ChatViewProps) {
composerFilesRef={composerFilesRef}
composerTerminalContextsRef={composerTerminalContextsRef}
composerElementContextsRef={composerElementContextsRef}
onPageScrollKeyDown={onComposerPageScrollKeyDown}
onPageScrollKeyUp={onComposerPageScrollKeyUp}
onPageScrollRelease={onComposerPageScrollRelease}
onSend={onSend}
onInterrupt={onInterrupt}
onImplementPlanInNewThread={onImplementPlanInNewThread}
@@ -83,6 +83,7 @@ import {
} from "./composerInlineChip";
import { FILE_TAG_CHIP_CLASS_NAME, FileTagChipContent } from "./chat/FileTagChip";
import { ComposerPendingTerminalContextChip } from "./chat/ComposerPendingTerminalContexts";
import { getTimelinePageScrollKey } from "./chat/pageScrollController";
import { formatProviderSkillDisplayName } from "@t3tools/client-runtime/providerSkills";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
import { registerComposerInlineTokenPaste } from "./composerInlineTokenPaste";
@@ -916,6 +917,9 @@ interface ComposerPromptEditorProps {
key: "ArrowDown" | "ArrowUp" | "Enter" | "Tab",
event: KeyboardEvent,
) => boolean;
onPageScrollKeyDown?: (key: "PageUp" | "PageDown") => void;
onPageScrollKeyUp?: (key: string) => void;
onPageScrollRelease?: () => void;
onPaste: React.ClipboardEventHandler<HTMLElement>;
editorRef: React.RefObject<ComposerPromptEditorHandle | null>;
}
@@ -1557,6 +1561,9 @@ function ComposerPromptEditorInner({
onRemoveTerminalContext,
onChange,
onCommandKeyDown,
onPageScrollKeyDown,
onPageScrollKeyUp,
onPageScrollRelease,
onPaste,
editorRef,
}: ComposerPromptEditorProps) {
@@ -1829,6 +1836,46 @@ function ComposerPromptEditorInner({
data-testid="composer-editor"
aria-placeholder={placeholder}
placeholder={<span />}
onKeyDown={(event) => {
if (
event.key === "Control" ||
event.key === "Meta" ||
event.key === "Alt" ||
event.key === "Shift"
) {
onPageScrollRelease?.();
}
if (event.key !== "PageUp" && event.key !== "PageDown") {
return;
}
const pageScrollKey = getTimelinePageScrollKey({
altKey: event.altKey,
clientHeight: event.currentTarget.clientHeight,
ctrlKey: event.ctrlKey,
defaultPrevented: event.defaultPrevented,
isComposing: event.nativeEvent.isComposing,
key: event.key,
keyCode: event.keyCode,
metaKey: event.metaKey,
scrollHeight: event.currentTarget.scrollHeight,
scrollTop: event.currentTarget.scrollTop,
shiftKey: event.shiftKey,
});
if (!pageScrollKey) {
onPageScrollRelease?.();
return;
}
if (!onPageScrollKeyDown) {
return;
}
event.preventDefault();
onPageScrollKeyDown(pageScrollKey);
}}
onKeyUp={(event) => onPageScrollKeyUp?.(event.key)}
onBlur={onPageScrollRelease}
onPaste={onPaste}
/>
}
@@ -1868,6 +1915,9 @@ export function ComposerPromptEditor({
onRemoveTerminalContext,
onChange,
onCommandKeyDown,
onPageScrollKeyDown,
onPageScrollKeyUp,
onPageScrollRelease,
onPaste,
editorRef,
}: ComposerPromptEditorProps) {
@@ -1912,6 +1962,9 @@ export function ComposerPromptEditor({
onPaste={onPaste}
editorRef={editorRef}
{...(onCommandKeyDown ? { onCommandKeyDown } : {})}
{...(onPageScrollKeyDown ? { onPageScrollKeyDown } : {})}
{...(onPageScrollKeyUp ? { onPageScrollKeyUp } : {})}
{...(onPageScrollRelease ? { onPageScrollRelease } : {})}
{...(className ? { className } : {})}
/>
</LexicalComposer>
@@ -710,6 +710,9 @@ export interface ChatComposerProps {
composerTerminalContextsRef: React.RefObject<TerminalContextDraft[]>;
composerElementContextsRef: React.RefObject<ElementContextDraft[]>;
composerRef: React.RefObject<ChatComposerHandle | null>;
onPageScrollKeyDown: (key: "PageUp" | "PageDown") => void;
onPageScrollKeyUp: (key: string) => void;
onPageScrollRelease: () => void;
// Callbacks
onSend: (e?: { preventDefault: () => void }, intent?: ComposerSubmissionIntent) => void;
@@ -801,6 +804,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
composerFilesRef,
composerTerminalContextsRef,
composerElementContextsRef,
onPageScrollKeyDown,
onPageScrollKeyUp,
onPageScrollRelease,
onSend,
onInterrupt,
onImplementPlanInNewThread,
@@ -4187,6 +4193,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
onRemoveTerminalContext={removeComposerTerminalContextFromDraft}
onChange={onPromptChange}
onCommandKeyDown={onComposerCommandKey}
onPageScrollKeyDown={onPageScrollKeyDown}
onPageScrollKeyUp={onPageScrollKeyUp}
onPageScrollRelease={onPageScrollRelease}
onPaste={onComposerPaste}
placeholder={
isComposerApprovalState
@@ -0,0 +1,279 @@
import { describe, expect, test } from "vite-plus/test";
import {
createPageScrollController,
getTimelinePageScrollKey,
getPageScrollDistancePx,
getPageScrollMultiplier,
getPageScrollVelocityPxPerMs,
PAGE_SCROLL_ACCELERATION_MS,
PAGE_SCROLL_ANIMATION_MS,
PAGE_SCROLL_MAX_MULTIPLIER,
} from "./pageScrollController";
class TestClock {
private currentTime = 0;
private nextHandle = 1;
private animationFrames = new Map<number, FrameRequestCallback>();
private timeouts = new Map<number, { at: number; callback: () => void }>();
readonly env = {
now: () => this.currentTime,
requestAnimationFrame: (callback: FrameRequestCallback) => {
const handle = this.nextHandle;
this.nextHandle += 1;
this.animationFrames.set(handle, callback);
return handle;
},
cancelAnimationFrame: (handle: number) => {
this.animationFrames.delete(handle);
},
setTimeout: (callback: () => void, delay: number) => {
const handle = this.nextHandle;
this.nextHandle += 1;
this.timeouts.set(handle, { at: this.currentTime + delay, callback });
return handle;
},
clearTimeout: (handle: number) => {
this.timeouts.delete(handle);
},
};
advanceBy(ms: number, frameMs = 16) {
const target = this.currentTime + ms;
while (this.currentTime < target) {
this.currentTime = Math.min(target, this.currentTime + frameMs);
this.flushTimeouts();
this.flushAnimationFrames();
}
}
private flushTimeouts() {
let hasDueTimeouts = true;
while (hasDueTimeouts) {
hasDueTimeouts = false;
for (const [handle, timeout] of this.timeouts) {
if (timeout.at > this.currentTime) {
continue;
}
this.timeouts.delete(handle);
timeout.callback();
hasDueTimeouts = true;
}
}
}
private flushAnimationFrames() {
if (this.animationFrames.size === 0) {
return;
}
const frames = [...this.animationFrames.values()];
this.animationFrames.clear();
for (const callback of frames) {
callback(this.currentTime);
}
}
}
describe("page scroll helpers", () => {
const composerPageScrollEvent = (
overrides: Partial<Parameters<typeof getTimelinePageScrollKey>[0]> = {},
) => ({
altKey: false,
clientHeight: 200,
ctrlKey: false,
defaultPrevented: false,
isComposing: false,
key: "PageDown",
keyCode: 34,
metaKey: false,
scrollHeight: 200,
scrollTop: 0,
shiftKey: false,
...overrides,
});
test("leaves page keys to IME composition", () => {
expect(getTimelinePageScrollKey(composerPageScrollEvent({ isComposing: true }))).toBeNull();
expect(getTimelinePageScrollKey(composerPageScrollEvent({ keyCode: 229 }))).toBeNull();
});
test("leaves page keys to an overflowing composer until it reaches the boundary", () => {
expect(
getTimelinePageScrollKey(composerPageScrollEvent({ scrollHeight: 600, scrollTop: 0 })),
).toBeNull();
expect(
getTimelinePageScrollKey(
composerPageScrollEvent({
key: "PageUp",
keyCode: 33,
scrollHeight: 600,
scrollTop: 400,
}),
),
).toBeNull();
expect(
getTimelinePageScrollKey(
composerPageScrollEvent({
key: "PageUp",
keyCode: 33,
scrollHeight: 600,
scrollTop: 0,
}),
),
).toBe("PageUp");
expect(
getTimelinePageScrollKey(composerPageScrollEvent({ scrollHeight: 600, scrollTop: 400 })),
).toBe("PageDown");
});
test("hands off page keys within a fractional pixel of the composer boundary", () => {
expect(
getTimelinePageScrollKey(
composerPageScrollEvent({
key: "PageUp",
keyCode: 33,
scrollHeight: 600,
scrollTop: 0.5,
}),
),
).toBe("PageUp");
expect(
getTimelinePageScrollKey(composerPageScrollEvent({ scrollHeight: 600, scrollTop: 399.5 })),
).toBe("PageDown");
});
test("ramps multiplier over time and caps at the max velocity", () => {
expect(getPageScrollMultiplier(0)).toBe(1);
expect(getPageScrollMultiplier(PAGE_SCROLL_ACCELERATION_MS / 2)).toBeCloseTo(1.5);
expect(getPageScrollMultiplier(PAGE_SCROLL_ACCELERATION_MS * 5)).toBe(
PAGE_SCROLL_MAX_MULTIPLIER,
);
});
test("derives the hold velocity from page size and acceleration", () => {
expect(
getPageScrollVelocityPxPerMs({
holdElapsedMs: 0,
pageScrollDistancePx: 600,
}),
).toBeCloseTo(4);
expect(
getPageScrollVelocityPxPerMs({
holdElapsedMs: PAGE_SCROLL_ACCELERATION_MS * 5,
pageScrollDistancePx: 600,
}),
).toBeCloseTo(8);
});
});
describe("createPageScrollController", () => {
test("keeps a single page scroll when the key is tapped", () => {
const clock = new TestClock();
const container = {
clientHeight: 600,
scrollHeight: 1_800,
scrollTop: 0,
getBoundingClientRect: () => ({ height: 600 }),
};
const controller = createPageScrollController({
getContainer: () => container,
getScrollPaddingBottomPx: () => 24,
env: clock.env,
});
controller.handleKeyDown("PageDown");
controller.handleKeyUp("PageDown");
clock.advanceBy(PAGE_SCROLL_ANIMATION_MS);
expect(container.scrollTop).toBeCloseTo(
getPageScrollDistancePx({
containerHeightPx: 600,
scrollPaddingBottomPx: 24,
}),
5,
);
});
test("continues scrolling on hold without repeated keydown events and stops on keyup", () => {
const clock = new TestClock();
const container = {
clientHeight: 600,
scrollHeight: 4_000,
scrollTop: 0,
getBoundingClientRect: () => ({ height: 600 }),
};
const controller = createPageScrollController({
getContainer: () => container,
getScrollPaddingBottomPx: () => 24,
env: clock.env,
});
controller.handleKeyDown("PageDown");
clock.advanceBy(PAGE_SCROLL_ANIMATION_MS + 50);
const afterHoldStarts = container.scrollTop;
clock.advanceBy(200);
expect(container.scrollTop).toBeGreaterThan(afterHoldStarts);
const stoppedAt = container.scrollTop;
controller.handleKeyUp("PageDown");
clock.advanceBy(250);
expect(container.scrollTop).toBe(stoppedAt);
});
test("notifies once when a page scroll starts", () => {
const clock = new TestClock();
const started: string[] = [];
const controller = createPageScrollController({
getContainer: () => ({
clientHeight: 600,
scrollHeight: 1_800,
scrollTop: 600,
getBoundingClientRect: () => ({ height: 600 }),
}),
getScrollPaddingBottomPx: () => 24,
onScrollStart: (key) => started.push(key),
env: clock.env,
});
controller.handleKeyDown("PageUp");
controller.handleKeyDown("PageUp");
expect(started).toEqual(["PageUp"]);
});
test("does not start a page scroll at the timeline boundary", () => {
const clock = new TestClock();
const started: string[] = [];
const container = {
clientHeight: 600,
scrollHeight: 1_800,
scrollTop: 0.5,
getBoundingClientRect: () => ({ height: 600 }),
};
const controller = createPageScrollController({
getContainer: () => container,
getScrollPaddingBottomPx: () => 24,
onScrollStart: (key) => started.push(key),
env: clock.env,
});
controller.handleKeyDown("PageUp");
clock.advanceBy(PAGE_SCROLL_ANIMATION_MS * 2);
container.scrollTop = container.scrollHeight - container.clientHeight - 0.5;
controller.handleKeyDown("PageDown");
clock.advanceBy(PAGE_SCROLL_ANIMATION_MS * 2);
expect(started).toEqual([]);
expect(container.scrollTop).toBe(1_199.5);
});
});
@@ -0,0 +1,307 @@
export const PAGE_SCROLL_ANIMATION_MS = 150;
export const PAGE_SCROLL_ACCELERATION_MS = 400;
export const PAGE_SCROLL_MAX_MULTIPLIER = 2;
const PAGE_SCROLL_ALIGNMENT_OFFSET_PX = 36;
const PAGE_SCROLL_BOUNDARY_EPSILON_PX = 1;
const PAGE_SCROLL_HOLD_DELAY_MS = PAGE_SCROLL_ANIMATION_MS;
export type PageScrollKey = "PageUp" | "PageDown";
type PageScrollMetrics = {
clientHeight: number;
scrollHeight: number;
scrollTop: number;
};
function canScrollInDirection(
{ clientHeight, scrollHeight, scrollTop }: PageScrollMetrics,
key: PageScrollKey,
): boolean {
const maxScrollTop = Math.max(0, scrollHeight - clientHeight);
const clampedScrollTop = Math.min(maxScrollTop, Math.max(0, scrollTop));
return key === "PageUp"
? clampedScrollTop > PAGE_SCROLL_BOUNDARY_EPSILON_PX
: clampedScrollTop < maxScrollTop - PAGE_SCROLL_BOUNDARY_EPSILON_PX;
}
export function getTimelinePageScrollKey({
altKey,
clientHeight,
ctrlKey,
defaultPrevented,
isComposing,
key,
keyCode,
metaKey,
scrollHeight,
scrollTop,
shiftKey,
}: {
altKey: boolean;
clientHeight: number;
ctrlKey: boolean;
defaultPrevented: boolean;
isComposing: boolean;
key: string;
keyCode: number;
metaKey: boolean;
scrollHeight: number;
scrollTop: number;
shiftKey: boolean;
}): PageScrollKey | null {
if (key !== "PageUp" && key !== "PageDown") {
return null;
}
if (
defaultPrevented ||
isComposing ||
keyCode === 229 ||
altKey ||
ctrlKey ||
metaKey ||
shiftKey
) {
return null;
}
const editorCanScroll = canScrollInDirection({ clientHeight, scrollHeight, scrollTop }, key);
return editorCanScroll ? null : key;
}
type PageScrollContainer = PageScrollMetrics & {
getBoundingClientRect: () => {
height: number;
};
};
type PageScrollEnv = {
now: () => number;
requestAnimationFrame: (callback: FrameRequestCallback) => number;
cancelAnimationFrame: (handle: number) => void;
setTimeout: (callback: () => void, delay: number) => number;
clearTimeout: (handle: number) => void;
};
function getDefaultEnv(): PageScrollEnv {
return {
now: () => performance.now(),
requestAnimationFrame: (callback) => window.requestAnimationFrame(callback),
cancelAnimationFrame: (handle) => window.cancelAnimationFrame(handle),
setTimeout: (callback, delay) => window.setTimeout(callback, delay),
clearTimeout: (handle) => window.clearTimeout(handle),
};
}
export function getPageScrollMultiplier(holdElapsedMs: number): number {
const progress = Math.max(0, holdElapsedMs) / PAGE_SCROLL_ACCELERATION_MS;
return 1 + Math.min(progress, 1) * (PAGE_SCROLL_MAX_MULTIPLIER - 1);
}
export function getPageScrollVelocityPxPerMs({
holdElapsedMs,
pageScrollDistancePx,
}: {
holdElapsedMs: number;
pageScrollDistancePx: number;
}): number {
return (pageScrollDistancePx * getPageScrollMultiplier(holdElapsedMs)) / PAGE_SCROLL_ANIMATION_MS;
}
export function getPageScrollDistancePx({
containerHeightPx,
scrollPaddingBottomPx,
}: {
containerHeightPx: number;
scrollPaddingBottomPx: number;
}): number {
return Math.max(0, containerHeightPx - PAGE_SCROLL_ALIGNMENT_OFFSET_PX - scrollPaddingBottomPx);
}
function getDirection(key: PageScrollKey): -1 | 1 {
return key === "PageUp" ? -1 : 1;
}
function easeInOut(progress: number): number {
const ax = 3 * 0.42 - 3 * 0.58 + 1;
const bx = 3 * (0.58 - 2 * 0.42);
const cx = 3 * 0.42;
const ay = -2;
const by = 3;
const x = (value: number) => ((ax * value + bx) * value + cx) * value;
const y = (value: number) => (ay * value + by) * value * value;
let value = progress;
for (let index = 0; index < 5; index += 1) {
const delta = x(value) - progress;
const derivative = (3 * ax * value + 2 * bx) * value + cx;
if (Math.abs(delta) < 1e-4 || derivative === 0) {
break;
}
value -= delta / derivative;
value = Math.min(1, Math.max(0, value));
}
return y(value);
}
export function createPageScrollController({
getContainer,
getScrollPaddingBottomPx,
onScrollStart,
env = getDefaultEnv(),
}: {
getContainer: () => PageScrollContainer | null;
getScrollPaddingBottomPx: () => number;
onScrollStart?: (key: PageScrollKey) => void;
env?: PageScrollEnv;
}) {
const state = {
activeKey: null as PageScrollKey | null,
discreteAnimationFrame: 0,
holdDelayTimeout: 0,
holdAnimationFrame: 0,
holdStartTime: 0,
lastFrameTime: 0,
holdActive: false,
};
const readPageScrollDistance = (container: PageScrollContainer) =>
getPageScrollDistancePx({
containerHeightPx: container.getBoundingClientRect().height,
scrollPaddingBottomPx: getScrollPaddingBottomPx(),
});
const cancelDiscreteAnimation = () => {
if (state.discreteAnimationFrame === 0) {
return;
}
env.cancelAnimationFrame(state.discreteAnimationFrame);
state.discreteAnimationFrame = 0;
};
const stop = ({
cancelDiscreteAnimation: shouldCancelDiscreteAnimation,
}: {
cancelDiscreteAnimation: boolean;
}) => {
if (state.holdDelayTimeout !== 0) {
env.clearTimeout(state.holdDelayTimeout);
state.holdDelayTimeout = 0;
}
if (state.holdAnimationFrame !== 0) {
env.cancelAnimationFrame(state.holdAnimationFrame);
state.holdAnimationFrame = 0;
}
if (shouldCancelDiscreteAnimation) {
cancelDiscreteAnimation();
}
state.activeKey = null;
state.holdStartTime = 0;
state.lastFrameTime = 0;
state.holdActive = false;
};
const smoothScrollBy = (container: PageScrollContainer, deltaY: number) => {
cancelDiscreteAnimation();
const startScrollTop = container.scrollTop;
const startTime = env.now();
const step = (now: number) => {
const progress = Math.min(1, (now - startTime) / PAGE_SCROLL_ANIMATION_MS);
container.scrollTop = startScrollTop + deltaY * easeInOut(progress);
if (progress < 1) {
state.discreteAnimationFrame = env.requestAnimationFrame(step);
return;
}
state.discreteAnimationFrame = 0;
};
state.discreteAnimationFrame = env.requestAnimationFrame(step);
};
const startHoldScroll = (key: PageScrollKey, container: PageScrollContainer) => {
cancelDiscreteAnimation();
state.holdActive = true;
state.holdStartTime = env.now();
state.lastFrameTime = state.holdStartTime;
const step = (now: number) => {
if (state.activeKey !== key) {
state.holdAnimationFrame = 0;
return;
}
const deltaMs = now - state.lastFrameTime;
state.lastFrameTime = now;
const velocityPxPerMs = getPageScrollVelocityPxPerMs({
holdElapsedMs: now - state.holdStartTime,
pageScrollDistancePx: readPageScrollDistance(container),
});
const previousScrollTop = container.scrollTop;
container.scrollTop = previousScrollTop + velocityPxPerMs * deltaMs * getDirection(key);
if (deltaMs > 0 && container.scrollTop === previousScrollTop) {
stop({ cancelDiscreteAnimation: true });
return;
}
state.holdAnimationFrame = env.requestAnimationFrame(step);
};
state.holdAnimationFrame = env.requestAnimationFrame(step);
};
return {
handleKeyDown(key: PageScrollKey) {
const container = getContainer();
if (!container) {
return;
}
if (!canScrollInDirection(container, key)) {
return;
}
if (state.activeKey === key) {
return;
}
stop({ cancelDiscreteAnimation: true });
state.activeKey = key;
onScrollStart?.(key);
smoothScrollBy(container, readPageScrollDistance(container) * getDirection(key));
state.holdDelayTimeout = env.setTimeout(() => {
state.holdDelayTimeout = 0;
if (state.activeKey !== key) {
return;
}
startHoldScroll(key, container);
}, PAGE_SCROLL_HOLD_DELAY_MS);
},
handleKeyUp(key: string) {
if (state.activeKey !== key) {
return;
}
stop({ cancelDiscreteAnimation: state.holdActive });
},
releaseActiveKey() {
stop({ cancelDiscreteAnimation: state.holdActive });
},
dispose() {
stop({ cancelDiscreteAnimation: true });
},
};
}