Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(motion): chat session switches are instant under reduced motion; CSS check covers every animation (MUL-9977) (#11312)
Jiayuan Zhangff7c4a36e1c6
diff --git a/packages/ui/docs/motion.md b/packages/ui/docs/motion.mdindex 5e03e167ac..8875630c91 100644--- a/packages/ui/docs/motion.md+++ b/packages/ui/docs/motion.md@@ -99,6 +99,7 @@ The Appearance setting "Reduce motion" and the system's `prefers-reduced-motion`- The Appearance setting zeroes CSS animation and transition durations for the whole document. The system setting reaches CSS only through media queries, so every CSS animation or transition also carries `motion-reduce:animate-none` or `motion-reduce:transition-none`.- JavaScript motion (motion/react, WAAPI) reads `useReducedMotion()` from `@multica/core/appearance`, or `prefersReducedMotion()` outside render, which cover both settings. With either set, pass `duration: 0` or skip the animation. motion's own `useReducedMotion` and a bare `matchMedia` check see only the system setting. `MotionProvider` at the app root makes motion/react skip transform and layout animation under either setting, but opacity and color still animate, so the `duration: 0` above still applies.- Test the reduced branch: with reduced motion, the end state is there in the same frame.+- Two checks enforce this. The `NO_SYSTEM_ONLY_REDUCED_MOTION` lint rule rejects a `prefers-reduced-motion` query string in `packages/views`, `apps/web` and `apps/desktop`. `packages/ui/styles/reduced-motion.test.ts` fails when a class in `base.css` starts an animation and no `@media (prefers-reduced-motion: reduce)` rule stops it; the few exceptions are listed in that test, each with its reason.## Do not animatediff --git a/packages/ui/docs/motion.zh.md b/packages/ui/docs/motion.zh.mdindex 45d3f85799..d4d999a8b5 100644--- a/packages/ui/docs/motion.zh.md+++ b/packages/ui/docs/motion.zh.md@@ -99,6 +99,7 @@ Dialog、AlertDialog、Sheet、Popover、DropdownMenu、ContextMenu、Select、H- 外观设置会把整个文档的 CSS 动画和过渡时长归零。系统设置只能通过媒体查询影响 CSS,所以每个 CSS 动画或过渡都要加 `motion-reduce:animate-none` 或 `motion-reduce:transition-none`。- JavaScript 动效(motion/react、WAAPI)读取 `@multica/core/appearance` 的 `useReducedMotion()`,渲染之外用 `prefersReducedMotion()`,两者都覆盖这两个设置。任一设置开启时传 `duration: 0` 或跳过动画。motion 自带的 `useReducedMotion` 和单独的 `matchMedia` 判断只能看到系统设置。应用根部的 `MotionProvider` 会让 motion/react 在任一设置开启时跳过位移和布局动画,但透明度和颜色仍会过渡,所以上面的 `duration: 0` 仍然需要。- 测试减少动态效果的分支:开启后,终点状态在同一帧出现。+- 这两条由检查兜底。`NO_SYSTEM_ONLY_REDUCED_MOTION` lint 规则拦截 `packages/views`、`apps/web` 和 `apps/desktop` 里的 `prefers-reduced-motion` 查询字符串。`base.css` 里的类只要启动了动画,却没有 `@media (prefers-reduced-motion: reduce)` 规则把它停掉,`packages/ui/styles/reduced-motion.test.ts` 就会失败;少数例外列在这个测试里,每条都写明原因。## 不要加动效diff --git a/packages/ui/styles/base.css b/packages/ui/styles/base.cssindex 96331ebec4..25336835af 100644--- a/packages/ui/styles/base.css+++ b/packages/ui/styles/base.css@@ -244,9 +244,9 @@@media (prefers-reduced-motion: reduce) {.animate-chat-enter-next,- .animate-chat-enter-prev {- animation-name: chat-enter-fade;- animation-duration: 120ms;+ .animate-chat-enter-prev,+ .animate-chat-enter-fade {+ animation: none;}}diff --git a/packages/ui/styles/reduced-motion.test.ts b/packages/ui/styles/reduced-motion.test.tsindex 541f8550bf..452ba282b2 100644--- a/packages/ui/styles/reduced-motion.test.ts+++ b/packages/ui/styles/reduced-motion.test.ts@@ -5,46 +5,157 @@ import { describe, expect, it } from "vitest";const css = readFileSync(join(__dirname, "base.css"), "utf8");-/** The bodies of every `@media (prefers-reduced-motion: reduce)` block. */-function reducedMotionBlocks(source: string): string[] {- const blocks: string[] = [];- const opener = /@media\s*\(prefers-reduced-motion:\s*reduce\)\s*\{/g;- for (let match = opener.exec(source); match; match = opener.exec(source)) {+/**+ * Animated classes that keep something under the system reduced-motion+ * setting. Each still needs a rule in `@media (prefers-reduced-motion: reduce)`;+ * the reason says why that rule is not `animation: none`.+ */+const EXCEPTIONS: Record<string, string> = {+ ".animate-skeleton":+ "Keeps only skeleton-hold, a 200ms visibility step that moves nothing, so data that lands fast still skips the placeholder. The pulse stops.",+};++const REDUCED_MEDIA = /@media\s*\(prefers-reduced-motion:\s*reduce\)\s*\{/g;++/** `[start, end)` of every `@media (prefers-reduced-motion: reduce)` block, braces included. */+function reducedMotionRanges(source: string): [number, number][] {+ const ranges: [number, number][] = [];+ for (const match of source.matchAll(REDUCED_MEDIA)) {let depth = 1;- let end = opener.lastIndex;+ let end = match.index + match[0].length;while (depth > 0 && end < source.length) {if (source[end] === "{") depth++;else if (source[end] === "}") depth--;end++;}- blocks.push(source.slice(opener.lastIndex, end - 1));+ ranges.push([match.index, end]);}- return blocks;+ return ranges;}-/** Rules inside a block as `[selectors, declarations]`. */-function rules(block: string): [string[], string][] {- return [...block.matchAll(/([^{}]+)\{([^{}]*)\}/g)].map(([, selectors, body]) => [+/** Innermost rules as `[selectors, declarations]`. */+function rules(source: string): [string[], string][] {+ return [...source.matchAll(/([^{}]+)\{([^{}]*)\}/g)].map(([, selectors, body]) => [selectors!.split(",").map((selector) => selector.trim()),body!,]);}+const STARTS_ANIMATION = /(^|;|\s)animation(-name)?:\s*(?!none\s*;)[^;]+;/;+const STOPS_ANIMATION = /(^|;|\s)(animation:\s*none|display:\s*none)\s*;/;++/**+ * Classes that start an animation outside reduced-motion blocks, and those the+ * reduced-motion blocks stop (`animation: none`, or hidden with `display: none`)+ * or otherwise restyle.+ */+function audit(withComments: string) {+ const source = withComments.replace(/\/\*[\s\S]*?\*\//g, "");+ const ranges = reducedMotionRanges(source);+ let outside = "";+ let cursor = 0;+ for (const [start, end] of ranges) {+ outside += source.slice(cursor, start);+ cursor = end;+ }+ outside += source.slice(cursor);+ const reduced = ranges.flatMap(([start, end]) => {+ const block = source.slice(start, end);+ return rules(block.slice(block.indexOf("{") + 1, -1));+ });++ const animated = new Set<string>();+ for (const [selectors, body] of rules(outside)) {+ if (!STARTS_ANIMATION.test(body)) continue;+ for (const selector of selectors) if (selector.startsWith(".")) animated.add(selector);+ }+ for (const name of source.match(/\.animate-[\w-]+/g) ?? []) animated.add(name);++ const stopped = new Set<string>();+ const restyled = new Set<string>();+ for (const [selectors, body] of reduced) {+ for (const selector of selectors) {+ restyled.add(selector);+ if (STOPS_ANIMATION.test(body)) stopped.add(selector);+ }+ }+ return { animated: [...animated].sort(), stopped, restyled };+}++/** Animated classes that would still move under the system reduced-motion setting. */+function stillMoving(source: string, exceptions: Record<string, string> = {}): string[] {+ const { animated, stopped } = audit(source);+ return animated.filter((name) => !stopped.has(name) && !(name in exceptions));+}+describe("base.css under the system reduced-motion setting", () => {- const classes = [...new Set(css.match(/\.animate-inbox-enter-[\w-]+/g))];- const reduced = reducedMotionBlocks(css).flatMap(rules);+ const { animated, restyled } = audit(css);++ it("finds the animated classes", () => {+ expect(animated).toEqual(+ expect.arrayContaining([+ ".animate-chat-enter-fade",+ ".animate-chat-enter-next",+ ".animate-chat-enter-prev",+ ".animate-chat-impulse",+ ".animate-inbox-enter-fade",+ ".animate-inbox-enter-next",+ ".animate-inbox-enter-prev",+ ".animate-nav-progress-sweep",+ ".animate-onboarding-enter",+ ".animate-skeleton",+ ".border-beam-light",+ ".multica-pop",+ ".shimmer-text-window",+ ]),+ );+ });++ it("stops every animated class, not even leaving a fade", () => {+ expect(stillMoving(css, EXCEPTIONS)).toEqual([]);+ });++ it.each(Object.keys(EXCEPTIONS))("%s is a live exception with its own reduced rule", (name) => {+ expect(animated).toContain(name);+ expect(restyled.has(name), `${name} needs a rule in @media (prefers-reduced-motion: reduce)`).toBe(true);+ });+});++describe("stillMoving", () => {+ const reduced = (body: string) => `@media (prefers-reduced-motion: reduce) {\n${body}\n}`;++ it("flags a new .animate-* class with no reduced rule", () => {+ const source = `${css}\n.animate-new-thing { animation: new-thing 150ms ease-out both; }`;+ expect(stillMoving(source, EXCEPTIONS)).toEqual([".animate-new-thing"]);+ });++ it("flags a class whose reduced rule was deleted", () => {+ const covered = ".animate-chat-enter-prev,\n .animate-chat-enter-fade {";+ expect(css).toContain(covered);+ const source = css.replace(covered, ".animate-chat-enter-prev {");+ expect(stillMoving(source, EXCEPTIONS)).toEqual([".animate-chat-enter-fade"]);+ });++ it("flags a class whose reduced rule swaps in a shorter fade", () => {+ const source = `.animate-a { animation: a-move 160ms ease-out; }\n${reduced(".animate-a { animation-name: a-fade; animation-duration: 120ms; }")}`;+ expect(stillMoving(source)).toEqual([".animate-a"]);+ });++ it("flags any class that starts an animation, not only .animate-*", () => {+ expect(stillMoving(".brand-spin { animation: spin 1s linear infinite; }")).toEqual([".brand-spin"]);+ });- it("defines the Inbox detail transitions", () => {- expect(classes.sort()).toEqual([- ".animate-inbox-enter-fade",- ".animate-inbox-enter-next",- ".animate-inbox-enter-prev",- ]);+ it("passes classes stopped with animation: none or hidden with display: none", () => {+ const source = [+ ".animate-a, .animate-b { animation: a 160ms ease-out; }",+ ".beam { animation: beam 3s linear infinite; }",+ reduced(".animate-a,\n .animate-b { animation: none; }\n .beam { display: none; }"),+ ].join("\n");+ expect(stillMoving(source)).toEqual([]);});- it.each(classes)("%s does not animate, not even as a fade", (name) => {- const rule = reduced.find(([selectors]) => selectors.includes(name));- expect(rule, `${name} needs a rule in @media (prefers-reduced-motion: reduce)`).toBeDefined();- expect(rule![1]).toMatch(/(^|;|\s)animation:\s*none\s*;/);+ it("lets a listed exception keep a reduced animation", () => {+ const source = `.animate-a { animation: a 1s infinite; }\n${reduced(".animate-a { animation: a-hold 200ms step-end; }")}`;+ expect(stillMoving(source, { ".animate-a": "test" })).toEqual([]);});});diff --git a/packages/views/chat/chat-page.test.tsx b/packages/views/chat/chat-page.test.tsxindex 203938d56c..f10f4283d4 100644--- a/packages/views/chat/chat-page.test.tsx+++ b/packages/views/chat/chat-page.test.tsx@@ -2,8 +2,9 @@import { StrictMode } from "react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import { describe, it, expect, vi, beforeEach } from "vitest";+import { describe, it, expect, vi, afterEach, beforeEach } from "vitest";import { act, fireEvent, render, screen } from "@testing-library/react";+import { useAppearanceStore } from "@multica/core/appearance";import type { Agent } from "@multica/core/types";import { I18nProvider } from "@multica/core/i18n/react";import enCommon from "../locales/en/common.json";@@ -633,6 +634,35 @@ describe("ChatPage archive and session transitions", () => {expect(prompt.parentElement?.className).toContain("animate-chat-enter-fade");});+ describe("under reduced motion", () => {+ function archiveOnlyThread() {+ mockHasMessages.current = true;+ storeRef.current = { activeSessionId: "session-only" };+ mockArchiveOutcome.current = { moved: true, targetSessionId: null, direction: null };+ renderPage("session=session-only");+ fireEvent.click(screen.getByRole("button", { name: "archive-active-thread" }));+ return screen.getByText("Pick a conversation, or start a new one with +").parentElement!;+ }+ afterEach(() => {+ useAppearanceStore.getState().reset();+ vi.unstubAllGlobals();+ });++ it("shows the select prompt at once with the Appearance Reduce motion switch", () => {+ useAppearanceStore.getState().set({ reduceMotion: true });+ expect(archiveOnlyThread().className).not.toMatch(/animate-chat-enter/);+ });++ it("shows the select prompt at once with the system reduced-motion setting", () => {+ vi.stubGlobal("matchMedia", vi.fn((query: string) => ({+ matches: query === "(prefers-reduced-motion: reduce)",+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ })));+ expect(archiveOnlyThread().className).not.toMatch(/animate-chat-enter/);+ });+ });+it("applies a gentle fade when selecting another thread directly", () => {mockHasMessages.current = true;storeRef.current = { activeSessionId: "session-1" };diff --git a/packages/views/chat/chat-page.tsx b/packages/views/chat/chat-page.tsxindex 5774f65509..d560c92a80 100644--- a/packages/views/chat/chat-page.tsx+++ b/packages/views/chat/chat-page.tsx@@ -376,15 +376,14 @@ export function ChatPage() {) : null;const hasActiveWakeup =!!c.activeSessionId && wakeups.some((w) => w.status === "active");- const emptyEnterClass = activeTransition- ? reduceMotion- ? "animate-chat-enter-fade"- : activeTransition === "next"+ const emptyEnterClass =+ activeTransition && !reduceMotion+ ? activeTransition === "next"? "animate-chat-enter-next": activeTransition === "prev"? "animate-chat-enter-prev": "animate-chat-enter-fade"- : undefined;+ : undefined;const conversation = (<div className="flex flex-1 flex-col min-h-0 @container">{c.currentSession ? (@@ -577,7 +576,7 @@ export function ChatPage() {<divclassName={cn("flex min-h-0 flex-1 flex-col items-center justify-center gap-3 text-muted-foreground",- activeTransition && "animate-chat-enter-fade",+ activeTransition && !reduceMotion && "animate-chat-enter-fade",)}><MessageSquare className="h-10 w-10 text-faint-foreground" />diff --git a/packages/views/chat/components/chat-message-list.autoscroll.test.tsx b/packages/views/chat/components/chat-message-list.autoscroll.test.tsxindex cf01c1d63e..a503bdae5c 100644--- a/packages/views/chat/components/chat-message-list.autoscroll.test.tsx+++ b/packages/views/chat/components/chat-message-list.autoscroll.test.tsx@@ -902,7 +902,7 @@ describe("ChatMessageList auto-scroll", () => {expect(observedTargets()).toHaveLength(0);});- it("defers the directional enter transition until the list reaches its live end, and degrades under reduced motion", () => {+ it("defers the directional enter transition until the list reaches its live end, and skips it under reduced motion", () => {const box = (el: Element, top: number, bottom: number) => {el.getBoundingClientRect = () => ({ top, bottom }) as DOMRect;};@@ -926,18 +926,30 @@ describe("ChatMessageList auto-scroll", () => {expect(first.scroll.el).toHaveAttribute("data-chat-enter-transition", "next");first.view.unmount();- // Under reduced motion, directional transitions degrade to pure opacity fade.- useAppearanceStore.setState({ reduceMotion: true });- try {- const reduced = renderStreamingChat({ revealKey: "enter-reduced", enterTransition: "prev" });+ // Either reduced-motion source shows the landed list at once, without even a fade.+ const landsInstantly = (revealKey: string) => {+ const reduced = renderStreamingChat({ revealKey, enterTransition: "prev" });box(reduced.scroll.el, 0, VIEWPORT);box(reduced.view.container.querySelector("[data-chat-live-end]")!, VIEWPORT - 120, VIEWPORT - 16);settleFrames(12);- expect(reduced.scroll.el.className).toContain("animate-chat-enter-fade");- expect(reduced.scroll.el.className).not.toContain("animate-chat-enter-prev");- expect(reduced.scroll.el).toHaveAttribute("data-chat-enter-transition", "fade");+ expect(reduced.scroll.el.className).not.toContain("invisible");+ expect(reduced.scroll.el.className).not.toMatch(/animate-chat-enter/);+ expect(reduced.scroll.el).not.toHaveAttribute("data-chat-enter-transition");+ reduced.view.unmount();+ };++ useAppearanceStore.setState({ reduceMotion: true });+ try {+ landsInstantly("enter-reduced-switch");} finally {useAppearanceStore.setState({ reduceMotion: false });}++ vi.stubGlobal("matchMedia", vi.fn((query: string) => ({+ matches: query === "(prefers-reduced-motion: reduce)",+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ })));+ landsInstantly("enter-reduced-system");});});diff --git a/packages/views/chat/components/chat-message-list.tsx b/packages/views/chat/components/chat-message-list.tsxindex c887428234..4a6fd18227 100644--- a/packages/views/chat/components/chat-message-list.tsx+++ b/packages/views/chat/components/chat-message-list.tsx@@ -81,7 +81,7 @@ interface ChatMessageListProps {* Subtle reveal transition played once the list has landed at the live end* (`hasReachedLiveEnd`): directional glide for archive-advance (`"next"` /* `"prev"`), or gentle opacity fade for direct session switches (`"fade"`).- * Respects `prefers-reduced-motion` by degrading directional glides to fade.+ * Skipped entirely under reduced motion (Appearance switch or system setting).*/enterTransition?: ChatMessageEnterTransition | null;/** The list became visible to the reader — on reveal, and on each reactivation after it. */@@ -249,16 +249,15 @@ export function ChatMessageList({// grazes full-bleed previews (image / HTML) at the edges.const fadeStyle = useScrollFade(scrollRef, 16);const reduceMotion = useReducedMotion();+ const playedTransition = hasReachedLiveEnd && !reduceMotion ? enterTransition : null;const enterClass =- hasReachedLiveEnd && enterTransition- ? reduceMotion- ? "animate-chat-enter-fade"- : enterTransition === "next"- ? "animate-chat-enter-next"- : enterTransition === "prev"- ? "animate-chat-enter-prev"- : "animate-chat-enter-fade"- : undefined;+ playedTransition === "next"+ ? "animate-chat-enter-next"+ : playedTransition === "prev"+ ? "animate-chat-enter-prev"+ : playedTransition === "fade"+ ? "animate-chat-enter-fade"+ : undefined;const pendingTaskId = pendingTask?.task_id ?? null;const wakeupsBySourceTask = useWakeupsBySourceTask(wakeups);@@ -392,7 +391,7 @@ export function ChatMessageList({<divref={setScrollContainerRef}data-tab-scroll-root- data-chat-enter-transition={hasReachedLiveEnd && enterTransition ? (reduceMotion ? "fade" : enterTransition) : undefined}+ data-chat-enter-transition={playedTransition ?? undefined}style={fadeStyle}// The gutter lives on the scroll container, so it applies once to the// whole list — rows, header, footer — and the scrollbar still rides the