Skip to content

Commit d71e51a

Browse files
committed
fix: respect reduced motion in programmatic scrolling
1 parent c6f32e2 commit d71e51a

12 files changed

Lines changed: 203 additions & 13 deletions

‎apps/mobile/src/features/threads/ThreadDetailScreen.tsx‎

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ import {
4040
useState,
4141
} from "react";
4242
import {
43+
AccessibilityInfo,
4344
Alert,
4445
AppState,
4546
Keyboard,
@@ -730,14 +731,15 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
730731
// leaves the keyboard padding permanently applied — overshooting the
731732
// anchor and leaving a phantom bottom inset once the reply streams in.
732733
void KeyboardController.dismiss()
733-
.then(() => {
734+
.then(() => AccessibilityInfo.isReduceMotionEnabled().catch(() => true))
735+
.then((reducedMotion) => {
734736
if (
735737
selectedThreadKeyRef.current !== targetThreadKey ||
736738
lastScrolledSubmittedMessageIdRef.current !== submittedMessageId
737739
) {
738740
return;
739741
}
740-
return scrollMessageToEnd({ animated: true, closeKeyboard: false });
742+
return scrollMessageToEnd({ animated: !reducedMotion, closeKeyboard: false });
741743
})
742744
.catch(() => {
743745
if (
@@ -835,10 +837,17 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
835837

836838
const handleScrollToEnd = useCallback(() => {
837839
void Haptics.selectionAsync();
838-
void scrollMessageToEnd({ animated: true, closeKeyboard: false }).catch(() => {
839-
freeze.set(false);
840-
});
841-
}, [freeze, scrollMessageToEnd]);
840+
const targetThreadKey = selectedThreadKey;
841+
void AccessibilityInfo.isReduceMotionEnabled()
842+
.catch(() => true)
843+
.then((reducedMotion) => {
844+
if (selectedThreadKeyRef.current !== targetThreadKey) return;
845+
return scrollMessageToEnd({ animated: !reducedMotion, closeKeyboard: false });
846+
})
847+
.catch(() => {
848+
if (selectedThreadKeyRef.current === targetThreadKey) freeze.set(false);
849+
});
850+
}, [freeze, scrollMessageToEnd, selectedThreadKey]);
842851

843852
const showScrollToEndButton = contentPresentationKind === "ready" && !endFollowEnabled;
844853
const { themeAppearance } = useAppearancePreferences();

‎apps/web/src/components/ChatView.tsx‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { prefersReducedMotion as readReducedMotion } from "../lib/reducedMotion";
12
import { useLoadBalancedEnvironment } from "../hooks/useLoadBalancedEnvironment";
23
import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests";
34
import type { UsageLimitSourceSnapshots } from "@t3tools/contracts";
@@ -5401,7 +5402,7 @@ export default function ChatView(props: ChatViewProps) {
54015402
setShowScrollToBottom(false);
54025403
setTimelineAnchor(releaseChatTimelineAnchor);
54035404
requestAnimationFrame(() => {
5404-
void legendListRef.current?.scrollToEnd?.({ animated });
5405+
void legendListRef.current?.scrollToEnd?.({ animated: animated && !readReducedMotion() });
54055406
});
54065407
}, []);
54075408
useLayoutEffect(() => {
@@ -5608,7 +5609,7 @@ export default function ChatView(props: ChatViewProps) {
56085609
void list
56095610
.scrollToIndex({
56105611
index: anchorIndex,
5611-
animated: true,
5612+
animated: !readReducedMotion(),
56125613
viewPosition: 0,
56135614
viewOffset: CHAT_TIMELINE_ANCHOR_OFFSET,
56145615
})

‎apps/web/src/components/RightPanelTabs.tsx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { prefersReducedMotion as readReducedMotion } from "../lib/reducedMotion";
12
import { pullRequestHostOf, type SourceControlProviderKind } from "@t3tools/contracts";
23
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
34
import { useProjects, useServerConfigs, useThreadShells } from "~/state/entities";
@@ -853,7 +854,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
853854
const scrollTabs = useCallback((direction: -1 | 1) => {
854855
const viewport = tabScrollViewport(tabListRef.current);
855856
if (!viewport) return;
856-
const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
857+
const reduceMotion = readReducedMotion();
857858
viewport.scrollBy({
858859
left: direction * Math.max(120, viewport.clientWidth * 0.75),
859860
behavior: reduceMotion ? "auto" : "smooth",

‎apps/web/src/components/chat/AssistantCitationSource.tsx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { prefersReducedMotion as readReducedMotion } from "../../lib/reducedMotion";
12
import type { LegendListRef } from "@legendapp/list/react";
23
import type { AssistantCitation, MessageId, ScopedThreadRef } from "@t3tools/contracts";
34
import { useEffect, useRef, type ReactNode, type RefObject } from "react";
@@ -117,7 +118,7 @@ export function observeAssistantCitationSource({
117118
if (activation.dismissed) return;
118119
const scrollNode = list.getScrollableNode();
119120
if (!(scrollNode instanceof HTMLElement)) return;
120-
const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
121+
const reducedMotion = readReducedMotion();
121122
let highlighted: Highlight | null = null;
122123
let ownedRange: Range | null = null;
123124
let selected: { range: Range; snapshot: Range } | null = null;

‎apps/web/src/components/chat/MessagesTimeline.tsx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { prefersReducedMotion as readReducedMotion } from "../../lib/reducedMotion";
12
import { ArrowUpIcon, ClockIcon } from "lucide-react";
23
import { ReadOnlySourcePreview } from "../files/AttachmentFilePreview";
34
import { useRightPanelStore } from "~/rightPanelStore";
@@ -1340,7 +1341,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
13401341
onManualNavigation();
13411342
void listRef.current?.scrollToIndex({
13421343
index: item.rowIndex,
1343-
animated: true,
1344+
animated: !readReducedMotion(),
13441345
viewOffset: 24,
13451346
});
13461347
}}

‎apps/web/src/components/chat/pageScrollController.test.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,39 @@ class TestClock {
8080
}
8181
}
8282

83+
describe("page scroll motion preference", () => {
84+
test("reaches the same page immediately after the preference changes", () => {
85+
const clock = new TestClock();
86+
const container = {
87+
clientHeight: 600,
88+
scrollHeight: 4_000,
89+
scrollTop: 0,
90+
getBoundingClientRect: () => ({ height: 600 }),
91+
};
92+
let reducedMotion = false;
93+
const controller = createPageScrollController({
94+
getContainer: () => container,
95+
getScrollPaddingBottomPx: () => 24,
96+
isReducedMotion: () => reducedMotion,
97+
env: clock.env,
98+
});
99+
controller.handleKeyDown("PageDown");
100+
controller.handleKeyUp("PageDown");
101+
expect(container.scrollTop).toBe(0);
102+
clock.advanceBy(PAGE_SCROLL_ANIMATION_MS);
103+
const destination = container.scrollTop;
104+
expect(destination).toBeGreaterThan(0);
105+
container.scrollTop = 0;
106+
reducedMotion = true;
107+
controller.handleKeyDown("PageDown");
108+
controller.handleKeyUp("PageDown");
109+
expect(container.scrollTop).toBe(destination);
110+
clock.advanceBy(PAGE_SCROLL_ANIMATION_MS);
111+
expect(container.scrollTop).toBe(destination);
112+
controller.dispose();
113+
});
114+
});
115+
83116
describe("page scroll helpers", () => {
84117
const composerPageScrollEvent = (
85118
overrides: Partial<Parameters<typeof getTimelinePageScrollKey>[0]> = {},

‎apps/web/src/components/chat/pageScrollController.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { prefersReducedMotion } from "../../lib/reducedMotion";
2+
13
export const PAGE_SCROLL_ANIMATION_MS = 150;
24
export const PAGE_SCROLL_ACCELERATION_MS = 400;
35
export const PAGE_SCROLL_MAX_MULTIPLIER = 2;
@@ -149,11 +151,13 @@ export function createPageScrollController({
149151
getContainer,
150152
getScrollPaddingBottomPx,
151153
onScrollStart,
154+
isReducedMotion = prefersReducedMotion,
152155
env = getDefaultEnv(),
153156
}: {
154157
getContainer: () => PageScrollContainer | null;
155158
getScrollPaddingBottomPx: () => number;
156159
onScrollStart?: (key: PageScrollKey) => void;
160+
isReducedMotion?: () => boolean;
157161
env?: PageScrollEnv;
158162
}) {
159163
const state = {
@@ -209,6 +213,11 @@ export function createPageScrollController({
209213
const smoothScrollBy = (container: PageScrollContainer, deltaY: number) => {
210214
cancelDiscreteAnimation();
211215

216+
if (isReducedMotion()) {
217+
container.scrollTop += deltaY;
218+
return;
219+
}
220+
212221
const startScrollTop = container.scrollTop;
213222
const startTime = env.now();
214223

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
import { isValidElement, type ReactElement, type ReactNode } from "react";
2+
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
3+
4+
import { reactHookHarness as hooks } from "../../test/reactHookHarness";
5+
import type { ThemeColorRole } from "../../themePalette";
6+
7+
vi.mock("react", async (importOriginal) => {
8+
const actual = await importOriginal<typeof import("react")>();
9+
const { reactHookHarness } = await import("../../test/reactHookHarness");
10+
return {
11+
...actual,
12+
useCallback: reactHookHarness.useCallback,
13+
useMemo: reactHookHarness.useMemo,
14+
useRef: reactHookHarness.useRef,
15+
useState: reactHookHarness.useState,
16+
useEffect: () => {},
17+
};
18+
});
19+
vi.mock("react/compiler-runtime", async () => {
20+
const { reactHookHarness } = await import("../../test/reactHookHarness");
21+
return { c: reactHookHarness.useMemoCache };
22+
});
23+
24+
import { ThemeEditorPanel } from "./ThemeEditorPanel";
25+
import { ThemeColorField } from "./ThemeColorPicker";
26+
27+
type FieldProps = {
28+
role: ThemeColorRole;
29+
selected: boolean;
30+
onSelect: (role: ThemeColorRole, reveal?: boolean) => void;
31+
};
32+
33+
function findFields(node: ReactNode): ReactElement<FieldProps>[] {
34+
if (Array.isArray(node)) return node.flatMap(findFields);
35+
if (!isValidElement<{ children?: ReactNode }>(node)) return [];
36+
if (node.type === ThemeColorField) return [node as ReactElement<FieldProps>];
37+
return findFields(node.props.children);
38+
}
39+
40+
function renderPanel() {
41+
hooks.beginRender();
42+
return ThemeEditorPanel({
43+
open: true,
44+
onOpenChange: vi.fn(),
45+
onSaved: () => true,
46+
editingTheme: null,
47+
initialAppearance: "dark",
48+
restoreTheme: vi.fn(),
49+
}) as ReactElement<{ ref: { current: unknown }; children: ReactNode }>;
50+
}
51+
52+
describe("theme role reveal", () => {
53+
beforeEach(() => {
54+
hooks.reset();
55+
vi.stubGlobal("window", { localStorage: { getItem: () => null } });
56+
});
57+
afterEach(() => vi.unstubAllGlobals());
58+
59+
it("keeps role selection and reveal targets when motion changes or matchMedia is missing", () => {
60+
let reducedMotion = false;
61+
window.matchMedia = vi.fn(() => ({ matches: reducedMotion }) as MediaQueryList);
62+
const frames: FrameRequestCallback[] = [];
63+
vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) =>
64+
frames.push(callback),
65+
);
66+
const scrollIntoView = vi.fn();
67+
const querySelector = vi.fn(() => ({ scrollIntoView }));
68+
const panel = renderPanel();
69+
panel.props.ref.current = { querySelector };
70+
const select = findFields(panel)[0]!.props.onSelect;
71+
72+
select("toolbar", true);
73+
frames.shift()!(0);
74+
expect(querySelector).toHaveBeenLastCalledWith('[data-theme-color-role="canvas"]');
75+
expect(scrollIntoView).toHaveBeenLastCalledWith({ behavior: "smooth", block: "nearest" });
76+
expect(findFields(renderPanel()).find((field) => field.props.selected)?.props.role).toBe(
77+
"canvas",
78+
);
79+
80+
select("surface", true);
81+
// Read at reveal time, including a preference change after the input event.
82+
reducedMotion = true;
83+
frames.shift()!(0);
84+
expect(querySelector).toHaveBeenLastCalledWith('[data-theme-color-role="surface"]');
85+
expect(scrollIntoView).toHaveBeenLastCalledWith({ behavior: "auto", block: "nearest" });
86+
expect(findFields(renderPanel()).find((field) => field.props.selected)?.props.role).toBe(
87+
"surface",
88+
);
89+
90+
vi.stubGlobal("window", { localStorage: { getItem: () => null } });
91+
select("surface", true);
92+
frames.shift()!(0);
93+
expect(querySelector).toHaveBeenLastCalledWith('[data-theme-color-role="surface"]');
94+
expect(scrollIntoView).toHaveBeenLastCalledWith({ behavior: "smooth", block: "nearest" });
95+
expect(findFields(renderPanel()).find((field) => field.props.selected)?.props.role).toBe(
96+
"surface",
97+
);
98+
});
99+
});

‎apps/web/src/components/settings/ThemeEditorPanel.tsx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { prefersReducedMotion as readReducedMotion } from "../../lib/reducedMotion";
12
import {
23
ChevronDownIcon,
34
ChevronUpIcon,
@@ -520,7 +521,7 @@ export function ThemeEditorPanel({
520521
requestAnimationFrame(() => {
521522
panelRef.current
522523
?.querySelector(`[data-theme-color-role="${visibleRole}"]`)
523-
?.scrollIntoView({ behavior: "smooth", block: "nearest" });
524+
?.scrollIntoView({ behavior: readReducedMotion() ? "auto" : "smooth", block: "nearest" });
524525
});
525526
}, []);
526527

‎apps/web/src/components/settings/settingsLayout.test.tsx‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,34 @@ describe("settings search targets", () => {
8787
expect(add).not.toHaveBeenCalled();
8888
});
8989

90+
it("keeps the destination and focus when the preference changes or is unavailable", () => {
91+
const scrollIntoView = vi.fn();
92+
const focus = vi.fn();
93+
const target = {
94+
tagName: "DIV",
95+
scrollIntoView,
96+
focus,
97+
classList: { remove: vi.fn(), add: vi.fn() },
98+
addEventListener: vi.fn(),
99+
offsetWidth: 100,
100+
} as unknown as HTMLElement;
101+
const getElementById = vi.fn(() => target);
102+
vi.stubGlobal("document", { getElementById });
103+
let reducedMotion = false;
104+
vi.stubGlobal("window", { matchMedia: () => ({ matches: reducedMotion }) });
105+
expect(scrollToSettingsTarget("word-wrap")).toBe(true);
106+
expect(scrollIntoView).toHaveBeenLastCalledWith({ behavior: "smooth", block: "center" });
107+
reducedMotion = true;
108+
expect(scrollToSettingsTarget("word-wrap")).toBe(true);
109+
expect(scrollIntoView).toHaveBeenLastCalledWith({ behavior: "auto", block: "center" });
110+
vi.stubGlobal("window", {});
111+
expect(scrollToSettingsTarget("word-wrap")).toBe(true);
112+
expect(scrollIntoView).toHaveBeenLastCalledWith({ behavior: "smooth", block: "center" });
113+
expect(getElementById.mock.calls).toEqual([["word-wrap"], ["word-wrap"], ["word-wrap"]]);
114+
expect(focus).toHaveBeenCalledTimes(3);
115+
expect(focus).toHaveBeenLastCalledWith({ preventScroll: true });
116+
});
117+
90118
it("leaves not-yet-mounted destinations to their mount lifecycle", () => {
91119
vi.stubGlobal("document", {
92120
getElementById: vi.fn(() => null),

0 commit comments

Comments
 (0)