Skip to content

Commit 6c3d410

Browse files
tellahoCarl
andcommitted
fix(sidebar): react to reduced-motion preference changes
Subscribe to the live media query so enabling reduced motion flushes pending orders and cancels active slides on the mounted list. Preserve normal motion when re-enabled and remove the subscription on unmount. Cover controlled-clock batching plus native cancellation and later reorders in Chromium and WebKit. Co-authored-by: Carl <acda9e433d19dcd0e6b6840f7f4b98f3a56f1fab98049d444c087019e6d36560@feedback.communities.buzz.xyz> Signed-off-by: Taylor Ho <[email protected]>
1 parent e73451e commit 6c3d410

3 files changed

Lines changed: 134 additions & 7 deletions

File tree

‎src/features/channel-navigation/ChannelSidebarRows.test.tsx‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ import { ChannelSidebarRows } from "./ChannelSidebarRows";
77
afterEach(() => {
88
cleanup();
99
vi.useRealTimers();
10+
vi.unstubAllGlobals();
11+
vi.restoreAllMocks();
1012
});
1113

1214
function rows(ids: string[]) {
@@ -128,3 +130,34 @@ it("bounds batching latency during continuous activity", async () => {
128130
targets.at(-1),
129131
);
130132
});
133+
134+
it("follows reduced-motion changes while mounted and removes its subscription", async () => {
135+
vi.useFakeTimers();
136+
const media = Object.assign(new EventTarget(), { matches: false });
137+
vi.stubGlobal("matchMedia", () => media);
138+
const remove = vi.spyOn(media, "removeEventListener");
139+
const view = render(rows(["alpha", "beta", "gamma"]));
140+
const order = () =>
141+
screen.getAllByRole("button").map((node) => node.textContent);
142+
const preference = (matches: boolean) =>
143+
act(() => {
144+
media.matches = matches;
145+
media.dispatchEvent(new Event("change"));
146+
});
147+
148+
view.rerender(rows(["beta", "alpha", "gamma"]));
149+
expect(order()).toEqual(["alpha", "beta", "gamma"]);
150+
preference(true);
151+
expect(order()).toEqual(["beta", "alpha", "gamma"]);
152+
view.rerender(rows(["gamma", "beta", "alpha"]));
153+
expect(order()).toEqual(["gamma", "beta", "alpha"]);
154+
155+
preference(false);
156+
view.rerender(rows(["alpha", "beta", "gamma"]));
157+
await act(() => vi.advanceTimersByTimeAsync(199));
158+
expect(order()).toEqual(["gamma", "beta", "alpha"]);
159+
await act(() => vi.advanceTimersByTimeAsync(1));
160+
expect(order()).toEqual(["alpha", "beta", "gamma"]);
161+
view.unmount();
162+
expect(remove).toHaveBeenCalledWith("change", expect.any(Function));
163+
});

‎src/features/channel-navigation/ChannelSidebarRows.tsx‎

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,6 @@
11
import { useDndContext } from "@dnd-kit/core";
22
import { animate } from "motion/mini";
3-
import {
4-
AnimatePresence,
5-
motion,
6-
useIsPresent,
7-
useReducedMotion,
8-
} from "motion/react";
3+
import { AnimatePresence, motion, useIsPresent } from "motion/react";
94
import {
105
forwardRef,
116
memo,
@@ -15,6 +10,7 @@ import {
1510
useLayoutEffect,
1611
useRef,
1712
useState,
13+
useSyncExternalStore,
1814
type ReactElement,
1915
} from "react";
2016
import styles from "./ChannelSidebarRows.module.css";
@@ -24,6 +20,15 @@ const animationGeneration = {};
2420

2521
type RowPositions = Map<HTMLElement, { index: number; top: number }>;
2622

23+
const reducedMotionQuery = "(prefers-reduced-motion: reduce)";
24+
function subscribeReducedMotion(change: () => void) {
25+
const media = window.matchMedia?.(reducedMotionQuery);
26+
media?.addEventListener("change", change);
27+
return () => media?.removeEventListener("change", change);
28+
}
29+
const prefersReducedMotion = () =>
30+
!!window.matchMedia?.(reducedMotionQuery).matches;
31+
2732
function clearSlide(node: HTMLElement) {
2833
if (node.style.transform && node.style.transform !== "none")
2934
node.style.transform = "none";
@@ -40,7 +45,10 @@ export function ChannelSidebarRows({
4045
open: boolean;
4146
}) {
4247
const { active } = useDndContext();
43-
const reducedMotion = useReducedMotion();
48+
const reducedMotion = useSyncExternalStore(
49+
subscribeReducedMotion,
50+
prefersReducedMotion,
51+
);
4452
const animated = open && !active && !reducedMotion;
4553
const desired = JSON.stringify(children.map((child) => String(child.key)));
4654
const [order, setOrder] = useState(desired);

‎tests/browser/navigation-sorting.spec.mjs‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,92 @@ for (const reducedMotion of ["no-preference", "reduce"]) {
158158
});
159159
}
160160

161+
// Real media-query delivery and canceling native playback require a browser.
162+
test.describe("live reduced-motion preference", () => {
163+
test.use({
164+
reducedMotion: "no-preference",
165+
initialSidebarSort: { channels: "recent" },
166+
});
167+
test("updates an already-mounted list when reduced motion changes", async ({
168+
page,
169+
app,
170+
}) => {
171+
await open(page, app);
172+
const section = page.locator('[data-sidebar-section="channels"]');
173+
const rows = section.locator("[data-channel-id]");
174+
const cedar = section.locator('[data-channel-id="cedar"]');
175+
await expect(rows.first()).toHaveAttribute("data-channel-id", "willow");
176+
await cedar.focus();
177+
const held = await holdSidebarMotion(page);
178+
try {
179+
app.activity({ channel: "cedar", kind: 45003, age: 30 });
180+
await expect(rows.first()).toHaveAttribute("data-channel-id", "cedar");
181+
await held.seek("transform");
182+
await page.emulateMedia({ reducedMotion: "reduce" });
183+
await expect(section.locator("[data-moving]")).toHaveCount(0);
184+
expect(
185+
await rows.evaluateAll((elements) =>
186+
elements.every((element) => {
187+
const row = element.closest(
188+
"[data-channel-sidebar-row]",
189+
).parentElement;
190+
const transform = new DOMMatrixReadOnly(
191+
getComputedStyle(row).transform,
192+
);
193+
return (
194+
transform.m42 === 0 &&
195+
row
196+
.getAnimations()
197+
.every(
198+
(animation) =>
199+
animation.playState !== "running" &&
200+
animation.playState !== "paused",
201+
)
202+
);
203+
}),
204+
),
205+
).toBe(true);
206+
} finally {
207+
await held.release();
208+
}
209+
// Record actual native animation creation without pausing or seeking it.
210+
const observed = await page.evaluateHandle(() => {
211+
const animate = Element.prototype.animate;
212+
const slides = [];
213+
Element.prototype.animate = function (...args) {
214+
const animation = animate.apply(this, args);
215+
if (
216+
this.closest('[data-sidebar-section="channels"]') &&
217+
animation.effect.getKeyframes().some((frame) => "transform" in frame)
218+
)
219+
slides.push(animation);
220+
return animation;
221+
};
222+
return {
223+
slides,
224+
restore() {
225+
Element.prototype.animate = animate;
226+
},
227+
};
228+
});
229+
try {
230+
app.activity({ channel: "willow", kind: 45003, age: 29 });
231+
await expect(rows.first()).toHaveAttribute("data-channel-id", "willow");
232+
expect(await observed.evaluate(({ slides }) => slides.length)).toBe(0);
233+
await page.emulateMedia({ reducedMotion: "no-preference" });
234+
await page.evaluate(() => new Promise(requestAnimationFrame));
235+
app.activity({ channel: "cedar", kind: 45003, age: 28 });
236+
await expect(rows.first()).toHaveAttribute("data-channel-id", "cedar");
237+
expect(
238+
await observed.evaluate(({ slides }) => slides.length),
239+
).toBeGreaterThan(0);
240+
await expect(cedar).toBeFocused();
241+
} finally {
242+
await observed.evaluate((state) => state.restore());
243+
}
244+
});
245+
});
246+
161247
// Hidden layout and rem-based row positions require the actual sidebar/browser.
162248
test.describe("nearby motion after layout changes", () => {
163249
test.use({ initialSidebarSort: { channels: "recent" } });

0 commit comments

Comments
 (0)