Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
docs(ui): motion rules, and frame-by-frame motion checks with 2x GIFs (MUL-9957) (#11288)
Jiayuan Zhang4c110971b29e
diff --git a/.github/ci-paths.json b/.github/ci-paths.jsonindex e3edcf7cbd..d061a65d58 100644--- a/.github/ci-paths.json+++ b/.github/ci-paths.json@@ -113,6 +113,7 @@"knip.jsonc","scripts/*.mjs","scripts/brand/*.mjs",+ "scripts/motion/*.mjs","scripts/pr-shots","server/cmd/multica/cmd_auth.go","docs/assets/logo-*.svg",diff --git a/AGENTS.md b/AGENTS.mdindex ace6878443..17dec3d897 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -119,6 +119,7 @@ Workspace-scoped queries filter by `workspace_id`; membership gates access and `## Web/Desktop UI Rules- For Button and Dialog usage, read `packages/ui/docs/button.md` and `packages/ui/docs/dialog.md`.+- Before building or reviewing an interaction that changes layout (overlays, expand/collapse, list rows, content switches, selection indicators, value feedback), read `packages/ui/docs/motion.md`: tokens, reduced motion, where not to animate, and the shared primitives. Such a PR attaches a GIF and the frame-sampling results from `scripts/motion/capture.mjs`.- Prefer existing shadcn/Base UI primitives. Add components with `pnpm ui:add <component>`.- For `pnpm ui:add @reui/<name>`, decline overwrite prompts. Keep `REUI_LICENSE_KEY` in the environment, never in repo files. Adapt vendored primitives into `packages/ui/components/ui/` and compositions into `packages/views/`.- Import icons from `@multica/ui/icons`; no icon library is installed. If the icon you need is missing, draw it by following `.agents/skills/multica-icons/SKILL.md`. Do not substitute an inline SVG or an emoji. Rewrite icon imports in `ui:add` output before committing. Exception: proportional-width optical keycap glyphs live exclusively in `KBD_GLYPHS` inside `packages/ui/components/ui/kbd.tsx` and are only for `<Kbd>`.diff --git a/knip.jsonc b/knip.jsoncindex 8bccf10da0..a1ef9e2878 100644--- a/knip.jsonc+++ b/knip.jsonc@@ -19,8 +19,8 @@"workspaces": {".": {- "entry": ["scripts/*.mjs", "scripts/brand/*.mjs"],- "project": ["scripts/*.mjs", "scripts/brand/*.mjs"],+ "entry": ["scripts/*.mjs", "scripts/brand/*.mjs", "scripts/motion/*.mjs"],+ "project": ["scripts/*.mjs", "scripts/brand/*.mjs", "scripts/motion/*.mjs"],// scripts/theme-preview.mjs drives Tailwind through the PostCSS API; the// root has no Tailwind stylesheets for the plugin to read."tailwind": falsediff --git a/packages/ui/docs/motion.md b/packages/ui/docs/motion.mdnew file mode 100644index 0000000000..1a745b04ff--- /dev/null+++ b/packages/ui/docs/motion.md@@ -0,0 +1,138 @@+# Motion++Import durations and curves from `@multica/ui/lib/motion`.++## Usage++Motion explains a change where it happens: where the selection went, what opened, what was removed, why the content below moved. Every interaction that changes layout in response to the user or to live data gets motion by default; a feature is not done when it only works.++| Token | Value | Use |+| --- | --- | --- |+| `UI_MOTION_DURATION.micro` | 100ms | Exits, icon swaps, hover and press feedback |+| `UI_MOTION_DURATION.fast` | 150ms | Entries, row add/remove, small size changes |+| `UI_MOTION_DURATION.standard` | 200ms | Indicators, expand/collapse, container size changes |+| `UI_EASE_OUT` / `UI_EASE_OUT_CSS` | `cubic-bezier(0.23, 1, 0.32, 1)` | Anything entering, moving or resizing |+| `UI_EASE_IN` | `cubic-bezier(0.4, 0, 1, 1)` | Anything leaving |++- Keep UI motion at 200ms or less. An exit is shorter than its entry.+- Never block input. A click during an animation acts on the end state, and the animation retargets from where it is.+- In class names, write the curve as `ease-[cubic-bezier(0.23,1,0.32,1)]`; in JavaScript, use the constants.++## Rules by interaction++### Overlays++Dialog, AlertDialog, Sheet, Popover, DropdownMenu, ContextMenu, Select, HoverCard, Tooltip.++- Enter: fade and scale from 95% toward the trigger (Sheet slides in from its edge), 100–150ms, `UI_EASE_OUT`. Exit: reverse, at most as long.+- Use the components in `packages/ui/components/ui/` as they are. Dialog timing lives in the `--dialog-*` tokens (`dialog.md`); do not override an overlay's animation at a call site.+- Keep the content mounted until the exit finishes. Do not gate the popup's children with `{open && …}`, and do not unmount the root when it closes. Base UI's Portal unmounts after the exit. A host that renders one modal at a time keeps the last modal and its data until `onOpenChangeComplete(false)`.+- Tooltips that open instantly while the pointer moves across a toolbar skip their animation (`data-[instant]:animate-none`).++### Expand and collapse++Sections, tree nodes, disclosures, "Show N more", inline hints.++- Animate height and opacity together, 150–200ms, `UI_EASE_OUT`. The content below moves with the change; it never jumps.+- Rotate one `ChevronRight` by 90° on the same duration. Do not swap two icons.+- Use `CollapsibleContent`. For a conditional block outside a Collapsible, use a `grid-rows-[0fr]` → `grid-rows-[1fr]` transition, as `CreateRunHint` in `packages/views/modals/create-issue.tsx` does, or motion's `height: "auto"`.++### List rows added and removed++Archive, complete, snooze, a new notification, a new run.++- A removed row collapses its height, margins and opacity, 150ms, `UI_EASE_OUT`, inside `AnimatePresence initial={false}`. Rows below close the gap; they do not jump.+- A row the user just added, or one that arrived live, fades in, with at most 4px of upward movement, 150ms.+- Rows on first render and rows a virtual list mounts while scrolling never animate.++### Content switch++Tabs, views, a filter that changes a list, the next or previous item in a detail pane.++- The old content fades out (100ms, `UI_EASE_IN`), then the new content fades in (150ms, `UI_EASE_OUT`).+- While the next content loads, the container keeps its height, then eases to the new height (200ms). It never collapses to 0 and grows back.+- Slide only when the order means something, such as next and previous: at most 12px, 160ms (`.animate-inbox-enter-next` / `-prev`).+- A loading placeholder uses `.animate-skeleton`, which stays hidden for its first 200ms, so fast data never flashes a skeleton.++### Selected-state indicator++Tabs and segmented controls.++- The indicator moves from the old option to the new one; the labels stay put. Use the indicator the shared control renders (`Tabs`, `SegmentedToggle`), with the transition it ships. Do not build a per-call-site indicator.+- Controls whose labels change width during the switch, such as tabs that show only an icon while closed, or a header that gains or loses a button, cannot use a layout animation: it measures a box that is still moving and overshoots. Measure the start and end of every part once before paint, animate them all on one curve, and tween the indicator on that same curve and duration from where it is straight to the new tab's measured end box. Do not derive it from the boxes while they move: blending moving boxes bulges past the end when the new tab starts far from where it settles. `useTabSwitchMotion` in `packages/views/inbox/components/inbox-tabs.tsx` is the reference.++### State and value feedback++Counts, progress, copy, send/stop, save state, toggles.++- Numbers that change in place use `NumberFlow`.+- Progress bars and rings transition the property that changes (`transition-[width]`, `transition-[stroke-dashoffset]`), 150–200ms.+- An icon that swaps to confirm an action (copy → check, send → stop) crossfades with a small scale, about 140ms: `CopyCheckIcon` for copy.+- Color and background state changes use `transition-colors`.++## Reduced motion++The Appearance setting "Reduce motion" and the system's `prefers-reduced-motion` both mean instant: no movement, no size animation, no fade in its place.++- 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.++## Do not animate++These stay instant:++- Switching the body of a Desktop tab (`tab-content.tsx`).+- J/K and other rapid keyboard navigation, such as stepping through issues in `IssuePeek`.+- Rows a virtualized list mounts while scrolling or restoring history. Only content that arrives live, or that the user just triggered, may animate.+- Anything that follows the pointer: resizing panels by drag (`data-sidebar-resizing`, `data-resizing`), and panning or zooming a canvas.++## Performance++- In Virtuoso and other virtualized lists, animate only rows that arrived live or that the user just acted on, once, with WAAPI on the row (`useNewRunIds`, `useRunCommentMotion`). Do not wrap long virtualized content in Base UI's `Collapsible.Panel`.+- Do not read layout on every frame of an animation: no `getBoundingClientRect()` in `onUpdate` or a `requestAnimationFrame` loop. Measure once in a layout effect, then animate between the measured values.+- Prefer `transform` and `opacity`. Animate width or height only on the container whose size actually changes.+- Pause looping motion while it is off screen (`useRunAnimationVisibility`).++## Shared primitives++| Need | Use | Where |+| --- | --- | --- |+| Durations and curves | `UI_MOTION_DURATION`, `UI_EASE_OUT`, `UI_EASE_IN`, `UI_INDICATOR_SPRING` (selected-state indicators) | `packages/ui/lib/motion.ts` |+| Overlay enter and exit | The overlay components; Dialog's `--dialog-*` tokens | `packages/ui/components/ui/`, `packages/ui/styles/tokens.css` |+| Expand and collapse | `CollapsibleContent` | `packages/ui/components/ui/collapsible.tsx` |+| Tabs indicator | `Tabs` | `packages/ui/components/ui/tabs.tsx` |+| Segmented control indicator | `SegmentedToggle` | `packages/views/common/segmented-toggle.tsx` |+| Reduced motion for motion/react | `MotionProvider` (mounted at the web and desktop roots) | `packages/views/common/motion-provider.tsx` |+| Tabs whose labels fold and unfold | `useTabSwitchMotion` | `packages/views/inbox/components/inbox-tabs.tsx` |+| Content switch that keeps its height while loading | `InboxTabBody` (pattern; extract it when a second caller needs it) | `packages/views/layout/panels/inbox-section.tsx` |+| Row exit collapse | Inbox row `motion.li` exit | `packages/views/layout/panels/inbox-section.tsx` |+| Right sidebar open and close | `AnimatedRightSidebar` | `packages/views/layout/animated-right-sidebar.tsx` |+| Next and previous detail | `.animate-inbox-enter-next`, `-prev`, `-fade` | `packages/ui/styles/base.css` |+| Live arrivals in virtualized lists | `useNewRunIds`, `useRunCommentMotion`, `useRunDisclosureMotion` | `packages/views/issues/components/use-run-comment-motion.ts` |+| Changing numbers | `NumberFlow` | `packages/ui/components/ui/number-flow.tsx` |+| Copy confirmation | `CopyCheckIcon` | `packages/ui/components/common/copy-check-icon.tsx` |+| Loading placeholder | `.animate-skeleton` | `packages/ui/styles/base.css` |++Add a row when you add a primitive, and point the rules above at it.++## Verification++jsdom has no layout, so unit tests cover wiring and the reduced-motion branch, not the animation. A static screenshot cannot show a jump or an overshoot either.++A UI PR whose interaction changes size, position, or what is on screen attaches a GIF of it and the results of a frame-by-frame sample from the real app. `scripts/motion/capture.mjs` does both against a `make up` environment; `scripts/motion/inbox-tabs.mjs` is a complete scenario to copy:++```bash+make up C=api,web ARGS="--ephemeral"+make env-exec ARGS="-- node scripts/dev-fixtures.mjs sidebar"+make env-exec ARGS="-- node scripts/motion/capture.mjs scripts/motion/inbox-tabs.mjs --out ../motion"+```++A scenario samples the boxes of the elements involved on every animation frame and checks, by default:++- an indicator ends exactly on its target and never overshoots on the way (`landsOn`, `monotonic`);+- a container's height changes in one direction, over several frames (`monotonic`, `animated`);+- the block below never jumps away and back (`monotonic`);+- with reduced motion, every change lands in a single frame (`instant`).++Hold the first request of a tab or page with `delay()` to reproduce what happens while it loads. The script's header lists its options and its limits.diff --git a/packages/ui/docs/motion.zh.md b/packages/ui/docs/motion.zh.mdnew file mode 100644index 0000000000..ce43799117--- /dev/null+++ b/packages/ui/docs/motion.zh.md@@ -0,0 +1,138 @@+# 动效++时长和曲线从 `@multica/ui/lib/motion` 导入。++## 使用规则++动效在变化发生的地方交代变化:选中项去了哪里,什么打开了,什么被移除了,下方内容为什么移动。凡是响应用户操作或实时数据、改变布局的交互,默认都要有动效;只是「能用」的功能还没做完。++| Token | 取值 | 用途 |+| --- | --- | --- |+| `UI_MOTION_DURATION.micro` | 100ms | 退场、图标切换、悬停和按压反馈 |+| `UI_MOTION_DURATION.fast` | 150ms | 进场、增删行、小幅尺寸变化 |+| `UI_MOTION_DURATION.standard` | 200ms | 指示器、展开折叠、容器尺寸变化 |+| `UI_EASE_OUT` / `UI_EASE_OUT_CSS` | `cubic-bezier(0.23, 1, 0.32, 1)` | 进场、移动和尺寸变化 |+| `UI_EASE_IN` | `cubic-bezier(0.4, 0, 1, 1)` | 退场 |++- 界面动效不超过 200ms。退场比进场短。+- 不阻塞输入。动画过程中的点击按终点状态生效,动画从当前位置转向新目标。+- 在 class 中写成 `ease-[cubic-bezier(0.23,1,0.32,1)]`;在 JavaScript 中使用常量。++## 按交互类型的规则++### 浮层++Dialog、AlertDialog、Sheet、Popover、DropdownMenu、ContextMenu、Select、HoverCard、Tooltip。++- 进场:淡入,并朝触发元素从 95% 缩放到 100%(Sheet 从所在边滑入),100–150ms,`UI_EASE_OUT`。退场反向,时长不超过进场。+- 直接使用 `packages/ui/components/ui/` 中的组件。Dialog 的时长和曲线在 `--dialog-*` token 中(见 `dialog.md`);不要在调用处覆盖浮层动画。+- 退场结束前保持内容挂载。不要用 `{open && …}` 包住弹层内容,也不要在关闭时卸载根组件;Base UI 的 Portal 会在退场后卸载。一次只渲染一个弹窗的宿主,要保留上一个弹窗及其数据,直到 `onOpenChangeComplete(false)`。+- 指针扫过工具栏时立即打开的 Tooltip 跳过动画(`data-[instant]:animate-none`)。++### 展开折叠++区块、树节点、详情展开、「显示更多」、行内提示。++- 高度和透明度一起过渡,150–200ms,`UI_EASE_OUT`。下方内容跟着移动,不跳变。+- 用同样的时长把一个 `ChevronRight` 旋转 90°,不要切换两个图标。+- 使用 `CollapsibleContent`。不在 Collapsible 中的条件内容,用 `grid-rows-[0fr]` → `grid-rows-[1fr]` 过渡(参考 `packages/views/modals/create-issue.tsx` 中的 `CreateRunHint`),或 motion 的 `height: "auto"`。++### 列表增删行++归档、完成、延后、新通知、新运行。++- 移除的行收起高度、外边距和透明度,150ms,`UI_EASE_OUT`,放在 `AnimatePresence initial={false}` 中。下方的行补上空位,不跳变。+- 用户刚添加或实时到达的行淡入,最多向上移动 4px,150ms。+- 首次渲染的行,以及虚拟列表滚动时挂载的行,一律不加动效。++### 内容切换++标签、视图、改变列表的筛选、详情面板的上一项和下一项。++- 旧内容淡出(100ms,`UI_EASE_IN`),新内容再淡入(150ms,`UI_EASE_OUT`)。+- 新内容加载期间,容器保持原高度,加载完成后过渡到新高度(200ms)。不要先塌成 0 再撑开。+- 只有顺序有含义时才滑动,比如上一项和下一项:最多 12px,160ms(`.animate-inbox-enter-next` / `-prev`)。+- 加载占位使用 `.animate-skeleton`,前 200ms 不显示,数据很快到达时不会闪出骨架屏。++### 选中态指示器++标签和分段控件。++- 指示器从旧选项移到新选项,标签文字不动。使用共享控件(`Tabs`、`SegmentedToggle`)自带的指示器和过渡,不要在调用处自己做指示器。+- 切换时标签宽度会变的控件,不能用 layout 动画。比如关闭时只显示图标的标签,或 header 多出、少了一个按钮。layout 动画量到的是仍在移动的盒子,会冲过头。应在绘制前一次性量好每个部分的起点和终点,所有部分走同一条曲线;指示器用同一条曲线和时长,从当前位置直接过渡到新标签量好的终点。不要跟着移动中的盒子推算指示器:混合移动中的盒子,在新标签起点离终点较远时会冲过头。参考 `packages/views/inbox/components/inbox-tabs.tsx` 中的 `useTabSwitchMotion`。++### 状态与数值反馈++计数、进度、复制、发送/停止、保存状态、开关。++- 原地变化的数字使用 `NumberFlow`。+- 进度条和进度环过渡发生变化的属性(`transition-[width]`、`transition-[stroke-dashoffset]`),150–200ms。+- 确认操作的图标切换(复制 → 勾、发送 → 停止)交叉淡入并带轻微缩放,约 140ms;复制使用 `CopyCheckIcon`。+- 颜色和背景的状态变化使用 `transition-colors`。++## 减少动态效果++外观设置中的「减少动态效果」和系统的 `prefers-reduced-motion` 都表示瞬切:不移动,不做尺寸动画,也不用淡入淡出代替。++- 外观设置会把整个文档的 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` 仍然需要。+- 测试减少动态效果的分支:开启后,终点状态在同一帧出现。++## 不要加动效++以下场景保持瞬切:++- Desktop 标签正文切换(`tab-content.tsx`)。+- J/K 等高频键盘导航,比如在 `IssuePeek` 中逐个翻看 Issue。+- 虚拟列表在滚动或恢复历史时挂载的行。只有实时到达、或用户刚触发的内容可以加动效。+- 跟随指针的操作:拖拽调整面板尺寸(`data-sidebar-resizing`、`data-resizing`),以及画布的平移和缩放。++## 性能++- 在 Virtuoso 等虚拟列表中,只给实时到达或用户刚操作的行加动效,在行上用 WAAPI 播放一次(`useNewRunIds`、`useRunCommentMotion`)。不要用 Base UI 的 `Collapsible.Panel` 包住虚拟列表中的长内容。+- 动画期间不要每帧读布局:不要在 `onUpdate` 或 `requestAnimationFrame` 循环中调用 `getBoundingClientRect()`。在 layout effect 中量一次,然后在量好的值之间做动画。+- 优先使用 `transform` 和 `opacity`。只对尺寸真正变化的容器做宽高动画。+- 循环动效离开屏幕时暂停(`useRunAnimationVisibility`)。++## 共享原语++| 需求 | 使用 | 位置 |+| --- | --- | --- |+| 时长和曲线 | `UI_MOTION_DURATION`、`UI_EASE_OUT`、`UI_EASE_IN`、`UI_INDICATOR_SPRING`(选中态指示器) | `packages/ui/lib/motion.ts` |+| 浮层进退场 | 浮层组件;Dialog 的 `--dialog-*` token | `packages/ui/components/ui/`、`packages/ui/styles/tokens.css` |+| 展开折叠 | `CollapsibleContent` | `packages/ui/components/ui/collapsible.tsx` |+| 标签指示器 | `Tabs` | `packages/ui/components/ui/tabs.tsx` |+| 分段控件指示器 | `SegmentedToggle` | `packages/views/common/segmented-toggle.tsx` |+| motion/react 的减少动态效果 | `MotionProvider`(挂在 web 和桌面端根部) | `packages/views/common/motion-provider.tsx` |+| 标签名会展开收起的标签 | `useTabSwitchMotion` | `packages/views/inbox/components/inbox-tabs.tsx` |+| 加载期间保持高度的内容切换 | `InboxTabBody`(模式;出现第二个使用者时再抽成原语) | `packages/views/layout/panels/inbox-section.tsx` |+| 行退场收起 | Inbox 行的 `motion.li` 退场 | `packages/views/layout/panels/inbox-section.tsx` |+| 右侧栏展开收起 | `AnimatedRightSidebar` | `packages/views/layout/animated-right-sidebar.tsx` |+| 详情的上一项和下一项 | `.animate-inbox-enter-next`、`-prev`、`-fade` | `packages/ui/styles/base.css` |+| 虚拟列表中的实时到达 | `useNewRunIds`、`useRunCommentMotion`、`useRunDisclosureMotion` | `packages/views/issues/components/use-run-comment-motion.ts` |+| 变化的数字 | `NumberFlow` | `packages/ui/components/ui/number-flow.tsx` |+| 复制确认 | `CopyCheckIcon` | `packages/ui/components/common/copy-check-icon.tsx` |+| 加载占位 | `.animate-skeleton` | `packages/ui/styles/base.css` |++新增原语时在表中加一行,并让上面的规则指向它。++## 验证++jsdom 没有布局,单元测试只能覆盖接线和减少动态效果的分支,测不了动画本身。静态截图也看不出跳变和冲过头。++UI PR 只要包含改变尺寸、位置或显示内容的交互,就附上这段交互的 GIF,以及在真实应用中逐帧采样的结果。`scripts/motion/capture.mjs` 在 `make up` 环境中完成这两件事;`scripts/motion/inbox-tabs.mjs` 是可以照着写的完整场景:++```bash+make up C=api,web ARGS="--ephemeral"+make env-exec ARGS="-- node scripts/dev-fixtures.mjs sidebar"+make env-exec ARGS="-- node scripts/motion/capture.mjs scripts/motion/inbox-tabs.mjs --out ../motion"+```++场景在每个动画帧记录相关元素的位置和尺寸,默认检查:++- 指示器终点准确落在目标上,途中不冲过头(`landsOn`、`monotonic`);+- 容器高度单向变化,并且分布在多帧中(`monotonic`、`animated`);+- 下方区块不会跳开再跳回(`monotonic`);+- 减少动态效果时,每个变化都在一帧内完成(`instant`)。++用 `delay()` 拖住标签或页面的首个请求,复现加载期间的表现。脚本开头的注释列出了选项和限制。diff --git a/scripts/ci-scope.test.mjs b/scripts/ci-scope.test.mjsindex 153f8ff5c5..af0a1094a7 100644--- a/scripts/ci-scope.test.mjs+++ b/scripts/ci-scope.test.mjs@@ -66,6 +66,7 @@ for (const [name, files, selected] of [["mobile brand copy", ["apps/mobile/components/brand/multica-logo.tsx"], ["quality"]],["README logo", ["docs/assets/logo-dark.svg"], ["quality"]],["brand generator", ["scripts/brand/sync.mjs"], ["quality"]],+ ["motion checks", ["scripts/motion/checks.test.mjs"], ["quality"]],["PR evidence uploader", ["scripts/pr-shots"], ["quality"]],["cross-module runtime contract", ["packages/core/runtimes/cli-version.ts"], ["frontend", "backend", "runtime", "quality", "e2e"]],["inbox type contract", ["packages/core/types/inbox.ts"], ["frontend", "backend", "quality", "e2e"]],diff --git a/scripts/motion/capture.mjs b/scripts/motion/capture.mjsnew file mode 100644index 0000000000..94af24abdb--- /dev/null+++ b/scripts/motion/capture.mjs@@ -0,0 +1,288 @@+#!/usr/bin/env node+/**+ * Verify UI motion in the running web app: sample element boxes every+ * animation frame, check the samples, and record a 2x GIF of the same+ * interaction. Static screenshots cannot show a jump, an overshoot or a+ * motion that ignores reduced motion, and jsdom has no layout to animate.+ *+ * make up C=api,web ARGS="--ephemeral"+ * make env-exec ARGS="-- node scripts/motion/capture.mjs scripts/motion/inbox-tabs.mjs --out ../motion"+ *+ * The rules this checks, and when a UI PR needs it, are in+ * packages/ui/docs/motion.md.+ *+ * A scenario is an ES module whose default export receives:+ *+ * open(path, options) a signed-in page at /<workspace><path>, in a fresh+ * browser context at deviceScaleFactor 2. Options:+ * reducedMotion, locale, theme ("light" | "dark"),+ * viewport, storage (extra localStorage entries).+ * sample(page, label, targets, action, options)+ * records the box of every target (name → CSS+ * selector, first match) on each animation frame from+ * before `action()` until nothing has moved for+ * `quietMs` (default 400). Returns the frames.+ * record(page, name, clip, action, options)+ * writes <out>/<name>.gif of `clip` (a selector or+ * { x, y, width, height }) while `action()` runs.+ * delay(page, urlGlob, ms, { times })+ * holds matching requests, to reproduce a slow load.+ * check(label, result) adds a line to the report; results come from+ * scripts/motion/checks.mjs, passed in as `checks`.+ * api(method, path, body), slug, out, args, log+ *+ * Output in --out: report.json (every check and every sampled frame) and the+ * GIFs. The exit code is 1 when a check failed.+ *+ * Options:+ * --out DIR output directory (default ../motion, outside the checkout)+ * --url URL app origin (default this environment's web port)+ * Any other argument after the scenario path goes to the scenario as `args`.+ *+ * Limits:+ * - Sample and record in separate passes. Each screenshot delays animation+ * frames, so frame counts from a recorded pass are wrong.+ * - Headless Chromium runs animation frames at 120Hz: a 200ms tween spans+ * about 24 sampled frames.+ * - A 2x screenshot of a panel-sized region takes about 40ms, so GIFs come+ * out at roughly 20–25fps, fewer on a busy machine. The GIF keeps the real+ * timing whatever the rate, and the log prints the rate reached. Judge+ * smoothness from the samples, not the GIF. A shot without a clip is 1x.+ * - Web only. For Desktop, drive the app with scripts/desktop-cdp.mjs.+ */+import { createRequire } from "node:module";+import { execFileSync, spawnSync } from "node:child_process";+import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { homedir } from "node:os";+import { join, resolve } from "node:path";+import { pathToFileURL } from "node:url";++import * as checks from "./checks.mjs";++const repoRoot = execFileSync("git", ["rev-parse", "--show-toplevel"]).toString().trim();+const { chromium } = createRequire(join(repoRoot, "package.json"))("@playwright/test");++function fail(message) {+ console.error(`[motion] ${message}`);+ process.exit(1);+}+const log = (message) => console.log(`[motion] ${message}`);++const argv = process.argv.slice(2);+const options = { out: resolve(repoRoot, "../motion"), url: "", scenario: "", args: [] };+for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg === "--out") options.out = resolve(argv[++i]);+ else if (arg === "--url") options.url = argv[++i];+ else if (options.scenario) options.args.push(arg);+ else if (arg.startsWith("--")) fail(`unknown option ${arg}`);+ else options.scenario = resolve(arg);+}+if (!options.scenario) fail("usage: capture.mjs [--out DIR] [--url URL] <scenario.mjs> [scenario args...]");++const env = process.env;+if (!env.PORT || !/^dev-/.test(env.MULTICA_DEV_PROFILE ?? "")) {+ fail('run through `make env-exec ARGS="-- node scripts/motion/capture.mjs ..."`.');+}+const base = (options.url || `http://localhost:${env.FRONTEND_PORT}`).replace(/\/+$/, "");+const profilesHome = env.MULTICA_DEV_PROFILES_HOME || join(homedir(), ".multica", "profiles");+const profile = JSON.parse(readFileSync(join(profilesHome, env.MULTICA_DEV_PROFILE, "config.json"), "utf8"));+const slug = JSON.parse(execFileSync("bash", [join(repoRoot, "scripts", "dev-env.sh"), "status", "--json"]).toString()).workspace_slug;++async function api(method, path, body) {+ const response = await fetch(`http://localhost:${env.PORT}${path}`, {+ method,+ headers: { Authorization: `Bearer ${profile.token}`, "X-Workspace-ID": profile.workspace_id, "Content-Type": "application/json" },+ body: body ? JSON.stringify(body) : undefined,+ });+ if (!response.ok) throw new Error(`${method} ${path}: ${response.status} ${await response.text()}`);+ return response.status === 204 ? null : response.json();+}++const SCALE = 2;+const browser = await chromium.launch();+const contexts = [];++async function open(path, { reducedMotion = false, locale = "en-US", theme = "light", viewport = { width: 1440, height: 900 }, storage = {} } = {}) {+ const context = await browser.newContext({+ viewport,+ locale,+ deviceScaleFactor: SCALE,+ colorScheme: theme,+ reducedMotion: reducedMotion ? "reduce" : "no-preference",+ });+ contexts.push(context);+ await context.addInitScript(+ ([token, theme, storage]) => {+ localStorage.setItem("multica_token", token);+ localStorage.setItem("theme", theme);+ localStorage.setItem("multica:chat:isOpen", "false");+ for (const [key, value] of Object.entries(storage)) localStorage.setItem(key, value);+ },+ [profile.token, theme, storage],+ );+ const page = await context.newPage();+ await page.goto(`${base}/${slug}${path}`, { waitUntil: "domcontentloaded" });+ // The Next.js dev indicator sits over the bottom-left corner of every frame.+ await page.addStyleTag({ content: "nextjs-portal { display: none !important; }" });+ return page;+}++const samples = [];+async function sample(page, label, targets, action, { quietMs = 400, timeoutMs = 8000 } = {}) {+ await page.evaluate((targets) => {+ const state = { frames: [], lastChange: performance.now(), actionDone: Infinity, stopped: false, previous: "" };+ window.__motionSampler = state;+ const t0 = performance.now();+ const frame = (now) => {+ if (state.stopped) return;+ const rects = {};+ for (const [name, selector] of Object.entries(targets)) {+ const el = document.querySelector(selector);+ const r = el?.getBoundingClientRect();+ rects[name] = r ? { x: r.x, y: r.y, w: r.width, h: r.height } : null;+ }+ const key = JSON.stringify(rects);+ if (key !== state.previous) state.lastChange = now;+ state.previous = key;+ state.frames.push({ t: Math.round((now - t0) * 10) / 10, rects });+ requestAnimationFrame(frame);+ };+ requestAnimationFrame(frame);+ }, targets);+ await page.waitForFunction(() => window.__motionSampler.frames.length >= 2);+ await action();+ await page.evaluate(() => { window.__motionSampler.actionDone = performance.now(); });+ try {+ await page.waitForFunction(+ (quietMs) => {+ const state = window.__motionSampler;+ return performance.now() - Math.max(state.lastChange, state.actionDone) >= quietMs;+ },+ quietMs,+ { timeout: timeoutMs, polling: 50 },+ );+ } catch {+ log(`${label}: still moving after ${timeoutMs}ms; the report holds what was sampled`);+ }+ const frames = await page.evaluate(() => {+ window.__motionSampler.stopped = true;+ return window.__motionSampler.frames;+ });+ samples.push({ label, targets, frames });+ return frames;+}++const results = [];+function check(label, result) {+ results.push({ label, ...result });+ console.log(`${result.ok ? "PASS" : "FAIL"} ${label} — ${result.detail}`);+}++async function delay(page, urlGlob, ms, { times = 1 } = {}) {+ await page.route(urlGlob, async (route) => {+ await new Promise((r) => setTimeout(r, ms));+ await route.continue();+ }, { times });+}++/**+ * Screenshots of one region, taken back to back through CDP and joined with+ * ffmpeg. The clip's `scale` is output pixels per CSS pixel, so the GIF is 2x;+ * a CDP screencast is 1x only, and scaling the page with CSS `zoom` doubles+ * every getBoundingClientRect() a sampling pass reads.+ */+async function record(page, name, clip, action, { fps = 35, leadMs = 250, tailMs = 700, padding = 0 } = {}) {+ let rect = clip;+ if (typeof clip === "string") {+ const box = await page.locator(clip).first().boundingBox();+ if (!box) throw new Error(`record ${name}: ${clip} is not on the page`);+ rect = box;+ }+ rect = {+ x: Math.max(0, Math.floor(rect.x - padding)),+ y: Math.max(0, Math.floor(rect.y - padding)),+ width: Math.ceil(rect.width + padding * 2),+ height: Math.ceil(rect.height + padding * 2),+ };+ const cdp = await page.context().newCDPSession(page);+ const shots = [];+ let done = false;+ const interval = 1000 / fps;+ const capture = (async () => {+ while (!done) {+ const started = Date.now();+ // JPEG encodes faster than PNG at 2x; the GIF palette absorbs its artifacts.+ const { data } = await cdp.send("Page.captureScreenshot", {+ format: "jpeg",+ quality: 92,+ clip: { ...rect, scale: SCALE },+ optimizeForSpeed: true,+ });+ shots.push({ t: started, data });+ const wait = interval - (Date.now() - started);+ if (wait > 0) await new Promise((r) => setTimeout(r, wait));+ }+ })();+ try {+ await new Promise((r) => setTimeout(r, leadMs));+ await action();+ await new Promise((r) => setTimeout(r, tailMs));+ } finally {+ done = true;+ await capture.catch(() => {});+ await cdp.detach().catch(() => {});+ }++ const dir = join(options.out, `${name}.frames`);+ rmSync(dir, { recursive: true, force: true });+ mkdirSync(dir, { recursive: true });+ const lines = ["ffconcat version 1.0"];+ shots.forEach((shot, i) => {+ const file = `${String(i).padStart(5, "0")}.jpg`;+ writeFileSync(join(dir, file), Buffer.from(shot.data, "base64"));+ const next = shots[i + 1]?.t ?? shot.t + 1000;+ lines.push(`file '${file}'`, `duration ${((next - shot.t) / 1000).toFixed(3)}`);+ });+ // The concat demuxer drops the last entry's duration unless it is listed again.+ lines.push(`file '${String(shots.length - 1).padStart(5, "0")}.jpg'`);+ writeFileSync(join(dir, "frames.ffconcat"), `${lines.join("\n")}\n`);++ const gif = join(options.out, `${name}.gif`);+ const ffmpeg = [+ "-y", "-loglevel", "error", "-f", "concat", "-safe", "0", "-i", join(dir, "frames.ffconcat"),+ "-vf", `fps=${fps},split[a][b];[a]palettegen=stats_mode=diff[p];[b][p]paletteuse=dither=bayer:bayer_scale=5:diff_mode=rectangle`,+ "-loop", "0", gif,+ ];+ const encoded = spawnSync("ffmpeg", ffmpeg, { stdio: "inherit" });+ const seconds = (shots.at(-1).t - shots[0].t) / 1000;+ const rate = Math.round((shots.length - 1) / seconds);+ if (encoded.status !== 0) {+ log(`${name}: ffmpeg failed; ${shots.length} frames kept in ${dir}`);+ return null;+ }+ rmSync(dir, { recursive: true, force: true });+ log(`${name}: ${shots.length} frames at ~${rate}fps, ${rect.width * SCALE}×${rect.height * SCALE}px → ${gif}`);+ return gif;+}++mkdirSync(options.out, { recursive: true });+const commit = execFileSync("git", ["rev-parse", "--short", "HEAD"], { cwd: repoRoot }).toString().trim();+const dirty = execFileSync("git", ["status", "--porcelain", "--untracked-files=no"], { cwd: repoRoot }).toString().trim() !== "";+log(`commit ${commit}${dirty ? " + uncommitted changes" : ""}, ${base}, out ${options.out}`);++const scenario = await import(pathToFileURL(options.scenario).href);+try {+ await scenario.default({ open, sample, record, delay, check, checks, api, slug, out: options.out, args: options.args, log });+} finally {+ for (const context of contexts) await context.close().catch(() => {});+ await browser.close();+ writeFileSync(+ join(options.out, "report.json"),+ `${JSON.stringify({ commit, dirty, scenario: options.scenario.replace(`${repoRoot}/`, ""), args: options.args, checks: results, samples }, null, 1)}\n`,+ );+}++const failed = results.filter((r) => !r.ok).length;+log(`${results.length - failed}/${results.length} checks passed; report → ${join(options.out, "report.json")}`);+process.exit(failed > 0 ? 1 : 0);diff --git a/scripts/motion/checks.mjs b/scripts/motion/checks.mjsnew file mode 100644index 0000000000..f7ead4b8e1--- /dev/null+++ b/scripts/motion/checks.mjs@@ -0,0 +1,103 @@+// Checks over the frames `scripts/motion/capture.mjs` samples: one entry per+// animation frame, `{ t, rects: { name: { x, y, w, h } | null } }`, in CSS+// pixels relative to the viewport. Each check returns `{ ok, detail }`.++const DEFAULT_TOLERANCE = 0.5;+// A still element reads back the same float every frame, and an ease-out tail+// at 120Hz moves well under the tolerance per frame, so any difference counts.+const CHANGED = 0.01;++function value(rect, prop) {+ if (!rect) return null;+ if (prop === "right") return rect.x + rect.w;+ if (prop === "bottom") return rect.y + rect.h;+ return rect[prop];+}++/** One property of one sampled element, frame by frame; frames where it is absent are dropped. */+export function track(frames, name, prop) {+ return frames.map((frame) => value(frame.rects[name], prop)).filter((v) => v !== null && v !== undefined);+}++const round = (v) => Math.round(v * 10) / 10;++/** How many frames the value changed in, and the longest run of consecutive changing frames. */+function movement(values) {+ let frames = 0;+ let run = 0;+ let longestRun = 0;+ for (let i = 1; i < values.length; i++) {+ if (Math.abs(values[i] - values[i - 1]) > CHANGED) {+ frames++;+ run++;+ longestRun = Math.max(longestRun, run);+ } else {+ run = 0;+ }+ }+ return { frames, longestRun };+}++/** "318 → 60 over 12 frames": what a track did, for a report line. */+export function describe(values) {+ if (values.length === 0) return "not found";+ const { frames } = movement(values);+ const first = round(values[0]);+ const last = round(values.at(-1));+ if (frames === 0) return `${first}, still`;+ return `${first} → ${last} over ${frames} frame${frames === 1 ? "" : "s"}`;+}++/**+ * The value moves in one direction only: a height that eases from the old+ * size to the new, an indicator that does not overshoot its target, a block+ * below that does not jump away and come back. A track that ends where it+ * started must not move at all.+ */+export function monotonic(values, { tolerance = DEFAULT_TOLERANCE } = {}) {+ if (values.length === 0) return { ok: false, detail: "not found" };+ const first = values[0];+ const last = values.at(-1);+ const direction = Math.abs(last - first) <= tolerance ? 0 : Math.sign(last - first);+ let worst = 0;+ let extreme = first;+ for (const v of values) {+ if (direction === 0) {+ worst = Math.max(worst, Math.abs(v - first));+ } else {+ extreme = direction > 0 ? Math.max(extreme, v) : Math.min(extreme, v);+ worst = Math.max(worst, Math.abs(v - extreme));+ }+ }+ const ok = worst <= tolerance;+ const what = direction === 0 ? `moved ${round(worst)}px and came back` : `reversed by ${round(worst)}px`;+ return { ok, detail: ok ? describe(values) : `${what} (${describe(values)})` };+}++/** The change is spread over several frames rather than applied in one. */+export function animated(values, { minFrames = 3 } = {}) {+ if (values.length === 0) return { ok: false, detail: "not found" };+ const { frames } = movement(values);+ return { ok: frames >= minFrames, detail: `${describe(values)}; expected at least ${minFrames}` };+}++/**+ * Every change lands in a single frame, as reduced motion requires. A track+ * may change more than once (an empty list while the next tab loads, then its+ * rows), but never in two frames in a row.+ */+export function instant(values) {+ if (values.length === 0) return { ok: false, detail: "not found" };+ const { longestRun } = movement(values);+ const ok = longestRun <= 1;+ return { ok, detail: ok ? describe(values) : `moved for ${longestRun} frames in a row (${describe(values)})` };+}++/** In the last frame, element `a` sits exactly on element `b` along `props`. */+export function landsOn(frames, a, b, { props = ["x", "w"], tolerance = DEFAULT_TOLERANCE } = {}) {+ const last = frames.at(-1)?.rects ?? {};+ if (!last[a] || !last[b]) return { ok: false, detail: `${last[a] ? b : a} not found in the last frame` };+ const off = props.map((prop) => [prop, value(last[a], prop) - value(last[b], prop)]);+ const ok = off.every(([, d]) => Math.abs(d) <= tolerance);+ return { ok, detail: off.map(([prop, d]) => `${prop} ${d >= 0 ? "+" : ""}${round(d)}px`).join(", ") };+}diff --git a/scripts/motion/checks.test.mjs b/scripts/motion/checks.test.mjsnew file mode 100644index 0000000000..bdbf40c7b1--- /dev/null+++ b/scripts/motion/checks.test.mjs@@ -0,0 +1,69 @@+import assert from "node:assert/strict";+import test from "node:test";++import { animated, describe, instant, landsOn, monotonic, track } from "./checks.mjs";++const frames = (heights) => heights.map((h, i) => ({ t: i * 16.7, rects: { list: { x: 0, y: 100, w: 240, h } } }));++test("track reads derived edges and skips frames without the element", () => {+ const sampled = [+ { t: 0, rects: { pill: { x: 10, y: 0, w: 40, h: 20 } } },+ { t: 16, rects: { pill: null } },+ { t: 33, rects: { pill: { x: 30, y: 0, w: 60, h: 20 } } },+ ];+ assert.deepEqual(track(sampled, "pill", "right"), [50, 90]);+ assert.deepEqual(track(sampled, "pill", "x"), [10, 30]);+});++test("a height easing from one size to the other is monotonic and animated", () => {+ const values = track(frames([318, 318, 210, 140, 98, 74, 63, 60, 60]), "list", "h");+ assert.equal(monotonic(values).ok, true);+ assert.equal(animated(values).ok, true);+ assert.equal(instant(values).ok, false);+ assert.equal(describe(values), "318 → 60 over 6 frames");+});++test("a block that jumps up while the next tab loads and is pushed back down is not monotonic", () => {+ const result = monotonic([500, 500, 468, 468, 468, 500, 500]);+ assert.equal(result.ok, false);+ assert.match(result.detail, /moved 32px and came back/);+});++test("an indicator that overshoots its target reverses", () => {+ const result = monotonic([0, 40, 90, 117, 104, 100, 100]);+ assert.equal(result.ok, false);+ assert.match(result.detail, /reversed by 17px/);+});++test("sub-pixel jitter stays within the overshoot tolerance", () => {+ assert.equal(monotonic([10, 20, 30, 29.7, 30]).ok, true);+});++test("an ease-out tail moving under half a pixel per frame still counts as motion", () => {+ const tail = [70, 92, 100, 103.5, 104.9, 105.4, 105.7, 105.8];+ assert.equal(animated(tail).ok, true);+ assert.equal(instant(tail).ok, false);+});++test("reduced motion: each change lands in one frame, even when it changes twice", () => {+ assert.equal(instant([318, 318, 0, 0, 0, 60, 60]).ok, true);+ assert.equal(instant([318, 200, 120, 60]).ok, false);+ assert.equal(animated([318, 318, 60, 60]).ok, false);+});++test("landsOn compares the last frame along the requested edges", () => {+ const sampled = [+ { t: 0, rects: { pill: { x: 0, y: 0, w: 40, h: 20 }, tab: { x: 60, y: 0, w: 72, h: 20 } } },+ { t: 16, rects: { pill: { x: 60.2, y: 0, w: 72, h: 20 }, tab: { x: 60, y: 0, w: 72, h: 20 } } },+ ];+ assert.equal(landsOn(sampled, "pill", "tab").ok, true);+ const off = landsOn([{ t: 0, rects: { pill: { x: 60, y: 0, w: 139, h: 20 }, tab: { x: 60, y: 0, w: 72, h: 20 } } }], "pill", "tab");+ assert.equal(off.ok, false);+ assert.equal(off.detail, "x +0px, w +67px");+});++test("a missing element fails instead of passing vacuously", () => {+ assert.equal(monotonic([]).ok, false);+ assert.equal(instant([]).ok, false);+ assert.equal(landsOn([{ t: 0, rects: { pill: null, tab: { x: 0, y: 0, w: 1, h: 1 } } }], "pill", "tab").ok, false);+});diff --git a/scripts/motion/inbox-tabs.mjs b/scripts/motion/inbox-tabs.mjsnew file mode 100644index 0000000000..68c2a52b0f--- /dev/null+++ b/scripts/motion/inbox-tabs.mjs@@ -0,0 +1,101 @@+// Example scenario for scripts/motion/capture.mjs: switching the Work panel's+// Inbox tabs (Inbox / Snoozed / Archived). It needs the `sidebar` fixture:+//+// make env-exec ARGS="-- node scripts/dev-fixtures.mjs sidebar"+// make env-exec ARGS="-- node scripts/motion/capture.mjs scripts/motion/inbox-tabs.mjs --out ../motion"+//+// It snoozes two of the fixture's notifications and archives three, so every+// tab has rows. Archived loads on its first open; that request is held for+// 600ms to show what the section does while a tab loads.+//+// Scenario options: --locale zh-CN (default en-US).++const SECTION = 'section[data-mc="panel-section"]:has([data-inbox-tab])';+const TARGETS = {+ // The sliding highlight when there is one, else the open tab's own background.+ indicator: `${SECTION} [role="tablist"] > span[aria-hidden], ${SECTION} [role="tab"][aria-selected="true"]`,+ tab: `${SECTION} [role="tab"][aria-selected="true"]`,+ section: SECTION,+ below: `${SECTION} + section`,+};+const ARCHIVED_PAGE = /\/api\/inbox\/archived\/page/;+const SLOW_MS = 600;+const SWITCHES = [+ { to: "snoozed" },+ { to: "archived", slowMs: SLOW_MS },+ { to: "inbox" },+ { to: "archived" },+ { to: "inbox" },+];++const list = (response) => (Array.isArray(response) ? response : (response?.items ?? []));++async function seed(api, log) {+ const snoozed = list(await api("GET", "/api/inbox/snoozed"));+ const archived = list(await api("GET", "/api/inbox/archived/page?limit=5"));+ const inbox = list(await api("GET", "/api/inbox")).filter((item) => !item.archived);+ const byIssue = [...new Map(inbox.map((item) => [item.issue_id, item])).values()];+ if (byIssue.length < 6) throw new Error("the Inbox needs the sidebar fixture: make env-exec ARGS=\"-- node scripts/dev-fixtures.mjs sidebar\"");+ const until = new Date(Date.now() + 3 * 24 * 3600 * 1000).toISOString();+ for (const item of byIssue.slice(0, Math.max(0, 2 - snoozed.length))) await api("POST", `/api/inbox/${item.id}/snooze`, { until });+ for (const item of byIssue.slice(2, 2 + Math.max(0, 3 - archived.length))) await api("POST", `/api/inbox/${item.id}/archive`);+ log(`seeded: ${Math.max(snoozed.length, 2)} snoozed, ${Math.max(archived.length, 3)} archived`);+}++async function openWorkPanel(open, options) {+ const page = await open("/issues", options);+ await page.waitForSelector(`${TARGETS.tab}`, { timeout: 60000 });+ await page.waitForSelector(`${SECTION} [data-inbox-row]`, { timeout: 30000 });+ await page.waitForTimeout(1500); // fonts, queries, entry transitions+ return page;+}++const clickTab = (page, to) => page.click(`${SECTION} [data-inbox-tab="${to}"]`);++export default async function inboxTabs({ open, sample, record, delay, check, checks, api, args, log }) {+ const at = args.indexOf("--locale");+ const locale = at >= 0 ? args[at + 1] : "en-US";+ const { track, landsOn, monotonic, animated, instant } = checks;+ await seed(api, log);++ for (const reducedMotion of [false, true]) {+ const pass = reducedMotion ? "reduced motion" : "motion";+ const page = await openWorkPanel(open, { reducedMotion, locale });+ let from = "inbox";+ for (const { to, slowMs } of SWITCHES) {+ if (slowMs) await delay(page, ARCHIVED_PAGE, slowMs);+ const label = `${pass}, ${from} → ${to}${slowMs ? ` (first load +${slowMs}ms)` : ""}`;+ const frames = await sample(page, label, TARGETS, () => clickTab(page, to), { quietMs: (slowMs ?? 0) + 400 });+ const x = track(frames, "indicator", "x");+ const right = track(frames, "indicator", "right");+ const height = track(frames, "section", "h");+ const below = track(frames, "below", "y");+ check(`${label}: highlight lands on the open tab`, landsOn(frames, "indicator", "tab"));+ if (reducedMotion) {+ check(`${label}: highlight moves instantly`, instant(x));+ check(`${label}: section height changes instantly`, instant(height));+ check(`${label}: section below moves instantly`, instant(below));+ } else {+ check(`${label}: highlight slides`, animated(x));+ check(`${label}: highlight left edge never overshoots`, monotonic(x));+ check(`${label}: highlight right edge never overshoots`, monotonic(right));+ check(`${label}: section height changes one way`, monotonic(height));+ if (Math.abs(height.at(-1) - height[0]) > 1) check(`${label}: section height eases`, animated(height));+ check(`${label}: section below never jumps back`, monotonic(below));+ }+ from = to;+ }+ }++ // The same switches, recorded: a fresh context, so Archived loads cold again.+ const page = await openWorkPanel(open, { locale });+ const box = await page.locator(SECTION).boundingBox();+ const clip = { x: box.x - 8, y: box.y - 8, width: box.width + 16, height: box.height + 120 };+ await record(page, "inbox-tabs", clip, async () => {+ for (const { to, slowMs } of SWITCHES) {+ if (slowMs) await delay(page, ARCHIVED_PAGE, slowMs);+ await clickTab(page, to);+ await page.waitForTimeout((slowMs ?? 0) + 900);+ }+ });+}