The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Motion: calm, quick transitions across pages, menus, cards and results
Adarsh3d3d9f16ca72
diff --git a/package.json b/package.jsonindex 39b56adf..9f7cb420 100644--- a/package.json+++ b/package.json@@ -21,6 +21,7 @@"test:e2e:shell": "node tests/e2e/shell.mjs","test:e2e:mega-menus": "node tests/e2e/mega-menus.mjs","test:e2e:tabs": "node tests/e2e/instant-tabs.mjs",+ "test:e2e:motion": "node tests/e2e/motion.mjs","test:e2e:tab-rows": "node tests/e2e/tab-rows.mjs","gen:catalog": "python3 scripts/gen-cloud-models.py && python3 scripts/gen-studio-packs.py && python3 scripts/gen-oss-loras.py && python3 scripts/gen-lora-library.py && python3 scripts/gen-influencer-options.py && python3 scripts/gen-soul-originals.py && python3 scripts/gen-trainers.py && node scripts/gen-icon-map.mjs","typecheck": "tsc --noEmit",diff --git a/src/app/(studio)/motions-and-effects/page.tsx b/src/app/(studio)/motions-and-effects/page.tsxindex 71db412f..a6fdcbab 100644--- a/src/app/(studio)/motions-and-effects/page.tsx+++ b/src/app/(studio)/motions-and-effects/page.tsx@@ -32,7 +32,7 @@ function GalleryRow({pillsLabel: string;}) {return (- <section id={id} aria-labelledby={`${id}-title`} className={AREA_SECTION}>+ <section id={id} aria-labelledby={`${id}-title`} data-reveal className={AREA_SECTION}><SectionHead id={`${id}-title`} title={title} count={data.count} all={href} line={line} />{/* Four a row, as the other area pages' cards, so every line under a picture shows whole. */}<PresetRail items={data.row} className="sm:grid-cols-4" />diff --git a/src/app/globals.css b/src/app/globals.cssindex cf66f8fa..fa76ad27 100644--- a/src/app/globals.css+++ b/src/app/globals.css@@ -2,6 +2,7 @@@import "tw-animate-css";@import "shadcn/tailwind.css";@import "./nav-states.css";+@import "./motion.css";@import "./tab-row.css";@custom-variant dark (&:is(.dark *));@@ -222,8 +223,8 @@--animate-shimmer-text: shimmer-text 2.5s ease-in-out infinite;--animate-skeleton: skeleton-sweep 1.4s ease-in-out infinite;- --animate-fade-up: fade-up 200ms cubic-bezier(0.08, 0.82, 0.17, 1) both;- --animate-pop-in: pop-in 120ms ease-out both;+ --animate-fade-up: fade-up var(--motion-base) cubic-bezier(0.08, 0.82, 0.17, 1) both;+ --animate-pop-in: pop-in var(--motion-fast) cubic-bezier(0.08, 0.82, 0.17, 1) both;--animate-caret: caret-blink 1s step-end infinite;/* Click feedback while a link's route loads: shows only if the navigation takes a moment. */--animate-pending-in: pending-in 150ms ease-out 120ms both;@@ -246,7 +247,7 @@to { opacity: 1; transform: translateY(0); }}@keyframes pop-in {- from { opacity: 0; transform: scale(0.95); }+ from { opacity: 0; transform: scale(0.97); }to { opacity: 1; transform: scale(1); }}@keyframes pending-in {diff --git a/src/app/motion.css b/src/app/motion.cssnew file mode 100644index 00000000..9a37f10a--- /dev/null+++ b/src/app/motion.css@@ -0,0 +1,306 @@+/* ---------------------------------------------------------------------------------------------+ * Motion: one set of durations, easings and distances for every surface (src/lib/ui-motion.ts+ * holds the same numbers for scripts). Motion is quick, small and calm: things settle, they don't+ * fly or bounce. Only transform (translate / scale) and opacity move; nothing waits for an+ * animation. Under prefers-reduced-motion every token is 0 and every change is instant.+ * ------------------------------------------------------------------------------------------- */++:root {+ --motion-instant: 0ms;+ --motion-fast: 120ms; /* presses, exits of small overlays, label cross-fades */+ --motion-base: 200ms; /* menus, dialogs, popovers, card lift, image fade-in, toasts */+ --motion-slow: 320ms; /* phone sheets, section reveals, cover zoom, a new result */+ --motion-page: 380ms; /* a page arriving: the longest motion on the site */+ --motion-count: 600ms; /* number count-ups (text only) */++ --motion-d1: 4px; /* rise and slide distances */+ --motion-d2: 8px;+ --motion-d3: 16px;+ --motion-lift: -2px; /* a card under the pointer */+ --motion-scale-in: 0.97;+ --motion-scale-out: 0.98;+ --motion-press: 0.97;+ --motion-press-card: 0.985;+ --motion-zoom: 1.03; /* a cover under the pointer */+ --motion-stagger: 40ms; /* per item, 6 steps at most */+}++@theme {+ /* A thing moving between two on-screen states (lift, zoom, morph). */+ --ease-standard: cubic-bezier(0.2, 0, 0, 1);+ /* A large surface from an edge (phone sheets, a page arriving): a strong ease-out, no overshoot. */+ --ease-emphasised: cubic-bezier(0.32, 0.72, 0, 1);+}++@media (prefers-reduced-motion: reduce) {+ :root {+ --motion-fast: 0ms;+ --motion-base: 0ms;+ --motion-slow: 0ms;+ --motion-page: 0ms;+ --motion-count: 0ms;+ --motion-stagger: 0ms;+ --motion-d1: 0px;+ --motion-d2: 0px;+ --motion-d3: 0px;+ --motion-lift: 0px;+ --motion-scale-in: 1;+ --motion-scale-out: 1;+ --motion-press: 1;+ --motion-press-card: 1;+ --motion-zoom: 1;+ }+ /* The safety net for motion that doesn't use the tokens (tw-animate, older keyframes): it ends at once. Spinners+ stop too; each one has words beside it. Media playback (clips, previews) keeps its own rules. */+ *, ::before, ::after {+ animation-duration: 0s !important;+ animation-delay: 0s !important;+ animation-iteration-count: 1 !important;+ transition-duration: 0s !important;+ transition-delay: 0s !important;+ scroll-behavior: auto !important;+ }+}++/* ----- Menus, popovers, selects, hover cards (Radix + tw-animate): open from the trigger, close quicker. ----- */+:is(+ [data-slot="dropdown-menu-content"], [data-slot="dropdown-menu-sub-content"], [data-slot="popover-content"],+ [data-slot="context-menu-content"], [data-slot="context-menu-sub-content"], [data-slot="select-content"],+ [data-slot="hover-card-content"]+) {+ &[data-state="open"] {+ --tw-duration: var(--motion-base);+ --tw-ease: var(--ease-enter);+ --tw-enter-scale: var(--motion-scale-in);+ }+ &[data-state="open"][data-side="bottom"] { --tw-enter-translate-y: calc(var(--motion-d1) * -1); }+ &[data-state="open"][data-side="top"] { --tw-enter-translate-y: var(--motion-d1); }+ &[data-state="open"][data-side="left"] { --tw-enter-translate-x: var(--motion-d1); }+ &[data-state="open"][data-side="right"] { --tw-enter-translate-x: calc(var(--motion-d1) * -1); }+ &[data-state="closed"] {+ --tw-duration: var(--motion-fast);+ --tw-ease: var(--ease-exit);+ --tw-exit-scale: var(--motion-scale-out);+ }+}+/* Tooltips are read in passing: quick both ways. */+[data-slot="tooltip-content"] {+ --tw-duration: var(--motion-fast);+ --tw-ease: var(--ease-enter);+ --tw-enter-scale: var(--motion-scale-in);+ --tw-exit-scale: var(--motion-scale-out);+ &[data-state="closed"] { --tw-ease: var(--ease-exit); }+}++/* ----- Dialogs and their backdrops: the box grows a touch from the centre; out is quicker. ----- */+:is([data-slot="dialog-overlay"], [data-slot="alert-dialog-overlay"], [data-slot="sheet-overlay"], [data-slot="search-palette-overlay"]) {+ &[data-state="open"] { --tw-duration: var(--motion-base); --tw-ease: var(--ease-standard); }+ &[data-state="closed"] { --tw-duration: var(--motion-fast); --tw-ease: var(--ease-exit); }+}+:is([data-slot="dialog-content"], [data-slot="alert-dialog-content"]) {+ &[data-state="open"] {+ --tw-duration: var(--motion-base);+ --tw-ease: var(--ease-enter);+ --tw-enter-scale: var(--motion-scale-in);+ }+ &[data-state="closed"] {+ --tw-duration: var(--motion-fast);+ --tw-ease: var(--ease-exit);+ --tw-exit-scale: var(--motion-scale-out);+ }+}++/* ----- Sheets: a solid surface slides from its edge (no fade); the backdrop fades with it. ----- */+:is([data-slot="sheet-content"][data-side], #phone-sheet) {+ &[data-state="open"] {+ --tw-duration: var(--motion-slow);+ --tw-ease: var(--ease-emphasised);+ --tw-enter-opacity: 1;+ }+ &[data-state="closed"] {+ --tw-duration: var(--motion-base);+ --tw-ease: var(--ease-exit);+ --tw-exit-opacity: 1;+ }+}+:is([data-slot="sheet-content"][data-side="bottom"], #phone-sheet) {+ --tw-enter-translate-y: 100%;+ --tw-exit-translate-y: 100%;+}+[data-slot="sheet-content"][data-side="top"] { --tw-enter-translate-y: -100%; --tw-exit-translate-y: -100%; }+[data-slot="sheet-content"][data-side="left"] { --tw-enter-translate-x: -100%; --tw-exit-translate-x: -100%; }+[data-slot="sheet-content"][data-side="right"] { --tw-enter-translate-x: 100%; --tw-exit-translate-x: 100%; }+/* The phone sheet's backdrop moves with the sheet, not ahead of it. */+[data-slot="sheet-overlay"][data-state="open"]:has(+ #phone-sheet) { --tw-duration: var(--motion-slow); }+[data-slot="sheet-overlay"][data-state="closed"]:has(+ #phone-sheet) { --tw-duration: var(--motion-base); }++/* ----- Search palette: a phone's full screen rises a little; a desktop's panel grows a touch from under the bar. ----- */+[data-slot="search-palette"] {+ &[data-state="open"] {+ --tw-duration: var(--motion-base);+ --tw-ease: var(--ease-enter);+ --tw-enter-translate-y: var(--motion-d2);+ }+ &[data-state="closed"] { --tw-duration: var(--motion-fast); --tw-ease: var(--ease-exit); }+ @media (min-width: 768px) {+ &[data-state="open"] { --tw-enter-translate-y: calc(var(--motion-d1) * -1); --tw-enter-scale: var(--motion-scale-out); }+ &[data-state="closed"] { --tw-exit-scale: var(--motion-scale-out); }+ }+}++/* ----- The bar's grouped menus (Studios, Apps, Motions & effects, Canvas): utility menus, so they are quick. The+ panel drops in from the bar and its columns follow 20 ms apart (3 steps at most: every column reads by 260 ms). It+ goes at once when it closes, so a menu that replaces it (data-switched, which just appears) never overlaps it. ----- */+:is(#studios-launcher, [data-mega-panel]) {+ --tw-duration: var(--motion-base);+ --tw-ease: var(--ease-enter);+ --tw-enter-translate-y: calc(var(--motion-d2) * -1);+ --launcher-step: calc(var(--motion-stagger) * 0.5);+ &[hidden] { display: none; }+ &:not([hidden]) [data-col] { animation: motion-rise-near var(--motion-base) var(--ease-enter) backwards; }+ &:not([hidden]) [data-col="1"] { animation-delay: var(--launcher-step); }+ &:not([hidden]) [data-col="2"] { animation-delay: calc(var(--launcher-step) * 2); }+ &:not([hidden]) :is([data-col="3"], [data-col="4"], [data-col="5"], [data-col="6"], [data-col="7"], [data-col="8"]) { animation-delay: calc(var(--launcher-step) * 3); }+ &[data-switched] [data-col] { animation: none; }+}++/* ----- Toasts (sonner, top centre): in from just above, out quicker; the stack moves on the standard curve. ----- */+[data-sonner-toaster] [data-sonner-toast] {+ transition:+ transform var(--motion-base) var(--ease-standard),+ opacity var(--motion-base) var(--ease-enter),+ height var(--motion-base) var(--ease-standard);+}+[data-sonner-toaster] [data-sonner-toast][data-y-position="top"][data-mounted="false"] { --y: translateY(calc(var(--motion-d2) * -1)); }+[data-sonner-toaster] [data-sonner-toast][data-y-position="bottom"][data-mounted="false"] { --y: translateY(var(--motion-d2)); }+[data-sonner-toaster] [data-sonner-toast][data-removed="true"] {+ transition:+ transform var(--motion-fast) var(--ease-exit),+ opacity var(--motion-fast) var(--ease-exit),+ height var(--motion-base) var(--ease-standard);+}+[data-sonner-toaster] [data-sonner-toast][data-y-position="top"][data-removed="true"][data-front="true"][data-swipe-out="false"] { --y: translateY(calc(var(--motion-d1) * -1)); }++/* ----- A confirmation in place ("Copied", "Saved"): the mark grows in, the words cross-fade. ----- */+.motion-confirm { animation: motion-confirm var(--motion-base) var(--ease-enter) both; }+.motion-swap { animation: motion-fade var(--motion-fast) var(--ease-enter) both; }+/* A spinner on a button: only when the wait is long enough to notice (150 ms); what it replaces hands over then. */+.motion-spinner { animation: motion-fade var(--motion-fast) var(--ease-enter) 150ms backwards, spin 1s linear infinite; }+.motion-hand-off { animation: motion-fade-out var(--motion-fast) var(--ease-exit) 150ms forwards; }++/* ----- Cards (galleries, Home rows, studios, projects): lift with a soft shadow under the pointer, the cover leans in,+ and a press gives a little. Touch screens get the press only. The shadow is a pseudo-element that fades, so nothing+ but opacity and transform ever animates. ----- */+.card-motion {+ position: relative;+ isolation: isolate;+ transition:+ translate var(--motion-base) var(--ease-standard),+ scale var(--motion-base) var(--ease-standard),+ background-color 100ms var(--ease-move);+ &::after {+ content: "";+ position: absolute;+ inset: 0;+ z-index: -1;+ border-radius: inherit;+ box-shadow: var(--elevation-normal);+ opacity: 0;+ pointer-events: none;+ transition: opacity var(--motion-base) var(--ease-standard);+ }+ &:active { scale: var(--motion-press-card); transition-duration: var(--motion-fast); }+ &:focus-visible { translate: 0 var(--motion-lift); }+ &:focus-visible::after { opacity: 1; }+}+/* The cover: the frame's first child (a preset preview, a picture), or anything marked .card-zoom. The frame clips it. */+:is(.card-cover > :first-child, .card-zoom) { transition: scale var(--motion-slow) var(--ease-standard); }+@media (hover: hover) and (pointer: fine) {+ .card-motion:hover { translate: 0 var(--motion-lift); }+ .card-motion:hover::after { opacity: 1; }+ .card-motion.card-fill:hover { background-color: var(--card); }+ :is(.card-motion, .group\/card):hover :is(.card-cover > :first-child, .card-zoom) { scale: var(--motion-zoom); }+}++/* ----- Pictures fade in once they've loaded (the frame under them is already the muted fill). page-motion.tsx marks only+ pictures that arrive after the first paint, never the first screen's. ----- */+img[data-fade] { transition: opacity var(--motion-base) var(--ease-enter); }+img[data-fade="wait"] { opacity: 0; }+.pv { background-color: var(--muted); }++/* ----- A page arriving (page-motion.tsx): the new page fades in and settles 8 px. The top bar, the phone tabs and+ every bar the page pins (sticky or fixed headers, tab bands, a docked composer, anything marked data-page-still)+ stay still: page-motion.tsx marks only the blocks around them with data-page-item, and never an ancestor of a+ pinned bar, so a translate never re-anchors a fixed bar or carries a sticky one. Nothing waits: the page is there,+ interactive, from its first frame. Back and Forward stay instant. ----- */+#content[data-page-in] [data-page-item] {+ animation:+ motion-fade calc(var(--motion-page) * 0.63) var(--ease-enter) backwards,+ motion-rise-page var(--motion-slow) var(--ease-emphasised) backwards;+}+/* Content that replaces its skeleton: a quick fade with a 4 px rise. */+[data-motion-reveal] { animation: motion-rise var(--motion-base) var(--ease-enter) backwards; }++/* ----- Sections reveal once as they come on screen (only those below the first screen at load, only with JS). ----- */+[data-reveal="wait"] { opacity: 0; translate: 0 var(--motion-d2); }+/* Jumped to (a #link, a section tab, find in page): shown at once, no transition, so the scroll lands on it ready. */+[data-reveal="now"], [data-reveal="now"] [data-reveal-item] { transition: none; }+[data-reveal="in"] {+ transition:+ opacity var(--motion-slow) var(--ease-enter),+ translate var(--motion-slow) var(--ease-enter);+}+[data-reveal="wait"] [data-reveal-item] { opacity: 0; translate: 0 var(--motion-d1); }+[data-reveal="in"] [data-reveal-item] {+ transition:+ opacity var(--motion-slow) var(--ease-enter),+ translate var(--motion-slow) var(--ease-enter);+ transition-delay: calc(min(var(--i, 0), 6) * var(--motion-stagger));+}+@media print {+ [data-reveal], [data-reveal] [data-reveal-item] { opacity: 1 !important; translate: none !important; }+}++/* ----- A result that finishes while the studio is open: the picture settles in over its tile, one soft light passes+ across it, and its next steps follow. Never on a page load or a scroll back. ----- */+[data-arrive] {+ /* The tile's frame stays; only the picture settles into it (its own load fade and the skeleton hand-over skip it). */+ & > :first-child { animation: motion-settle var(--motion-slow) var(--ease-standard) backwards; animation-delay: calc(min(var(--i, 0), 6) * var(--motion-stagger)); }+ &::after {+ content: "";+ position: absolute;+ inset: 0;+ z-index: 1;+ pointer-events: none;+ background: linear-gradient(105deg, transparent 40%, oklch(1 0 0 / 10%) 50%, transparent 60%);+ translate: -100% 0;+ animation: motion-sweep 500ms var(--ease-standard) both;+ animation-delay: calc(240ms + min(var(--i, 0), 6) * var(--motion-stagger));+ }+}+[data-follow] { animation: motion-rise var(--motion-base) var(--ease-enter) backwards; animation-delay: calc(120ms + min(var(--i, 0), 6) * var(--motion-stagger)); }++/* A new request at the top of a feed (not the ones there when it loaded). */+[data-enter] { animation: motion-rise var(--motion-base) var(--ease-enter) backwards; }++@keyframes motion-fade { from { opacity: 0; } }+@keyframes motion-fade-out { to { opacity: 0; } }+@keyframes spin { to { transform: rotate(360deg); } }+@keyframes motion-rise { from { opacity: 0; translate: 0 var(--motion-d1); } }+@keyframes motion-rise-near { from { opacity: 0; translate: 0 calc(var(--motion-d1) * -1); } }+@keyframes motion-rise-page { from { translate: 0 var(--motion-d2); } }+@keyframes motion-settle { from { opacity: 0; scale: 1.02; } }+@keyframes motion-sweep { to { translate: 100% 0; } }+@keyframes motion-confirm { from { opacity: 0; scale: 0.8; } }++@media (prefers-reduced-motion: reduce) {+ [data-arrive]::after { display: none; }+ [data-reveal], [data-reveal] [data-reveal-item], img[data-fade] { opacity: 1 !important; translate: none !important; }+}++/* A before/after pair (home/before-after.tsx): its two pictures show together, once both have loaded. */+[data-pair="wait"] { opacity: 0; }+[data-pair="in"] { transition: opacity var(--motion-base) var(--ease-enter); }+@media (prefers-reduced-motion: reduce) {+ [data-pair] { opacity: 1 !important; }+}diff --git a/src/app/tab-row.css b/src/app/tab-row.cssindex 0f1b24d8..74248dd3 100644--- a/src/app/tab-row.css+++ b/src/app/tab-row.css@@ -6,14 +6,14 @@* - Selected: a soft fill. Hover: a lighter fill of the same shape (only for a mouse, and never while the page scrolls* under a resting mouse). Pressed: a stronger fill. Keyboard focus: a 2 px ring of the same shape.* - Once the row's script runs, one fill (`.tab-ind`) slides between the items instead of each item painting its own.- * In @layer components, so a row's own utilities (margins, wrapping) still apply.+ * Timings are the site's motion tokens (motion.css). In @layer components, so a row's own utilities (margins,+ * wrapping) still apply.*/:root {/* Hover and pressed are the nav's own fills (nav-states.css); selected is a step stronger than hover. */--tab-hi: var(--nav-hi);--tab-on: color-mix(in oklab, var(--foreground) 10%, transparent);--tab-press: var(--nav-press);- --tab-ease: cubic-bezier(0.25, 0.8, 0.25, 1);/* Where a sticky row of tabs sits: under the phone's bar (and the notch), or under the top bar from md. */--tab-band-top: calc(3.5rem + env(safe-area-inset-top));}@@ -70,8 +70,8 @@user-select: none;-webkit-tap-highlight-color: transparent;transition:- background-color 140ms var(--tab-ease),- color 140ms var(--tab-ease);+ background-color var(--motion-fast) var(--ease-standard),+ color var(--motion-fast) var(--ease-standard);}/* An icon leads: a little less room on its side, so icon and words look centred. */.tab-pill:has(> svg:first-child) {@@ -100,7 +100,7 @@height: 16px;flex-shrink: 0;color: var(--muted-foreground);- transition: color 140ms var(--tab-ease);+ transition: color var(--motion-fast) var(--ease-standard);}/* A count after the words (Library). */.tab-pill .tab-count {@@ -169,7 +169,7 @@pointer-events: none;z-index: -1;opacity: 0;- transition: opacity 160ms var(--tab-ease);+ transition: opacity var(--motion-base) var(--ease-enter);}.tab-row[data-ind] > .tab-ind {opacity: 1;@@ -198,7 +198,7 @@transform: translate(var(--ti-r, 0px), var(--ti-y, 0px));}.tab-row[data-ind-moving] > .tab-ind > span {- transition: transform 320ms var(--tab-ease);+ transition: transform var(--motion-slow) var(--ease-standard);}/* While the fill is there, the selected pill paints none of its own. */.tab-row[data-ind] > .tab-pill:is([data-on], [data-state="active"]),@@ -237,7 +237,7 @@clip-path: inset(0 -100vmax);opacity: 0;pointer-events: none;- transition: opacity 160ms var(--tab-ease);+ transition: opacity var(--motion-base) var(--ease-enter);}.tab-band[data-stuck]::after {opacity: 1;diff --git a/src/components/areas/area-page.tsx b/src/components/areas/area-page.tsxindex ce208722..908aa640 100644--- a/src/components/areas/area-page.tsx+++ b/src/components/areas/area-page.tsx@@ -89,7 +89,7 @@ export function AreaSections({ sections }: { sections: AreaShowcase["sections"]const ids = areaIds(sections);return sections.map((s, i) => (<div key={s.id}>- <div id={s.id} className={AREA_SECTION}>+ <div id={s.id} data-reveal className={AREA_SECTION}><DestinationsSectionid={`${s.id}-title`}title={s.title}@@ -113,7 +113,7 @@ export function MoreInFuobe({ current }: { current: AreaId }) {const others = AREAS.filter((a) => a.id !== current).map((a) => entry(a.entryId));const list = [...others, entry("canvas"), entry("assist")].filter((e): e is NavEntry => !!e);return (- <section aria-labelledby="more-in-fuobe" className="mt-10 sm:mt-14">+ <section aria-labelledby="more-in-fuobe" data-reveal className="mt-10 sm:mt-14"><h2 id="more-in-fuobe" className="mb-2 font-sans text-[13px] font-medium">More in Fuobe</h2>diff --git a/src/components/av/step-list.tsx b/src/components/av/step-list.tsxindex 8809234b..1f784c62 100644--- a/src/components/av/step-list.tsx+++ b/src/components/av/step-list.tsx@@ -64,7 +64,7 @@ export function StepList({ steps, className }: { steps: StepRow[]; className?: s</div>{(status === "running" || (status === "queued" && !waiting)) && (<div className="mt-1 h-1 overflow-hidden rounded-full bg-muted">- <div className={cn("h-full rounded-full bg-primary transition-[width] duration-500", pct == null && "w-1/3 animate-pulse")} style={pct != null ? { width: `${Math.max(4, pct)}%` } : undefined} />+ <div className={cn("h-full rounded-full bg-primary origin-left transition-transform duration-(--motion-slow) ease-standard", pct == null && "w-1/3 animate-pulse")} style={pct != null ? { transform: `scaleX(${(Math.max(4, pct)) / 100})` } : undefined} /></div>)}{(status === "failed" || status === "canceled") && g?.error && <p className="mt-0.5 text-[12px] leading-snug break-words text-destructive">{g.error}</p>}diff --git a/src/components/canvas/nodes.tsx b/src/components/canvas/nodes.tsxindex 7d22dc76..0afcae37 100644--- a/src/components/canvas/nodes.tsx+++ b/src/components/canvas/nodes.tsx@@ -558,7 +558,7 @@ function Results({ id, r, compact }: { id: string; r: NodeResults; compact?: boo<p className="shimmer-text animate-shimmer-text truncate text-[12px] font-medium">{r.message ?? (r.state === "queued" ? "Queued" : "Generating…")}</p>{pct != null && <span className="font-mono text-[11px] text-muted-foreground">{pct}%</span>}</div>- {pct != null && <div className="absolute inset-x-0 top-0 h-0.5 bg-primary transition-[width] duration-500" style={{ width: `${pct}%` }} />}+ {pct != null && <div className="absolute inset-x-0 top-0 h-0.5 bg-primary origin-left transition-transform duration-(--motion-slow) ease-standard" style={{ transform: `scaleX(${(pct) / 100})` }} />}</div>);}diff --git a/src/components/cinema/projects-view.tsx b/src/components/cinema/projects-view.tsxindex 3262ca7c..c08177ca 100644--- a/src/components/cinema/projects-view.tsx+++ b/src/components/cinema/projects-view.tsx@@ -51,9 +51,9 @@ function ProjectCard({ project, onSettings, query = "" }: { project: CinemaProjeconst href = `/cinema/${project.id}${query}`;return (<div className="group/card relative animate-fade-up">- <Link href={href} className="block rounded-xl outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <Link href={href} className="card-motion block rounded-xl outline-none focus-visible:ring-2 focus-visible:ring-ring"><div className="relative aspect-video overflow-hidden rounded-xl bg-muted">- <Cover project={project} className="transition-transform duration-300 ease-move group-hover/card:scale-[1.02]" />+ <Cover project={project} className="card-zoom" />{project.pinned && (<span className="absolute top-2 left-2 grid size-7 place-items-center rounded-full bg-black/45 text-white backdrop-blur"><Pin className="size-3.5" />diff --git a/src/components/cinema/side-panel.tsx b/src/components/cinema/side-panel.tsxindex 7c3aeb85..7e4f067b 100644--- a/src/components/cinema/side-panel.tsx+++ b/src/components/cinema/side-panel.tsx@@ -193,7 +193,7 @@ function Brief({ project }: { project: CinemaProject }) {<div className="flex items-center gap-2"><Input value={title} onChange={(e) => (setTitle(e.target.value), save(e.target.value, body))} placeholder="Brief title" className="h-9 font-heading text-[18px]" aria-label="Brief title" /><span className="flex shrink-0 items-center gap-1 text-[11.5px] text-muted-foreground" aria-live="polite">- {state === "saving" ? <Loader2 className="size-3 animate-spin" /> : state === "saved" ? <Check className="size-3" /> : null}+ {state === "saving" ? <Loader2 className="size-3 animate-spin" /> : state === "saved" ? <Check className="motion-confirm size-3" /> : null}{state === "saving" ? "Saving…" : state === "saved" ? "Saved" : "Editing"}</span></div>diff --git a/src/components/color-grade-view.tsx b/src/components/color-grade-view.tsxindex 2191dee8..0d796cc7 100644--- a/src/components/color-grade-view.tsx+++ b/src/components/color-grade-view.tsx@@ -585,7 +585,7 @@ function Grader() {<div className="space-y-2 border-t p-3">{saving?.progress !== undefined && (<div className="h-1 overflow-hidden rounded-full bg-muted">- <div className="h-full bg-primary transition-[width]" style={{ width: `${saving.progress * 100}%` }} />+ <div className="h-full bg-primary origin-left transition-transform duration-(--motion-slow) ease-standard" style={{ transform: `scaleX(${(saving.progress * 100) / 100})` }} /></div>)}<div className="flex gap-2">diff --git a/src/components/content-factory/home.tsx b/src/components/content-factory/home.tsxindex 35e07a27..dd7a6915 100644--- a/src/components/content-factory/home.tsx+++ b/src/components/content-factory/home.tsx@@ -583,10 +583,10 @@ export function ContentFactoryHome({ voices, starters: given = [], fills: givenFfunction SeriesTile({ s }: { s: SeriesCard }) {const picture = s.poster?.outputs.find((o) => o.kind === "image");return (- <Link href={`/content-factory/${s.id}`} className="group/card block min-w-0 animate-fade-up rounded-xl outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <Link href={`/content-factory/${s.id}`} className="group/card card-motion block min-w-0 animate-fade-up rounded-xl outline-none focus-visible:ring-2 focus-visible:ring-ring"><div className={cn("relative overflow-hidden rounded-xl bg-muted", s.aspect === "9:16" ? "aspect-[4/5]" : "aspect-video")}>{picture ? (- <MediaThumb output={picture} className="transition-transform duration-300 ease-move group-hover/card:scale-[1.02]" />+ <MediaThumb output={picture} className="card-zoom" />) : s.thumbnail ? (// eslint-disable-next-line @next/next/no-img-element<img src={s.thumbnail} alt="" className="size-full object-cover" />diff --git a/src/components/evolution/evolution-tool.tsx b/src/components/evolution/evolution-tool.tsxindex f74c8e69..367f59fe 100644--- a/src/components/evolution/evolution-tool.tsx+++ b/src/components/evolution/evolution-tool.tsx@@ -368,7 +368,7 @@ function RunPanel({ run, onAgain }: { run: Run; onAgain: () => void }) {) : (<div className="space-y-3"><div className="h-1.5 overflow-hidden rounded-full bg-muted" role="progressbar" aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.round(state.progress * 100)} aria-label="Progress">- <div className={cn("h-full transition-[width]", state.status === "failed" ? "bg-destructive" : "bg-primary")} style={{ width: `${Math.max(4, state.progress * 100)}%` }} />+ <div className={cn("h-full origin-left transition-transform duration-(--motion-slow) ease-standard", state.status === "failed" ? "bg-destructive" : "bg-primary")} style={{ transform: `scaleX(${(Math.max(4, state.progress * 100)) / 100})` }} /></div><p className={cn("text-[13px]", state.status === "failed" ? "text-destructive" : "text-muted-foreground")} aria-live="polite">{state.status === "failed" ? `${state.label}: ${state.error}` : state.label}diff --git a/src/components/faceless/cards.tsx b/src/components/faceless/cards.tsxindex b273c600..3810ee3d 100644--- a/src/components/faceless/cards.tsx+++ b/src/components/faceless/cards.tsx@@ -53,10 +53,10 @@ export function ChannelCard({ channel }: { channel: FacelessChannel }) {const cover = channel.cover?.outputs.find((o) => o.kind === "image");const refs = channel.settings.styleRefs ?? [];return (- <Link href={`/faceless/${channel.id}`} className="group/card block animate-fade-up rounded-xl outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <Link href={`/faceless/${channel.id}`} className="group/card card-motion block animate-fade-up rounded-xl outline-none focus-visible:ring-2 focus-visible:ring-ring"><div className="relative aspect-video overflow-hidden rounded-xl bg-muted">{cover ? (- <MediaThumb output={cover} className="transition-transform duration-300 ease-move group-hover/card:scale-[1.02]" />+ <MediaThumb output={cover} className="card-zoom" />) : (<StylePicture styleId={channel.settings.styleId} styleRef={refs[0]} className="opacity-90" />)}@@ -92,10 +92,10 @@ export function EpisodeTile({ ep, href, onLike }: { ep: Card; href: string; onLiconst vertical = ep.aspect === "9:16";return (<div className="group/card relative min-w-0 animate-fade-up">- <Link href={href} className="block rounded-xl outline-none focus-visible:ring-2 focus-visible:ring-ring" aria-label={`Open ${ep.title}`}>+ <Link href={href} className="card-motion block rounded-xl outline-none focus-visible:ring-2 focus-visible:ring-ring" aria-label={`Open ${ep.title}`}><div className={cn("relative overflow-hidden rounded-xl bg-muted", vertical ? "aspect-[4/5]" : "aspect-video")}>{picture ? (- <MediaThumb output={picture} className={cn("transition-transform duration-300 ease-move group-hover/card:scale-[1.02]", ep.status !== "done" && "opacity-70")} />+ <MediaThumb output={picture} className={cn("card-zoom", ep.status !== "done" && "opacity-70")} />) : film ? (<MediaThumb output={film} />) : (@@ -116,7 +116,7 @@ export function EpisodeTile({ ep, href, onLike }: { ep: Card; href: string; onLi)}{ep.status === "rendering" && (<div className="absolute inset-x-0 top-0 h-0.5">- <div className="h-full bg-primary transition-[width] duration-500" style={{ width: `${Math.round(ep.progress * 100)}%` }} />+ <div className="h-full bg-primary origin-left transition-transform duration-(--motion-slow) ease-standard" style={{ transform: `scaleX(${(Math.round(ep.progress * 100)) / 100})` }} /></div>)}{ep.status === "done" && <span className="absolute right-2 bottom-2 rounded-full bg-black/55 px-1.5 py-0.5 font-mono text-[11px] text-white tabular-nums">{formatLength(ep.seconds)}</span>}diff --git a/src/components/faceless/episode-view.tsx b/src/components/faceless/episode-view.tsxindex 13a25c4c..fc010750 100644--- a/src/components/faceless/episode-view.tsx+++ b/src/components/faceless/episode-view.tsx@@ -104,7 +104,7 @@ function Player({ view, onRetry, retrying }: { view: View; onRetry: () => void;<p className="shimmer-text animate-shimmer-text font-heading text-[24px]">Generating your episode</p><p className="mt-1 text-[13px] text-muted-foreground">This can take a while for longer videos. You can close this page — it will keep running.</p><div className="mx-auto mt-4 h-1.5 w-56 overflow-hidden rounded-full bg-background/70" role="progressbar" aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.round(view.progress * 100)} aria-label="Episode progress">- <div className="h-full rounded-full bg-primary transition-[width] duration-700" style={{ width: `${Math.max(3, Math.round(view.progress * 100))}%` }} />+ <div className="h-full rounded-full bg-primary origin-left transition-transform duration-(--motion-slow) ease-standard" style={{ transform: `scaleX(${(Math.max(3, Math.round(view.progress * 100))) / 100})` }} /></div><p className="mt-2 font-mono text-[12px] text-muted-foreground tabular-nums">{stepsDone} of {view.steps.length} steps · {Math.round(view.progress * 100)}%diff --git a/src/components/genjutsu/genjutsu-studio.tsx b/src/components/genjutsu/genjutsu-studio.tsxindex a2326e5e..ae6d3d2f 100644--- a/src/components/genjutsu/genjutsu-studio.tsx+++ b/src/components/genjutsu/genjutsu-studio.tsx@@ -1326,7 +1326,7 @@ function RunPanel({ run, onAgain, finish = [], onFinish }: { run: Run; onAgain:) : (<div className="space-y-3"><div className="h-1.5 overflow-hidden rounded-full bg-muted" role="progressbar" aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.round(state.progress * 100)} aria-label="Progress">- <div className={cn("h-full transition-[width]", state.status === "failed" ? "bg-destructive" : "bg-primary")} style={{ width: `${Math.max(4, state.progress * 100)}%` }} />+ <div className={cn("h-full origin-left transition-transform duration-(--motion-slow) ease-standard", state.status === "failed" ? "bg-destructive" : "bg-primary")} style={{ transform: `scaleX(${(Math.max(4, state.progress * 100)) / 100})` }} /></div><p className={cn("text-[13px]", state.status === "failed" ? "text-destructive" : "text-muted-foreground")} aria-live="polite">{state.status === "failed" ? `${state.label}: ${state.error}` : state.label}diff --git a/src/components/home/before-after.tsx b/src/components/home/before-after.tsxindex eb008fba..22325d97 100644--- a/src/components/home/before-after.tsx+++ b/src/components/home/before-after.tsx@@ -1,11 +1,44 @@"use client";import { ArrowRight } from "lucide-react";-import { useEffect, useId, useRef, useState } from "react";+import { useEffect, useId, useLayoutEffect, useRef, useState } from "react";import { IntentLink } from "@/components/intent-link";import { onAttr, TAB_PILL, TabRow } from "@/components/ui/tab-row";+import { reducedMotion } from "@/lib/ui-motion";import { cn } from "@/lib/utils";+/**+ * Shows a pair's two pictures together: when neither has loaded yet (after hydration, or a tab just picked), the pair+ * waits hidden (motion.css: [data-pair]) and fades in once both are there, instead of an empty frame, then one side,+ * then the other. Server HTML and a page without JS show the pictures as they load; one already showing is never hidden.+ */+function usePairTogether(key: string) {+ const ref = useRef<HTMLDivElement>(null);+ useLayoutEffect(() => {+ const el = ref.current;+ if (!el || reducedMotion()) return;+ const imgs = [...el.querySelectorAll("img")];+ if (imgs.length < 2 || imgs.some((i) => i.complete)) return;+ el.dataset.pair = "wait";+ let left = imgs.length;+ // Each picture ends with a load or an error; once both have, the pair shows.+ const show = () => {+ for (const i of imgs) {+ i.removeEventListener("load", one);+ i.removeEventListener("error", one);+ }+ el.dataset.pair = "in";+ };+ const one = () => --left <= 0 && show();+ for (const i of imgs) {+ i.addEventListener("load", one);+ i.addEventListener("error", one);+ }+ return show;+ }, [key]);+ return ref;+}+/** One side's picture: a 512 px still, and with HD stills its 960 and 1280 px copies (each with its version). */export interface BeforeAfterStill {src: string;@@ -173,6 +206,7 @@ export function BeforeAfter({ pairs }: { pairs: BeforeAfterPair[] }) {}};const value = Math.round(pos);+ const together = usePairTogether(pair.id);return (<div className="w-full max-w-[512px] lg:max-xl:flex lg:max-xl:max-w-none lg:max-xl:items-start lg:max-xl:gap-4 xl:max-w-[460px]">@@ -211,7 +245,7 @@ export function BeforeAfter({ pairs }: { pairs: BeforeAfterPair[] }) {touch.current = null;}}>- <div key={pair.id} className="absolute inset-0 motion-safe:animate-in motion-safe:fade-in motion-safe:duration-150">+ <div key={pair.id} ref={together} data-own-motion className="absolute inset-0 motion-safe:animate-in motion-safe:fade-in motion-safe:duration-150">{/* Both enlarged alike (pair.zoom), so an edge in the source never shows; the after is cut at the handle. */}<BeforeAfterPicture still={pair.before} zoom={pair.zoom} hd={near} onLoad={() => setLoaded((n) => n + 1)} /><div className="absolute inset-0" style={{ clipPath: `inset(0 0 0 ${pos}%)` }}>@@ -220,30 +254,32 @@ export function BeforeAfter({ pairs }: { pairs: BeforeAfterPair[] }) {</div><span className={cn(TAG, "left-2.5")}>{beforeTag}</span><span className={cn(TAG, "right-2.5")}>{afterTag}</span>- <span aria-hidden className="pointer-events-none absolute inset-y-0 -ml-px w-0.5 bg-white shadow-[0_0_6px_rgb(0_0_0/35%)]" style={{ left: `${pos}%` }} />- <span- role="slider"- tabIndex={0}- aria-label={`Compare ${beforeTag.toLowerCase()} and ${afterTag.toLowerCase()}`}- aria-valuemin={0}- aria-valuemax={100}- aria-valuenow={value}- aria-valuetext={`${beforeTag} ${value}%, ${afterTag} ${100 - value}%`}- onKeyDown={(e) => {- const big = e.shiftKey ? 25 : 5;- const next =- e.key === "ArrowLeft" || e.key === "ArrowDown" ? pos - big : e.key === "ArrowRight" || e.key === "ArrowUp" ? pos + big : e.key === "Home" ? 0 : e.key === "End" ? 100 : null;- if (next === null) return;- e.preventDefault();- take();- setPos(clamp(next));- }}- className="absolute top-1/2 -mt-3.5 -ml-3.5 grid size-7 place-items-center rounded-full bg-white text-black shadow-[0_2px_8px_rgb(0_0_0/30%)] outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"- style={{ left: `${pos}%` }}- >- <svg viewBox="0 0 16 16" aria-hidden className="size-3.5" fill="currentColor">- <path d="M6 4 2 8l4 4V4Zm4 0v8l4-4-4-4Z" />- </svg>+ {/* The handle and its line move by transform (a full-width layer shifted by pos %): no layout while it plays. */}+ <span className="pointer-events-none absolute inset-0" style={{ transform: `translateX(${pos}%)` }}>+ <span aria-hidden className="absolute inset-y-0 left-0 -ml-px w-0.5 bg-white shadow-[0_0_6px_rgb(0_0_0/35%)]" />+ <span+ role="slider"+ tabIndex={0}+ aria-label={`Compare ${beforeTag.toLowerCase()} and ${afterTag.toLowerCase()}`}+ aria-valuemin={0}+ aria-valuemax={100}+ aria-valuenow={value}+ aria-valuetext={`${beforeTag} ${value}%, ${afterTag} ${100 - value}%`}+ onKeyDown={(e) => {+ const big = e.shiftKey ? 25 : 5;+ const next =+ e.key === "ArrowLeft" || e.key === "ArrowDown" ? pos - big : e.key === "ArrowRight" || e.key === "ArrowUp" ? pos + big : e.key === "Home" ? 0 : e.key === "End" ? 100 : null;+ if (next === null) return;+ e.preventDefault();+ take();+ setPos(clamp(next));+ }}+ className="pointer-events-auto absolute top-1/2 left-0 -mt-3.5 -ml-3.5 grid size-7 place-items-center rounded-full bg-white text-black shadow-[0_2px_8px_rgb(0_0_0/30%)] outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"+ >+ <svg viewBox="0 0 16 16" aria-hidden className="size-3.5" fill="currentColor">+ <path d="M6 4 2 8l4 4V4Zm4 0v8l4-4-4-4Z" />+ </svg>+ </span></span></div><div className="min-w-0 lg:max-xl:flex-1">diff --git a/src/components/home/home-bento.css b/src/components/home/home-bento.cssindex fa34c316..13d4c1a1 100644--- a/src/components/home/home-bento.css+++ b/src/components/home/home-bento.css@@ -310,8 +310,8 @@outline-offset: 2px;container-type: inline-size;transition:- border-color 0.25s ease,- transform 0.25s ease,+ border-color var(--motion-base) var(--ease-standard),+ transform var(--motion-base) var(--ease-standard),box-shadow 0.15s ease;-webkit-tap-highlight-color: transparent;}diff --git a/src/components/home/home-bento.tsx b/src/components/home/home-bento.tsxindex 0b30b70a..4d34ff8a 100644--- a/src/components/home/home-bento.tsx+++ b/src/components/home/home-bento.tsx@@ -2,6 +2,7 @@ import { ArrowRight, ArrowUpRight, ChevronsLeftRight, Play, Sparkles, Video } frimport { BentoClip, BentoMotion, LiveTyping, NumbersLink } from "@/components/home/bento-islands";import { PausePreviews } from "@/components/home/home-islands";import { IntentLink } from "@/components/intent-link";+import { CountUp } from "@/components/ui/count-up";import type { BentoPicture, BentoTile, HomeBento as Bento } from "@/lib/home-bento";import { cn } from "@/lib/utils";import { s } from "./home-bento-classes";@@ -218,7 +219,9 @@ export function HomeBento({ bento }: { bento: Bento }) {{bento.numbers.map((n) => (<div key={n.label}><dt>{n.label}</dt>- <dd>{n.value}</dd>+ <dd>+ <CountUp value={n.value} id={`bento-${n.label}`} />+ </dd></div>))}</dl>diff --git a/src/components/home/home-islands.tsx b/src/components/home/home-islands.tsxindex 848bb947..3fd2639f 100644--- a/src/components/home/home-islands.tsx+++ b/src/components/home/home-islands.tsx@@ -64,8 +64,10 @@ export function CopyCommand({ text }: { text: string }) {}}className="inline-flex h-6 items-center gap-1.5 rounded-full bg-white/10 px-2.5 text-[12px] text-white/80 transition-colors hover:bg-white/15 hover:text-white">- {done ? <Check className="size-3" /> : <Copy className="size-3" />}- {done ? "Copied" : "Copy"}+ {done ? <Check className="motion-confirm size-3" /> : <Copy className="size-3" />}+ <span key={done ? "done" : "copy"} className="motion-swap">+ {done ? "Copied" : "Copy"}+ </span></button>);}diff --git a/src/components/home/home-sections.tsx b/src/components/home/home-sections.tsxindex 27ae6f51..bbe69cfd 100644--- a/src/components/home/home-sections.tsx+++ b/src/components/home/home-sections.tsx@@ -18,6 +18,7 @@ import {} from "@/components/home/home-islands";import { PILL, PILL_ICON, PILL_TAP } from "@/components/home/pill";import { ShowcaseTile } from "@/components/home/showcase-tile";+import { CountUp } from "@/components/ui/count-up";import { IntentLink } from "@/components/intent-link";import { LiveDemo } from "@/components/live/live-demo";import { NAV } from "@/components/nav-items";@@ -95,7 +96,7 @@ export function SectionHead({aria-hiddenclassName="ml-2 inline-block rounded-full bg-muted px-2 align-[0.3em] font-sans text-[13px] leading-6 tracking-normal text-muted-foreground tabular-nums">- {count}+ <CountUp value={count} id={id} /></span>)}</Heading>@@ -185,7 +186,7 @@ export function ShowcaseWall({export function EffectsSection({ facts, effects }: Pick<HomeShowcase, "facts" | "effects">) {return (- <section aria-labelledby="home-effects" className={cn(SECTION, "[--cv:336px] sm:[--cv:946px] md:[--cv:846px] lg:[--cv:691px] xl:[--cv:490px]")}>+ <section aria-labelledby="home-effects" data-reveal className={cn(SECTION, "[--cv:336px] sm:[--cv:946px] md:[--cv:846px] lg:[--cv:691px] xl:[--cv:490px]")}><SectionHeadid="home-effects"title="Effects"@@ -200,7 +201,7 @@ export function EffectsSection({ facts, effects }: Pick<HomeShowcase, "facts" |export function MotionsSection({ facts, motions }: Pick<HomeShowcase, "facts" | "motions">) {return (- <section aria-labelledby="home-motions" className={cn(SECTION, "[--cv:336px] sm:[--cv:528px] md:[--cv:492px] lg:[--cv:293px] xl:[--cv:290px]")}>+ <section aria-labelledby="home-motions" data-reveal className={cn(SECTION, "[--cv:336px] sm:[--cv:528px] md:[--cv:492px] lg:[--cv:293px] xl:[--cv:290px]")}><SectionHeadid="home-motions"title="Camera motions"@@ -220,7 +221,7 @@ export function MotionsSection({ facts, motions }: Pick<HomeShowcase, "facts" |export function AppsSection({ facts, beforeAfter, reveals, start }: Pick<HomeShowcase, "facts" | "beforeAfter" | "reveals"> & { start?: { title: string; line: string } }) {const id = start ? "apps-start" : "home-apps";return (- <section aria-labelledby={id} className={cn(SECTION, "[--cv:676px] sm:[--cv:1004px] md:[--cv:943px] lg:[--cv:957px] xl:[--cv:525px]")}>+ <section aria-labelledby={id} data-reveal className={cn(SECTION, "[--cv:676px] sm:[--cv:1004px] md:[--cv:943px] lg:[--cv:957px] xl:[--cv:525px]")}>{start ? (<SectionHead id={id} title={start.title} line={start.line} />) : (@@ -247,7 +248,7 @@ export function LiveEditSection() {[Undo2, "Undo a change, or start fresh from the picture"],];return (- <section aria-labelledby="home-live" className={cn(SECTION, "[--cv:720px] sm:[--cv:860px] md:[--cv:820px] lg:[--cv:470px] xl:[--cv:500px]")}>+ <section aria-labelledby="home-live" data-reveal className={cn(SECTION, "[--cv:720px] sm:[--cv:860px] md:[--cv:820px] lg:[--cv:470px] xl:[--cv:500px]")}><div className="grid grid-cols-1 items-center gap-6 lg:grid-cols-12 lg:gap-10"><LiveDemo className="aspect-[4/3] w-full shadow-strong lg:col-span-7" /><div className="min-w-0 lg:col-span-5">@@ -453,7 +454,7 @@ export function StudiosSection({ facts, studios, audioTools, pills }: Pick<HomeSall={area("studios").href}allCount={studioCount()}allNoun="studios"- className={cn(SECTION, "[--cv:529px] sm:[--cv:1597px] md:[--cv:1482px] lg:[--cv:770px] xl:[--cv:795px]")}+ data-reveal className={cn(SECTION, "[--cv:529px] sm:[--cv:1597px] md:[--cv:1482px] lg:[--cv:770px] xl:[--cv:795px]")}/>);}@@ -472,7 +473,7 @@ export function AssistSection({ facts, skills }: Pick<HomeShowcase, "facts" | "s[Plug, "Works with your other tools"],];return (- <section aria-labelledby="home-assist" className={cn(SECTION, "[--cv:912px] sm:[--cv:831px] md:[--cv:911px] lg:[--cv:562px] xl:[--cv:480px]")}>+ <section aria-labelledby="home-assist" data-reveal className={cn(SECTION, "[--cv:912px] sm:[--cv:831px] md:[--cv:911px] lg:[--cv:562px] xl:[--cv:480px]")}><div className="grid gap-8 rounded-2xl border bg-card p-5 sm:p-7 lg:grid-cols-2"><div className="min-w-0"><AssistTag />@@ -509,7 +510,7 @@ export function OpenSourceSection({ facts, newModels }: Pick<HomeShowcase, "fact{ value: facts.presets, label: "presets: apps, camera motions and effects", href: "/effects" },];return (- <section aria-labelledby="home-open" className={cn(SECTION, "[--cv:528px] sm:[--cv:494px] md:[--cv:571px] lg:[--cv:494px] xl:[--cv:363px]")}>+ <section aria-labelledby="home-open" data-reveal className={cn(SECTION, "[--cv:528px] sm:[--cv:494px] md:[--cv:571px] lg:[--cv:494px] xl:[--cv:363px]")}><h2 id="home-open" className={H2}>Open source, all the way down</h2>@@ -574,7 +575,7 @@ const COMMANDS = ["git clone https://github.com/workingprototype/fuobe.git && cdexport function StartSection() {return (- <section aria-labelledby="home-start" className={cn(SECTION, "[--cv:843px] sm:[--cv:726px] md:[--cv:748px] lg:[--cv:430px] xl:[--cv:427px]")}>+ <section aria-labelledby="home-start" data-reveal className={cn(SECTION, "[--cv:843px] sm:[--cv:726px] md:[--cv:748px] lg:[--cv:430px] xl:[--cv:427px]")}><h2 id="home-start" className={H2}>Your GPU. Your models. Your files.</h2>diff --git a/src/components/katana/katana-studio.tsx b/src/components/katana/katana-studio.tsxindex facf49fa..16651956 100644--- a/src/components/katana/katana-studio.tsx+++ b/src/components/katana/katana-studio.tsx@@ -436,7 +436,7 @@ function Runs({ jobs, loading }: { jobs?: KatanaJobView[]; loading: boolean }) {{stage !== "done" && (<div className="mt-3"><div className="h-1.5 overflow-hidden rounded-full bg-muted">- <div className={cn("h-full rounded-full transition-[width] duration-500", stage === "failed" ? "bg-destructive" : "bg-primary")} style={{ width: `${Math.max(3, pct)}%` }} />+ <div className={cn("h-full rounded-full origin-left transition-transform duration-(--motion-slow) ease-standard", stage === "failed" ? "bg-destructive" : "bg-primary")} style={{ transform: `scaleX(${(Math.max(3, pct)) / 100})` }} /></div><p className="mt-1 text-[12px] text-muted-foreground">{stage === "failed" ? "A step failed — open the steps for the reason, then retry: the finished steps are kept" : `${pct}% · steps run as soon as the ones before them finish`}diff --git a/src/components/layers/top-bar.tsx b/src/components/layers/top-bar.tsxindex a48e3128..0fbd770f 100644--- a/src/components/layers/top-bar.tsx+++ b/src/components/layers/top-bar.tsx@@ -119,7 +119,7 @@ function SaveBadge({ state, onRetry }: { state: SaveState; onRetry: () => void }const bad = state === "error" || state === "conflict";const body = (<>- {state === "saved" ? <Check className="size-3.5 shrink-0" /> : bad ? <CloudOff className="size-3.5 shrink-0" /> : <Loader2 className="size-3.5 shrink-0 animate-spin" />}+ {state === "saved" ? <Check className="motion-confirm size-3.5 shrink-0" /> : bad ? <CloudOff className="size-3.5 shrink-0" /> : <Loader2 className="size-3.5 shrink-0 animate-spin" />}<span className="sr-only">{text}</span><span className="hidden xl:inline" aria-hidden>{short}diff --git a/src/components/live/live-editor.tsx b/src/components/live/live-editor.tsxindex 67cff492..177dbcdf 100644--- a/src/components/live/live-editor.tsx+++ b/src/components/live/live-editor.tsx@@ -1166,7 +1166,7 @@ export function LiveEditor(props: LiveEditorProps) {<Tooltip><TooltipTrigger asChild><Button size="lg" variant="secondary" className={cn("h-11 shrink-0 rounded-2xl px-4 max-sm:w-11 max-sm:px-0", keptFlash && "bg-success text-white hover:bg-success")} onClick={() => void keep()} disabled={!canKeep} aria-label="Start fresh from this picture" data-live-keep>- {keeping ? <Loader2 className="size-4 animate-spin" /> : keptFlash ? <Check className="size-4" /> : <Layers className="size-4" />}+ {keeping ? <Loader2 className="size-4 animate-spin" /> : keptFlash ? <Check className="motion-confirm size-4" /> : <Layers className="size-4" />}<span className="max-sm:hidden">Start fresh</span></Button></TooltipTrigger>@@ -1174,7 +1174,7 @@ export function LiveEditor(props: LiveEditorProps) {</Tooltip>) : (<Button size="lg" className={cn("h-11 shrink-0 rounded-2xl px-4", keptFlash && "bg-success hover:bg-success")} onClick={() => void keep()} disabled={!canKeep} data-live-keep>- {keeping ? <Loader2 className="size-4 animate-spin" /> : keptFlash ? <Check className="size-4" /> : <CornerDownLeft className="size-4" />}+ {keeping ? <Loader2 className="size-4 animate-spin" /> : keptFlash ? <Check className="motion-confirm size-4" /> : <CornerDownLeft className="size-4" />}{keptFlash ? "Kept" : "Keep"}</Button>)}@@ -1290,7 +1290,7 @@ function StatusPill({ tone, text, detail, progress }: { tone: string; text: stri{text}{detail && <span className="max-sm:hidden"> · {detail}</span>}</span>- {tone === "busy" && progress !== undefined && <span className="absolute inset-x-0 bottom-0 h-0.5 bg-primary/70 transition-[width]" style={{ width: `${Math.round(progress * 100)}%` }} />}+ {tone === "busy" && progress !== undefined && <span className="absolute inset-x-0 bottom-0 h-0.5 bg-primary/70 origin-left transition-transform duration-(--motion-slow) ease-standard" style={{ transform: `scaleX(${(Math.round(progress * 100)) / 100})` }} />}</span>);}diff --git a/src/components/marketing/runs.tsx b/src/components/marketing/runs.tsxindex 51b3a075..178e5387 100644--- a/src/components/marketing/runs.tsx+++ b/src/components/marketing/runs.tsx@@ -155,7 +155,7 @@ function RunCard({ run, brand, onOpen, onCompose }: { run: MarketingRun; brand?:{elapsed(run.createdAt)}</p></div>- {steps.length > 1 && <div className="absolute inset-x-0 top-0 h-0.5 bg-primary/70 transition-[width] duration-500" style={{ width: `${Math.round((done / steps.length) * 100)}%` }} />}+ {steps.length > 1 && <div className="absolute inset-x-0 top-0 h-0.5 bg-primary/70 origin-left transition-transform duration-(--motion-slow) ease-standard" style={{ transform: `scaleX(${(Math.round((done / steps.length) * 100)) / 100})` }} />}</div>)}<DropdownMenu>diff --git a/src/components/moodboards/create-moodboard.tsx b/src/components/moodboards/create-moodboard.tsxindex 8a8fc7e2..73198026 100644--- a/src/components/moodboards/create-moodboard.tsx+++ b/src/components/moodboards/create-moodboard.tsx@@ -247,7 +247,7 @@ export function CreateMoodboardDialog({ open, onOpenChange, onCreated }: { open:<div className="flex flex-wrap items-center gap-3"><div className="flex min-w-40 flex-1 items-center gap-2"><span className="h-1.5 flex-1 overflow-hidden rounded-full bg-muted">- <span className={cn("block h-full rounded-full transition-[width]", q.tone)} style={{ width: `${q.pct}%` }} />+ <span className={cn("block h-full rounded-full origin-left transition-transform duration-(--motion-slow) ease-standard", q.tone)} style={{ transform: `scaleX(${(q.pct) / 100})` }} /></span><span className="text-[12px] font-medium tabular-nums">{q.label} · {items.length}/{MOODBOARD_LIMITS.max}diff --git a/src/components/nav/bar-split.tsx b/src/components/nav/bar-split.tsxindex 9fb52bec..404c4d2f 100644--- a/src/components/nav/bar-split.tsx+++ b/src/components/nav/bar-split.tsx@@ -277,6 +277,11 @@ export function BarSplitMenu({warmNav(panel);}}onPointerLeave={hover.leave}+ // A press on the chevron is the trigger's own (it closes the menu, or pins one opened by hovering): it never+ // also counts as a press outside, which would close a menu the press meant to pin.+ onInteractOutside={(e) => {+ if (chevron.current?.contains(e.target as Node)) e.preventDefault();+ }}{...keepFocusOnHover(hover.openedByHover)}onCloseAutoFocus={(e) => {if (quietClose.current) {diff --git a/src/components/nav/mega-launcher.tsx b/src/components/nav/mega-launcher.tsxindex 13506fbc..2b96f93e 100644--- a/src/components/nav/mega-launcher.tsx+++ b/src/components/nav/mega-launcher.tsx@@ -345,6 +345,7 @@ export function MegaLauncher({data-mega-panel={id}aria-label={area.panel}hidden={!open}+ inert={!open}onKeyDown={onPanelKey}onPointerMove={onPanelPointer}onClick={(e) => {diff --git a/src/components/nav/phone-tabs.tsx b/src/components/nav/phone-tabs.tsxindex ea6f7512..ce475d8e 100644--- a/src/components/nav/phone-tabs.tsx+++ b/src/components/nav/phone-tabs.tsx@@ -1,7 +1,7 @@"use client";import { usePathname } from "next/navigation";-import { Suspense, useEffect } from "react";+import { Suspense, useEffect, useState } from "react";import { CircleUserRound, House, LayoutGrid, Library, Plus, type LucideIcon } from "lucide-react";import { IntentLink } from "@/components/intent-link";import { useNavUi, useViewerKind } from "@/components/nav/nav-ui";@@ -10,6 +10,7 @@ import { avatarDot, useShownStatus } from "@/components/nav/status-chips";import { NavPrefetcher } from "@/components/nav/nav-prefetch";import { useEngineMode } from "@/lib/api";import { navActive } from "@/lib/nav";+import { ms } from "@/lib/ui-motion";import { activeEntry } from "@/lib/nav-model";import { cn } from "@/lib/utils";@@ -147,13 +148,26 @@ function useKeyboardFlag() {export function PhoneTabs() {const { sheet } = useNavUi();useKeyboardFlag();+ // Stays above a closing sheet until its slide out ends, so the sheet goes back under the bar the way it came.+ const [lastSheet, setLastSheet] = useState(sheet);+ const [closing, setClosing] = useState(false);+ if (sheet !== lastSheet) {+ setLastSheet(sheet);+ setClosing(!sheet);+ }+ useEffect(() => {+ if (!closing) return;+ const t = window.setTimeout(() => setClosing(false), ms("base") + 40);+ return () => window.clearTimeout(t);+ }, [closing]);+ const raised = !!sheet || closing;return (<navaria-label="Main"data-phone-tabsclassName={cn("pointer-events-auto fixed inset-x-0 bottom-0 grid h-[calc(4rem+env(safe-area-inset-bottom))] grid-cols-5 border-t border-sidebar-border bg-sidebar/95 pt-[3px] pr-[max(0.5rem,env(safe-area-inset-right))] pb-[calc(0.25rem+env(safe-area-inset-bottom))] pl-[max(0.5rem,env(safe-area-inset-left))] backdrop-blur md:hidden print:hidden [html[data-fullscreen-studio]_&]:hidden [html[data-keyboard-open]_&]:hidden",- sheet ? "z-[60]" : "z-40",+ raised ? "z-[60]" : "z-40",)}><Suspense fallback={<Tabs pathname="" />}>diff --git a/src/components/nav/search-palette.tsx b/src/components/nav/search-palette.tsxindex 91f928d0..ffec445b 100644--- a/src/components/nav/search-palette.tsx+++ b/src/components/nav/search-palette.tsx@@ -107,8 +107,9 @@ export function SearchPalette({ session, onClose, takeReturn }: { session: Palet<><DialogPrimitive.Root open={session.open} onOpenChange={(o) => !o && onClose()}><DialogPrimitive.Portal>- <DialogPrimitive.Overlay className="fixed inset-0 z-50 bg-overlay backdrop-blur-[2px] motion-safe:duration-150 motion-safe:data-open:animate-in motion-safe:data-open:fade-in-0 motion-safe:data-closed:animate-out motion-safe:data-closed:fade-out-0" />+ <DialogPrimitive.Overlay data-slot="search-palette-overlay" className="fixed inset-0 z-50 bg-overlay backdrop-blur-[2px] motion-safe:duration-150 motion-safe:data-open:animate-in motion-safe:data-open:fade-in-0 motion-safe:data-closed:animate-out motion-safe:data-closed:fade-out-0" /><DialogPrimitive.Content+ data-slot="search-palette"onCloseAutoFocus={restoreFocus}className={cn("fixed inset-0 z-50 flex h-dvh w-full flex-col overflow-hidden bg-popover text-popover-foreground outline-none",diff --git a/src/components/nav/studio-chrome.tsx b/src/components/nav/studio-chrome.tsxindex ed5bbef0..9303606f 100644--- a/src/components/nav/studio-chrome.tsx+++ b/src/components/nav/studio-chrome.tsx@@ -3,6 +3,7 @@import { usePathname } from "next/navigation";import { Suspense, useLayoutEffect } from "react";import { JobNotifications } from "@/components/job-notifications";+import { PageMotion } from "@/components/page-motion";import { SkillBuilderProvider } from "@/components/skills/skill-builder-provider";import { CHROME_STATE_SCRIPT, fullScreenStudio } from "@/lib/nav";import type { NavCovers } from "@/lib/nav-covers";@@ -78,6 +79,8 @@ export function StudioChrome({ covers, children }: { covers: NavCovers; children<Suspense fallback={null}><ExploreTracker /><ChromeState />+ {/* usePathname: inside Suspense, like ChromeState. */}+ <PageMotion /></Suspense><JobNotifications /></SearchPaletteProvider>diff --git a/src/components/page-motion.tsx b/src/components/page-motion.tsxnew file mode 100644index 00000000..1bd3a160--- /dev/null+++ b/src/components/page-motion.tsx@@ -0,0 +1,205 @@+"use client";++import { usePathname } from "next/navigation";+import { useCallback, useEffect, useLayoutEffect, useRef } from "react";+import { fadeInOnLoad, MOTION, newPlace, reducedMotion, revealOnScroll, tabRowOf } from "@/lib/ui-motion";++/** What a loading placeholder looks like in the page (route skeletons say aria-busy; the Skeleton primitive has its slot). */+const SKELETON = '[aria-busy="true"], [data-slot="skeleton"], .animate-skeleton';+/** Content with motion of its own (a studio's result tiles, a request just sent): the skeleton hand-over leaves it alone. */+const OWN_MOTION = "[data-gen-id], [data-arrive], [data-enter], [data-own-motion]";+/**+ * What stays still while a page arrives: a bar the page pins (sticky or fixed, at any breakpoint, or a section-tab+ * band, sticky by its own CSS) and anything marked data-page-still. A translate on one of them, or on what holds one,+ * would carry a sticky bar or re-anchor a fixed one.+ */+const STILL = '[data-page-still], .tab-band, [class*="sticky"], [class~="fixed"], [class*=":fixed"]';+/** The longest a page keeps arriving: a page that streams in late just appears. */+const PAGE_IN_MAX = 3000;+/** A click on a tab this recently (ms) makes the page change it causes an in-place one. */+const TAB_WINDOW = 1500;++/** Back and Forward within this long of a popstate are the browser's own: they stay instant. */+const POP_WINDOW = 1000;++function isSkeleton(n: Node): boolean {+ return n instanceof Element && (n.matches(SKELETON) || n.querySelector(SKELETON) !== null);+}++function eachImage(n: Node, fn: (img: HTMLImageElement) => void) {+ if (n instanceof HTMLImageElement) fn(n);+ else if (n instanceof Element) n.querySelectorAll("img").forEach(fn);+}++/**+ * Marks the blocks of the page that arrive (data-page-item): the page's top blocks, except that every pinned bar+ * (STILL) stays as it is and every block holding one is split into its children, down to the bar. Class and attribute+ * reads only: no layout. Returns the blocks marked.+ */+function markPageItems(content: HTMLElement): HTMLElement[] {+ const holders = new Set<Element>();+ for (const still of content.querySelectorAll(STILL)) {+ for (let n = still.parentElement; n && n !== content && !holders.has(n); n = n.parentElement) holders.add(n);+ }+ const items: HTMLElement[] = [];+ const walk = (parent: Element) => {+ for (const c of parent.children) {+ if (!(c instanceof HTMLElement) || c.matches(STILL) || c.tagName === "SCRIPT" || c.tagName === "STYLE") continue;+ if (holders.has(c)) walk(c);+ else items.push(c);+ }+ };+ walk(content);+ for (const el of items) el.setAttribute("data-page-item", "");+ return items;+}++/**+ * The page's motion, mounted once in the app frame (StudioChrome). It moves nothing itself: it sets the attributes+ * motion.css animates, only after the first paint and never under reduced motion.+ * - A new place (another first path segment, by a link or code, not Back/Forward, not a tab in the page's own tab+ * row): #content[data-page-in] for the length of the arrival, and data-page-item on the blocks that arrive (never a+ * pinned bar), so the new page (and its content when it streams in after its skeleton) fades in and settles.+ * - Content that replaces its skeleton in the same commit: data-motion-reveal (a quick fade and 4 px rise), except+ * content with motion of its own (a studio's results).+ * - Pictures added after the first paint fade in on load; while a page arrives, and on a fresh load, only those off+ * screen (the first screen shows as it loads, under the page's own fade).+ * - Sections marked data-reveal below the screen: they reveal once, on scroll.+ */+type PageIn = { started: number; timer: number; items: HTMLElement[] };++/** Ends arrival p (if it is still the current one): the page is simply there. */+function endPageIn(content: HTMLElement, p: PageIn, current: { current: PageIn | null }) {+ if (current.current !== p) return;+ delete content.dataset.pageIn;+ for (const el of p.items) el.removeAttribute("data-page-item");+ current.current = null;+}++export function PageMotion() {+ const pathname = usePathname();+ const prev = useRef<string | null>(null);+ const popAt = useRef(-Infinity);+ const tabAt = useRef<{ path: string; at: number } | null>(null);+ const pageIn = useRef<PageIn | null>(null);+ // The reveals waiting on this page (each cancel shows its section).+ const reveals = useRef<(() => void)[]>([]);+ const revealRaf = useRef(0);+ /** Looks for new data-reveal sections after the next frame (the page has painted by then). */+ const scanReveals = useCallback(() => {+ cancelAnimationFrame(revealRaf.current);+ revealRaf.current = requestAnimationFrame(() => {+ const content = document.getElementById("content");+ if (content) reveals.current.push(revealOnScroll(content));+ });+ }, []);++ useEffect(() => {+ const onPop = () => (popAt.current = performance.now());+ // Capture: it runs before the router's own listener (which may stop the event); the Navigation API names a+ // traversal too, where there is one.+ const onNavigate = (e: Event) => (e as Event & { navigationType?: string }).navigationType === "traverse" && onPop();+ // A tab in the page's own tab row: the page it opens changes in place.+ const onClick = (e: MouseEvent) => {+ const a = (e.target as Element | null)?.closest?.("a[href]");+ if (!a || !tabRowOf(a)) return;+ try {+ tabAt.current = { path: new URL(a.getAttribute("href") ?? "", location.href).pathname, at: performance.now() };+ } catch {+ tabAt.current = null;+ }+ };+ const nav = (window as Window & { navigation?: EventTarget }).navigation;+ window.addEventListener("popstate", onPop, true);+ document.addEventListener("click", onClick, true);+ nav?.addEventListener("navigate", onNavigate);+ return () => {+ window.removeEventListener("popstate", onPop, true);+ document.removeEventListener("click", onClick, true);+ nav?.removeEventListener("navigate", onNavigate);+ };+ }, []);++ // Before the new page's first paint: mark it as arriving.+ useLayoutEffect(() => {+ const from = prev.current;+ prev.current = pathname;+ const tab = tabAt.current;+ tabAt.current = null;+ const fromTabRow = !!tab && tab.path === pathname && performance.now() - tab.at < TAB_WINDOW;+ if (!newPlace(from, pathname, { fromTabRow }) || performance.now() - popAt.current < POP_WINDOW || reducedMotion()) return;+ const content = document.getElementById("content");+ if (!content) return;+ if (pageIn.current) {+ window.clearTimeout(pageIn.current.timer);+ for (const el of pageIn.current.items) el.removeAttribute("data-page-item");+ }+ const items = markPageItems(content);+ content.dataset.pageIn = "";+ const p: PageIn = { started: performance.now(), timer: 0, items };+ p.timer = window.setTimeout(() => endPageIn(content, p, pageIn), MOTION.page + 120);+ pageIn.current = p;+ }, [pathname]);++ // Skeleton → content, late pictures, and a page that streams in while it arrives.+ useEffect(() => {+ const content = document.getElementById("content");+ if (!content || reducedMotion() || typeof MutationObserver === "undefined") return;+ // The first screen's own pictures load as they always did; the lazy ones off screen fade in when they arrive.+ content.querySelectorAll<HTMLImageElement>('img[loading="lazy"]').forEach((img) => fadeInOnLoad(img, { offScreenOnly: true }));+ const mo = new MutationObserver((records) => {+ const p = pageIn.current;+ const swapped = new Set<Node>();+ let added = false;+ for (const r of records) {+ for (const n of r.removedNodes) if (isSkeleton(n)) swapped.add(r.target);+ if (r.addedNodes.length) added = true;+ }+ if (!added) return;+ if (p) {+ // Still arriving: a new block of the page (content streaming in after its skeleton) arrives too, and the+ // arrival lasts a little longer. Changes inside a block already arriving (a number, a picture) don't extend it.+ const fresh = markPageItems(content).filter((el) => !p.items.includes(el));+ if (fresh.length) {+ p.items.push(...fresh);+ window.clearTimeout(p.timer);+ const left = Math.max(0, PAGE_IN_MAX - (performance.now() - p.started));+ p.timer = window.setTimeout(() => endPageIn(content, p, pageIn), Math.min(left, MOTION.page + 120));+ }+ }+ for (const r of records) {+ for (const n of r.addedNodes) {+ eachImage(n, (img) => fadeInOnLoad(img, { offScreenOnly: !!p }));+ if (n instanceof Element && (n.matches("[data-reveal]") || n.querySelector("[data-reveal]"))) scanReveals();+ if (p || !swapped.has(r.target) || !(n instanceof HTMLElement) || isSkeleton(n)) continue;+ if (n.closest(OWN_MOTION) || n.querySelector(OWN_MOTION)) continue;+ n.dataset.motionReveal = "";+ const done = (e: AnimationEvent) => {+ if (e.target !== n) return;+ n.removeEventListener("animationend", done);+ delete n.dataset.motionReveal;+ };+ n.addEventListener("animationend", done);+ }+ }+ });+ mo.observe(content, { childList: true, subtree: true });+ return () => mo.disconnect();+ }, [scanReveals]);++ // Sections below the screen reveal as they come on screen (once per page view; a print shows them all).+ useEffect(() => {+ const showAll = () => {+ cancelAnimationFrame(revealRaf.current);+ for (const c of reveals.current.splice(0)) c();+ };+ scanReveals();+ window.addEventListener("beforeprint", showAll);+ return () => {+ window.removeEventListener("beforeprint", showAll);+ showAll();+ };+ }, [pathname, scanReveals]);++ return null;+}diff --git a/src/components/preset-gallery.tsx b/src/components/preset-gallery.tsxindex bb2c23ff..776ebcc2 100644--- a/src/components/preset-gallery.tsx+++ b/src/components/preset-gallery.tsx@@ -72,9 +72,9 @@ export const PresetCard = memo(function PresetCard({ref={ref}href={href}{...handlers}- className="group/card flex min-w-0 flex-col gap-2 rounded-xl p-1.5 transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring"+ className="group/card card-motion card-fill flex min-w-0 flex-col gap-2 rounded-xl p-1.5 outline-none focus-visible:ring-2 focus-visible:ring-ring">- <div className="relative aspect-[4/3] overflow-hidden rounded-lg bg-muted">+ <div className="card-cover relative aspect-[4/3] overflow-hidden rounded-lg bg-muted"><PresetPreview preview={preset.preview} hue={preset.hue} playing={playing} asked={asked} place={place} sizes={sizes} flip={previewFlip(preset)} />{!bare && (<>@@ -203,8 +203,8 @@ export interface LinkCard {function LeadingCard({ card }: { card: LinkCard }) {return (- <Link href={card.href} className="group/card flex min-w-0 flex-col gap-2 rounded-xl p-1.5 transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring" data-leading-card>- <div className="relative aspect-[4/3] overflow-hidden rounded-lg bg-muted">+ <Link href={card.href} className="group/card card-motion card-fill flex min-w-0 flex-col gap-2 rounded-xl p-1.5 outline-none focus-visible:ring-2 focus-visible:ring-ring" data-leading-card>+ <div className="card-cover relative aspect-[4/3] overflow-hidden rounded-lg bg-muted">{card.cover}{card.badge && <span className="pointer-events-none absolute top-1.5 right-1.5 rounded-full bg-highlight px-1.5 py-0.5 text-[10.5px] font-semibold text-highlight-foreground">{card.badge}</span>}</div>diff --git a/src/components/remove-object/remove-object-tool.tsx b/src/components/remove-object/remove-object-tool.tsxindex 8ac1996e..8431ac44 100644--- a/src/components/remove-object/remove-object-tool.tsx+++ b/src/components/remove-object/remove-object-tool.tsx@@ -740,7 +740,7 @@ function RunPanel({ run, onAgain, onRedo }: { run: Run; onAgain: () => void; onR) : (<div className="space-y-3"><div className="h-1.5 overflow-hidden rounded-full bg-muted" role="progressbar" aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.round(state.progress * 100)} aria-label="Progress">- <div className={cn("h-full transition-[width]", state.status === "failed" ? "bg-destructive" : "bg-primary")} style={{ width: `${Math.max(4, state.progress * 100)}%` }} />+ <div className={cn("h-full origin-left transition-transform duration-(--motion-slow) ease-standard", state.status === "failed" ? "bg-destructive" : "bg-primary")} style={{ transform: `scaleX(${(Math.max(4, state.progress * 100)) / 100})` }} /></div><p className={cn("text-[13px]", state.status === "failed" ? "text-destructive" : "text-muted-foreground")} aria-live="polite">{state.status === "failed" ? `${state.label}: ${state.error}` : state.label}diff --git a/src/components/restore/restore-tool.tsx b/src/components/restore/restore-tool.tsxindex d186a2de..f1eaed7d 100644--- a/src/components/restore/restore-tool.tsx+++ b/src/components/restore/restore-tool.tsx@@ -394,7 +394,7 @@ function RunPanel({ run, onAgain }: { run: Run; onAgain: () => void }) {) : (<div className="space-y-3"><div className="h-1.5 overflow-hidden rounded-full bg-muted" role="progressbar" aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.round(state.progress * 100)} aria-label="Progress">- <div className={cn("h-full transition-[width]", state.status === "failed" ? "bg-destructive" : "bg-primary")} style={{ width: `${Math.max(4, state.progress * 100)}%` }} />+ <div className={cn("h-full origin-left transition-transform duration-(--motion-slow) ease-standard", state.status === "failed" ? "bg-destructive" : "bg-primary")} style={{ transform: `scaleX(${(Math.max(4, state.progress * 100)) / 100})` }} /></div><p className={cn("text-[13px]", state.status === "failed" ? "text-destructive" : "text-muted-foreground")} aria-live="polite">{state.status === "failed" ? `${state.label}: ${state.error}` : state.label}diff --git a/src/components/share/share-dialog.tsx b/src/components/share/share-dialog.tsxindex dcf1b686..97af1433 100644--- a/src/components/share/share-dialog.tsx+++ b/src/components/share/share-dialog.tsx@@ -175,7 +175,10 @@ export function LinkResult({ created, onDone }: { created: ShareCreated; onDone:})}>- {copied ? <Check /> : <Copy />} {copied ? "Copied" : "Copy"}+ {copied ? <Check className="motion-confirm" /> : <Copy />}{" "}+ <span key={copied ? "done" : "copy"} className="motion-swap">+ {copied ? "Copied" : "Copy"}+ </span></Button></div>{(local || signIn === false) && (diff --git a/src/components/shorts/history.tsx b/src/components/shorts/history.tsxindex 24a18b63..eb855d4d 100644--- a/src/components/shorts/history.tsx+++ b/src/components/shorts/history.tsx@@ -46,8 +46,8 @@ export function ShortsHistory({ onStart }: { onStart: () => void }) {function SessionCard({ s }: { s: ShortsSessionCard }) {const out = s.cover?.status === "succeeded" ? s.cover.outputs.find((o) => o.kind === "video") : undefined;return (- <Link href={`/shorts/${s.id}`} className="group/card min-w-0 rounded-xl p-1.5 outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring">- <div className="relative aspect-[9/14] overflow-hidden rounded-lg bg-muted">+ <Link href={`/shorts/${s.id}`} className="group/card card-motion card-fill min-w-0 rounded-xl p-1.5 outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <div className="card-cover relative aspect-[9/14] overflow-hidden rounded-lg bg-muted">{out ? (<MediaThumb output={out} />) : (diff --git a/src/components/shorts/preset-card.tsx b/src/components/shorts/preset-card.tsxindex 0a393c19..a3ea97c6 100644--- a/src/components/shorts/preset-card.tsx+++ b/src/components/shorts/preset-card.tsx@@ -42,7 +42,7 @@ export const LookCard = memo(function LookCard({aria-pressed={selected}data-look={id}className={cn(- "group/card flex min-w-0 flex-col gap-2 rounded-xl p-1.5 text-left transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",+ "group/card card-motion flex min-w-0 flex-col gap-2 rounded-xl p-1.5 text-left outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",selected && "bg-brand-faint hover:bg-brand-faint-hover",)}>diff --git a/src/components/shorts/session-view.tsx b/src/components/shorts/session-view.tsxindex cc961ce6..62095596 100644--- a/src/components/shorts/session-view.tsx+++ b/src/components/shorts/session-view.tsx@@ -164,7 +164,7 @@ function Session({ s }: { s: View }) {{Math.round(overall * 100)}%</p><div className="relative h-1 w-40 overflow-hidden rounded-full bg-background/70">- <div className="h-full bg-primary transition-[width] duration-500" style={{ width: `${Math.round(overall * 100)}%` }} />+ <div className="h-full bg-primary origin-left transition-transform duration-(--motion-slow) ease-standard" style={{ transform: `scaleX(${(Math.round(overall * 100)) / 100})` }} /></div></div>)}diff --git a/src/components/shorts/ui.tsx b/src/components/shorts/ui.tsxindex 0577eeb8..b638715a 100644--- a/src/components/shorts/ui.tsx+++ b/src/components/shorts/ui.tsx@@ -200,7 +200,7 @@ export function ClipBar({ clip, onRemove }: { clip: SourceClip; onRemove: () =></p>{clip.uploading && clip.progress < 1 && (<div className="mt-1 h-1 overflow-hidden rounded-full bg-background">- <div className="h-full bg-primary transition-[width]" style={{ width: `${Math.round(clip.progress * 100)}%` }} />+ <div className="h-full bg-primary origin-left transition-transform duration-(--motion-slow) ease-standard" style={{ transform: `scaleX(${(Math.round(clip.progress * 100)) / 100})` }} /></div>)}</div>diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsxindex 971f40e4..4d7d13e4 100644--- a/src/components/studio/composer.tsx+++ b/src/components/studio/composer.tsx@@ -1603,10 +1603,19 @@ export function Composer({ docked }: { docked: boolean }) {onClick={submit}disabled={create.isPending || signature.lock.isPending || priceUnavailable}aria-label={blocker ? `Generate — ${blocker.message}` : "Generate"}+ aria-busy={create.isPending || signature.lock.isPending || undefined}// Blocked, it stays the brand colour (paler, the arrow still 3:1 or more): pressing it still says what's missing and points at it.className={cn("size-10 shrink-0 rounded-full", blocker && "bg-primary/70 hover:bg-primary/80")}>- {create.isPending || signature.lock.isPending ? <Loader2 className="size-4 animate-spin" /> : <ArrowUp className="size-4" />}+ {create.isPending || signature.lock.isPending ? (+ // A quick send keeps its arrow; a wait of more than a moment hands over to the spinner.+ <span className="grid place-items-center">+ <ArrowUp className="motion-hand-off col-start-1 row-start-1 size-4" />+ <Loader2 className="motion-spinner col-start-1 row-start-1 size-4" />+ </span>+ ) : (+ <ArrowUp className="size-4" />+ )}</Button></TooltipTrigger><TooltipContent>diff --git a/src/components/studio/feed-motion.ts b/src/components/studio/feed-motion.tsnew file mode 100644index 00000000..07b272d1--- /dev/null+++ b/src/components/studio/feed-motion.ts@@ -0,0 +1,84 @@+"use client";++import { useEffect, useLayoutEffect, useRef } from "react";+import { reducedMotion } from "@/lib/ui-motion";++/**+ * The feed's motion (motion.css: [data-enter], [data-arrive], [data-follow]). Only what happens while the studio is+ * open moves: a request just sent, and a result that finishes then. A feed that loads, a page that opens and a scroll+ * back show everything as it is, still.+ */++/** Runs this tab has seen in progress: when one of them finishes, its result arrives with motion. */+const live = new Set<string>();+/** The last "Keep going with this picture" row's height: a run on its way keeps that much room under it, so its row lands without pushing the feed. */+let rowHeight = 0;++/** The most a mark stays: an element that never animates (off screen, skipped) doesn't keep it to animate later. */+const MARK_MAX = 1500;++function mark(el: HTMLElement | null, attr: "data-enter" | "data-arrive" | "data-follow", i = 0) {+ if (!el || reducedMotion()) return;+ el.style.setProperty("--i", String(i));+ el.setAttribute(attr, "");+ let timer = 0;+ const clear = () => {+ window.clearTimeout(timer);+ el.removeEventListener("animationend", done);+ el.removeAttribute(attr);+ };+ // A result's light sweep (its ::after) is the last of its motion.+ const done = (e: AnimationEvent) => {+ if (e.target === el && (attr !== "data-arrive" || e.pseudoElement === "::after")) clear();+ };+ el.addEventListener("animationend", done);+ timer = window.setTimeout(clear, MARK_MAX);+}++/** A pending tile: its run is in progress in this tab. */+export function useLiveRun(id: string) {+ useEffect(() => {+ live.add(id);+ }, [id]);+}++/** A result tile: it settles in, with one light passing over it, when its run finished while the studio was open. */+export function useArrival<T extends HTMLElement>(id: string, index: number) {+ const ref = useRef<T>(null);+ useLayoutEffect(() => {+ if (!live.has(id)) return;+ mark(ref.current, "data-arrive", index);+ // Every tile and the row of the same run mount in this commit: they all see it first.+ queueMicrotask(() => live.delete(id));+ }, [id, index]);+ return ref;+}++/** A request's section: it rises in when it was just sent (in progress, made in the last moments), never on a load. */+export function useEnter<T extends HTMLElement>(id: string, active: boolean, createdAt: number) {+ const ref = useRef<T>(null);+ const seen = useRef<string | null>(null);+ useLayoutEffect(() => {+ if (seen.current === id) return;+ seen.current = id;+ if (active && Date.now() - createdAt < 15_000) mark(ref.current, "data-enter");+ }, [id, active, createdAt]);+ return ref;+}++/** The next-steps row under the newest result: remembers its height, and follows its result in when that just arrived. */+export function useFollowRow<T extends HTMLElement>(id: string) {+ const ref = useRef<T>(null);+ useLayoutEffect(() => {+ const el = ref.current;+ if (!el) return;+ if (el.offsetHeight > 0) rowHeight = el.offsetHeight;+ if (live.has(id)) mark(el, "data-follow");+ }, [id]);+ return ref;+}++/** The room a run on its way keeps for its row (0 until a row has been seen on this page). */+export function reservedRowHeight(): number {+ return rowHeight;+}diff --git a/src/components/studio/feed.tsx b/src/components/studio/feed.tsxindex dd150ac1..0fca3d15 100644--- a/src/components/studio/feed.tsx+++ b/src/components/studio/feed.tsx@@ -31,6 +31,7 @@ import { useNow } from "./use-now";import { PlaceholderChip } from "@/components/demo-mode";import { Viewer } from "./viewer";import { NextSteps } from "@/components/nav/next-steps";+import { reservedRowHeight, useArrival, useEnter, useFollowRow, useLiveRun } from "./feed-motion";export { MediaThumb } from "./result-media";export { downloadName } from "@/lib/library";@@ -50,6 +51,7 @@ export function PendingTile({ g, ratio }: { g: Generation; ratio: number }) {// Running on the ComfyUI on this computer: its live preview (sharper with each step), where it runs, and its step now.// Its % and time left come from its own steps then, so they agree with "step 9 of 12".const local = useLocalJob(g.id, now);+ useLiveRun(g.id);const label = (local && jobWords(local.job, g.kind, g.message ?? undefined, local.comfy)) ?? (g.status === "queued" ? (g.message ?? "Queued") : (g.message ?? "Generating…"));const steps = local ? jobFraction(local.job) : null;const saving = local && (local.job.phase === "saving" || local.job.phase === "done");@@ -116,7 +118,7 @@ export function PendingTile({ g, ratio }: { g: Generation; ratio: number }) {</div>{bar != null && (<div className="absolute inset-x-0 top-0 h-0.5 bg-transparent">- <div className="h-full bg-primary transition-[width] duration-500" style={{ width: `${bar}%` }} />+ <div className="h-full origin-left bg-primary transition-transform duration-(--motion-slow) ease-standard" style={{ transform: `scaleX(${bar / 100})` }} /></div>)}</div>@@ -211,14 +213,16 @@ const OutputTile = memo(function OutputTile({ g, index, ratio, layered, count }:const o = g.outputs[index];const audio = o.kind === "audio";const ctx = useMemo(() => ({ reuse: !!feed.reuse }), [feed.reuse]);+ const arrive = useArrival<HTMLDivElement>(g.id, index);return (// The tile opens on click; keyboards and screen readers use the Open button over it (a sibling of// the action buttons, so no button sits inside another).<div+ ref={arrive}onClick={() => feed.open(g, index)}onPointerEnter={(e) => e.pointerType === "mouse" && !hot && setHot("bar")}onFocus={() => canHover && !hot && setHot("bar")}- className="group/tile relative h-56 max-w-full animate-fade-up cursor-zoom-in overflow-hidden rounded-xl bg-muted sm:h-64"+ className="group/tile relative h-56 max-w-full cursor-zoom-in overflow-hidden rounded-xl bg-muted sm:h-64"style={{ aspectRatio: audio ? 1.6 : layered ? Math.max(ratio, 0.8) : ratio }}>{layered ? <LayersStack g={g} /> : <MediaThumb output={o} g={g} inset={!canHover || g.favorite} />}@@ -270,12 +274,15 @@ const OutputTile = memo(function OutputTile({ g, index, ratio, layered, count }:});/** One request: the user's words in serif, a meta line, then its outputs (or progress / failure). */-export const GenerationGroup = memo(function GenerationGroup({ g, newest }: { g: Generation; newest?: boolean }) {+export const GenerationGroup = memo(function GenerationGroup({ g, newest, first }: { g: Generation; newest?: boolean; /** The feed's top request (newest first). */ first?: boolean }) {const feed = useFeed();const { favorite, trash } = useGenerationActions();const ratio = tileRatio(g);const active = g.status === "queued" || g.status === "running";const placeholders = Math.max(1, g.request.params?.numOutputs ?? 1);+ const enter = useEnter<HTMLElement>(g.id, active, g.createdAt);+ // The top run on its way, with one picture to come: its next-steps row will land under it, so its room is kept now.+ const reserve = first && active && placeholders === 1 ? reservedRowHeight() : 0;const layered = g.status === "succeeded" && isLayered(g);const shown = shownOutputs(g);const single = g.status === "succeeded" && shown.length === 1 ? g.outputs[shown[0]] : null;@@ -295,7 +302,7 @@ export const GenerationGroup = memo(function GenerationGroup({ g, newest }: { g:].filter((x, i, all) => x && all.indexOf(x) === i);return (- <section data-gen-id={g.id} className="group/gen animate-fade-up space-y-2.5 [contain-intrinsic-size:auto_330px] [content-visibility:auto]">+ <section ref={enter} data-gen-id={g.id} className="group/gen space-y-2.5 [contain-intrinsic-size:auto_330px] [content-visibility:auto]"><header className="flex items-start gap-3"><div className="min-w-0 flex-1"><h2 className="line-clamp-2 font-heading text-[19px] leading-snug" title={g.prompt ?? undefined}>@@ -399,11 +406,23 @@ export const GenerationGroup = memo(function GenerationGroup({ g, newest }: { g:))}</div>{/* Under the newest result: where it can go next, with it attached. A group with several takes has none: which one to take on is picked on its tile. */}- {newest && !layered && shown.length === 1 && <NextSteps g={g} index={shown[0]} variant="row" max={5} className="pt-1" />}+ {newest && !layered && shown.length === 1 && <NextStepsRow g={g} index={shown[0]} />}+ {reserve > 0 && <div aria-hidden style={{ height: reserve }} />}</section>);});+/** The next-steps row under the newest result (it follows its result in when that just arrived). */+function NextStepsRow({ g, index }: { g: Generation; index: number }) {+ const row = useFollowRow<HTMLDivElement>(g.id);+ return (+ // Nothing to show (a text result): it takes no room, as before (its margin in the section's spacing cancels out).+ <div ref={row} className="empty:-mt-2.5">+ <NextSteps g={g} index={index} variant="row" max={5} className="pt-1" />+ </div>+ );+}+export function Feed({items,onReuse,@@ -443,8 +462,8 @@ export function Feed({return (<FeedCtx.Provider value={api}><div className="space-y-9">- {items.map((g) => (- <GenerationGroup key={g.id} g={g} newest={g.id === newest} />+ {items.map((g, i) => (+ <GenerationGroup key={g.id} g={g} newest={g.id === newest} first={i === 0} />))}</div>{open && pos >= 0 && (diff --git a/src/components/studio/viewer.tsx b/src/components/studio/viewer.tsxindex f0fb0c50..a5ecdaed 100644--- a/src/components/studio/viewer.tsx+++ b/src/components/studio/viewer.tsx@@ -2,7 +2,7 @@import { ChevronLeft, ChevronRight, Columns2, Copy, Info, Layers, MoreHorizontal, X } from "lucide-react";import Link from "next/link";-import { useEffect, useMemo, useRef, useState } from "react";+import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";import { Button } from "@/components/ui/button";import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog";import { Kbd } from "@/components/ui/kbd";@@ -167,6 +167,22 @@ export function Viewer({const [saving, setSaving] = useState(false);// A video this browser can't decode (HEVC or 10-bit H.264 on some systems): shown as a file to download instead.const [failedVideo, setFailedVideo] = useState<string | null>(null);+ // Closing plays the dialog's exit first; the owner hears onClose once it has gone (Radix calls onCloseAutoFocus then).+ const [open, setOpen] = useState(true);+ const dismiss = () => setOpen(false);+ // Where focus goes back to when it closes: what opened it (read before the dialog takes focus), else this result's+ // Open button in the feed.+ const opener = useRef<HTMLElement | null>(null);+ useLayoutEffect(() => {+ const at = document.activeElement;+ if (at instanceof HTMLElement && at !== document.body) opener.current = at;+ }, []);+ const giveFocusBack = () => {+ const back =+ (opener.current?.isConnected ? opener.current : null) ??+ document.querySelector<HTMLElement>(`[data-gen-id="${CSS.escape(g.id)}"] button[aria-label^="Open"]`);+ back?.focus({ preventScroll: true });+ };const run = useActionRunner({ onReuse: onReuse && ((x) => (onReuse(x), onClose())), onCompare: () => setComparing((v) => !v), onDeleted: onClose });const engineMode = useEngineMode();const visitor = useLikelyVisitor();@@ -311,9 +327,14 @@ export function Viewer({);return (- <Dialog open onOpenChange={(v) => !v && onClose()}>+ <Dialog open={open} onOpenChange={(v) => !v && dismiss()}><DialogContentshowCloseButton={false}+ onCloseAutoFocus={(e) => {+ e.preventDefault();+ onClose();+ giveFocusBack();+ }}className="flex h-[100svh] w-screen max-w-none gap-0 overflow-hidden rounded-none p-0 sm:max-w-none md:h-[min(92vh,900px)] md:w-[min(96vw,1400px)] md:rounded-xl"><DialogTitle className="sr-only">{userTitle(g)}</DialogTitle>@@ -389,7 +410,7 @@ export function Viewer({<span className="inline-flex items-center gap-1 text-[12px] text-muted-foreground"><Info className="size-3.5" /> Details</span>- <button onClick={onClose} className="grid size-8 place-items-center rounded-lg text-muted-foreground hover:bg-accent hover:text-foreground" aria-label="Close">+ <button onClick={dismiss} className="grid size-8 place-items-center rounded-lg text-muted-foreground hover:bg-accent hover:text-foreground" aria-label="Close"><X className="size-4" /></button></div>@@ -448,7 +469,7 @@ export function Viewer({</p></aside>- <button onClick={onClose} className="absolute top-3 right-3 grid size-10 place-items-center rounded-full bg-black/40 text-white backdrop-blur md:hidden" aria-label="Close">+ <button onClick={dismiss} className="absolute top-3 right-3 grid size-10 place-items-center rounded-full bg-black/40 text-white backdrop-blur md:hidden" aria-label="Close"><X className="size-5" /></button>diff --git a/src/components/swap-studio/workbench.tsx b/src/components/swap-studio/workbench.tsxindex dff35499..146d063b 100644--- a/src/components/swap-studio/workbench.tsx+++ b/src/components/swap-studio/workbench.tsx@@ -356,7 +356,7 @@ function ClipsPanel({<div className="mb-2 rounded-lg bg-muted px-2.5 py-2 text-[12px]"><span className="block truncate font-medium">{upload.name}</span><div className="mt-1 h-1 overflow-hidden rounded-full bg-background" role="progressbar" aria-valuenow={Math.round(upload.progress * 100)} aria-valuemin={0} aria-valuemax={100} aria-label="Uploading">- <div className="h-full bg-primary transition-[width]" style={{ width: `${Math.round(upload.progress * 100)}%` }} />+ <div className="h-full bg-primary origin-left transition-transform duration-(--motion-slow) ease-standard" style={{ transform: `scaleX(${(Math.round(upload.progress * 100)) / 100})` }} /></div></div>)}diff --git a/src/components/ui/button.tsx b/src/components/ui/button.tsxindex 18407c9c..fc4e758b 100644--- a/src/components/ui/button.tsx+++ b/src/components/ui/button.tsx@@ -4,7 +4,7 @@ import { cn } from "cn"import { Slot } from "radix-ui"const buttonVariants = cva(- "group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ "group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-[color,background-color,border-color,box-shadow,scale] duration-(--motion-base) ease-(--ease-standard) outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:duration-(--motion-fast) active:not-aria-[haspopup]:scale-(--motion-press-card) disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",{variants: {variant: {@@ -25,12 +25,12 @@ const buttonVariants = cva(xs: "h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",sm: "h-7 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",lg: "h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",- icon: "size-8",+ icon: "size-8 active:not-aria-[haspopup]:scale-(--motion-press)","icon-xs":- "size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3",+ "size-6 active:not-aria-[haspopup]:scale-(--motion-press) rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3","icon-sm":- "size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg",- "icon-lg": "size-9",+ "size-7 active:not-aria-[haspopup]:scale-(--motion-press) rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg",+ "icon-lg": "size-9 active:not-aria-[haspopup]:scale-(--motion-press)",},},defaultVariants: {diff --git a/src/components/ui/count-up.tsx b/src/components/ui/count-up.tsxnew file mode 100644index 00000000..1e8bf460--- /dev/null+++ b/src/components/ui/count-up.tsx@@ -0,0 +1,60 @@+"use client";++import { useEffect, useRef } from "react";+import { counts, countUp, firstSight, onceVisible, reducedMotion } from "@/lib/ui-motion";++/** Numbers that have counted up this session (each once; without storage, once per page view). */+const SEEN_KEY = "fuobe:counted";++function seen(key: string): boolean {+ try {+ return (JSON.parse(sessionStorage.getItem(SEEN_KEY) ?? "[]") as string[]).includes(key);+ } catch {+ return false;+ }+}++function markSeen(key: string) {+ try {+ const list = JSON.parse(sessionStorage.getItem(SEEN_KEY) ?? "[]") as string[];+ if (!list.includes(key)) sessionStorage.setItem(SEEN_KEY, JSON.stringify([...list, key].slice(-200)));+ } catch {+ // Private mode or storage off: it may count again on another visit, which is fine.+ }+}++/**+ * A number that settles up to its value the first time it scrolls on screen (once per session): from about 70 % to the+ * value in 600 ms, in tabular figures with its width held, so nothing beside it moves. The server renders the final+ * value (no JS, screen readers and a print read that). A number under 10 doesn't count; a number already on screen when+ * its page shows (a fresh load or a page arriving by a link) is drawn final, so it never competes with the page's own+ * motion; under reduced motion it never counts. Where it is comes from the browser's intersection pass, not a layout read.+ */+export function CountUp({ value, id, className }: { value: number; /** Tells apart two counts of the same value on a page. */ id?: string; className?: string }) {+ const ref = useRef<HTMLSpanElement>(null);+ useEffect(() => {+ const el = ref.current;+ if (!el || !counts(value) || reducedMotion()) return;+ const key = `${location.pathname}|${id ?? ""}|${value}`;+ if (seen(key)) return;+ let stop = () => {};+ let cancelVisible = () => {};+ const cancelSight = firstSight(el, (where) => {+ if (where === "on") return markSeen(key);+ cancelVisible = onceVisible(el, () => {+ markSeen(key);+ stop = countUp(el, value);+ });+ });+ return () => {+ cancelSight();+ cancelVisible();+ stop();+ };+ }, [value, id]);+ return (+ <span ref={ref} className={className} style={{ display: "inline-block", minWidth: `${String(value).length}ch`, fontVariantNumeric: "tabular-nums" }}>+ {value}+ </span>+ );+}diff --git a/src/lib/glide-scroll.ts b/src/lib/glide-scroll.tsindex a76812e6..385552a4 100644--- a/src/lib/glide-scroll.ts+++ b/src/lib/glide-scroll.ts@@ -1,3 +1,5 @@+import { REVEAL_EVENT } from "@/lib/ui-motion";+/** A refined scroll to a section: ease-out over 450 to 650 ms (longer for a longer way, never crawling), landing exactly* where a jump to its #id would (under the sticky bars: the page's scroll-padding-top and the section's@@ -29,6 +31,8 @@ let stopCurrent: (() => void) | null = null;/** Glides the page to `el`. Resolves true when it landed, false when the visitor took over (or another glide began). */export function glideTo(el: Element): Promise<boolean> {stopCurrent?.();+ // Sections on the way (and the target) show before the glide starts, so it never lands on one still waiting.+ document.dispatchEvent(new CustomEvent(REVEAL_EVENT, { detail: { target: el } }));const instant = window.matchMedia("(prefers-reduced-motion: reduce)").matches;if (instant) {window.scrollTo({ top: landingY(el), behavior: "instant" });diff --git a/src/lib/ui-motion.ts b/src/lib/ui-motion.tsnew file mode 100644index 00000000..f04a6983--- /dev/null+++ b/src/lib/ui-motion.ts@@ -0,0 +1,336 @@+/**+ * The site's motion in numbers, for scripts: the same tokens as src/app/motion.css (CSS reads those; this file is+ * for what CSS can't do: staggers, count-ups, reveal-once, and the reduced-motion check). No dependency.+ * Under prefers-reduced-motion every duration and delay is 0 and every change lands at once.+ */++export const MOTION = { fast: 120, base: 200, slow: 320, page: 380, count: 600, stagger: 40 } as const;+export type MotionToken = keyof typeof MOTION;++export const EASE = {+ standard: "cubic-bezier(0.2, 0, 0, 1)",+ enter: "cubic-bezier(0.08, 0.82, 0.17, 1)",+ exit: "cubic-bezier(0.3, 0, 1, 1)",+ emphasised: "cubic-bezier(0.32, 0.72, 0, 1)",+} as const;++/** The most steps a stagger takes: later items move with the last one. */+export const STAGGER_CAP = 6;++/**+ * The event that shows sections waiting to reveal before a scroll lands on them: dispatch it on `document` with+ * `detail: { target }` (an element, or its id or "#id") before an in-page jump starts. Links to "#…" do it by themselves.+ */+export const REVEAL_EVENT = "fuobe:reveal-to";++/** True when the system asks for less motion (false on the server, where nothing moves anyway). */+export function reducedMotion(): boolean {+ return typeof window !== "undefined" && typeof window.matchMedia === "function" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;+}++/** A token in milliseconds: 0 under reduced motion. */+export function ms(token: MotionToken, reduce = reducedMotion()): number {+ return reduce ? 0 : MOTION[token];+}++/** The delay of item `i` in a staggered group (ms): `step` each, capped at `cap` steps; 0 under reduced motion. */+export function stagger(i: number, step: number = MOTION.stagger, cap: number = STAGGER_CAP, reduce = reducedMotion()): number {+ if (reduce || !(i > 0)) return 0;+ return Math.min(Math.floor(i), cap) * step;+}++/** The count-up curve: a quartic ease-out, 0 → 1 (quick at first, no crawl at the end). */+export function easeOutQuart(t: number): number {+ const c = Math.min(1, Math.max(0, t));+ return 1 - (1 - c) ** 4;+}++/** Where a count-up starts: about 70 % of the value (so it reads as settling, not as counting from zero). */+export function countFrom(value: number): number {+ return Math.round(value * 0.7);+}++/** A number counts up only when it is a whole number of at least 10. */+export function counts(value: number): boolean {+ return Number.isInteger(value) && value >= 10;+}++/** The number shown `elapsed` ms into a count-up to `to` lasting `duration` ms. */+export function countAt(to: number, elapsed: number, duration: number = MOTION.count): number {+ if (duration <= 0 || elapsed >= duration) return to;+ const from = countFrom(to);+ return Math.round(from + (to - from) * easeOutQuart(elapsed / duration));+}++/**+ * Counts `el`'s text up to `to` (rAF, text only). Under reduced motion, or for a number under 10, the final value is+ * written at once. Returns a cancel, which also writes the final value.+ */+export function countUp(el: HTMLElement, to: number, { duration = MOTION.count, reduce = reducedMotion() }: { duration?: number; reduce?: boolean } = {}): () => void {+ const done = () => {+ el.textContent = String(to);+ };+ if (reduce || !counts(to) || duration <= 0) {+ done();+ return () => {};+ }+ let raf = 0;+ const start = performance.now();+ const tick = (now: number) => {+ const t = now - start;+ el.textContent = String(countAt(to, t, duration));+ if (t < duration) raf = requestAnimationFrame(tick);+ };+ el.textContent = String(countFrom(to));+ raf = requestAnimationFrame(tick);+ return () => {+ cancelAnimationFrame(raf);+ done();+ };+}++/**+ * Whether a page change is a new place (it gets the page motion). Not when the link was a tab in the page's own tab+ * row (`fromTabRow`: Marketing's row holds /marketing and /ads alike), nor within one first path segment (a hub's tabs+ * /audio → /audio/music, a page's own sections ?tab=…, the same page again): those change in place.+ */+export function newPlace(from: string | null, to: string, { fromTabRow = false }: { fromTabRow?: boolean } = {}): boolean {+ if (from === null || fromTabRow) return false;+ const first = (p: string) => p.split(/[?#]/)[0].split("/").filter(Boolean)[0] ?? "";+ return first(from) !== first(to);+}++/**+ * A tab row in the page: a nav, tablist or tab row that marks the current page (aria-current / aria-selected). A link+ * in one is a tab: following it changes the page in place.+ */+export function tabRowOf(link: Element): Element | null {+ const row = link.closest('[data-tab-row], [role="tablist"], nav');+ if (!row || !row.closest("#content")) return null;+ return row.querySelector('[aria-current="page"], [aria-selected="true"]') ? row : null;+}++// ---------------------------------------------------------------------------------------------------------------+// Seen once: shared IntersectionObservers, read only in their callbacks (never a layout read of our own).++type Reveal = () => void;+let observer: IntersectionObserver | null = null;+const waiting = new WeakMap<Element, Reveal>();+/** Set by the first callback of any observer here: the browser does deliver them. */+let observersAlive = false;++function sharedObserver(): IntersectionObserver | null {+ if (observer || typeof IntersectionObserver === "undefined") return observer;+ observer = new IntersectionObserver(+ (entries) => {+ observersAlive = true;+ for (const e of entries) {+ if (!e.isIntersecting) continue;+ const run = waiting.get(e.target);+ observer?.unobserve(e.target);+ waiting.delete(e.target);+ run?.();+ }+ },+ { rootMargin: "0px 0px -10% 0px", threshold: 0 },+ );+ return observer;+}++/** Calls `run` once, the first time `el` comes on screen. Returns a cancel. Without IntersectionObserver it runs now. */+export function onceVisible(el: Element, run: Reveal): () => void {+ const io = sharedObserver();+ if (!io) {+ run();+ return () => {};+ }+ waiting.set(el, run);+ io.observe(el);+ return () => {+ waiting.delete(el);+ io.unobserve(el);+ };+}++/** Where an element was when first looked at: on screen, or off it (below it, or above it). */+export type Sight = "on" | "below" | "above";+let sightObserver: IntersectionObserver | null = null;+const sightWaiting = new WeakMap<Element, (s: Sight) => void>();++/**+ * Calls `run` once with where `el` is now (on screen, below or above it), from the browser's own next intersection+ * pass: no forced layout. Returns a cancel. Without IntersectionObserver it says "on" (so nothing is hidden).+ */+export function firstSight(el: Element, run: (s: Sight) => void): () => void {+ if (!sightObserver && typeof IntersectionObserver !== "undefined") {+ sightObserver = new IntersectionObserver((entries) => {+ observersAlive = true;+ for (const e of entries) {+ const cb = sightWaiting.get(e.target);+ sightObserver?.unobserve(e.target);+ sightWaiting.delete(e.target);+ const rootH = e.rootBounds?.height ?? window.innerHeight;+ cb?.(e.isIntersecting ? "on" : e.boundingClientRect.top >= rootH ? "below" : "above");+ }+ });+ }+ if (!sightObserver) {+ run("on");+ return () => {};+ }+ sightWaiting.set(el, run);+ sightObserver.observe(el);+ return () => {+ sightWaiting.delete(el);+ sightObserver?.unobserve(el);+ };+}++/** The element a "#id" (or an id, or an element) names. */+function targetOf(t: Element | string | null | undefined): Element | null {+ if (!t) return null;+ if (typeof t !== "string") return t;+ const id = t.startsWith("#") ? t.slice(1) : t;+ if (!id) return null;+ try {+ return document.getElementById(decodeURIComponent(id));+ } catch {+ return document.getElementById(id);+ }+}++/** The longest the page waits for the browser's first intersection pass before it shows every section anyway. */+const REVEAL_SAFETY = 3000;++/**+ * Sections marked data-reveal that start below the screen fade in and settle 8 px when they first come on screen+ * (their data-reveal-item children follow, 40 ms apart, 6 steps at most). Never hidden: a section on screen or above+ * it, any section under reduced motion, on a page opened at a #part, or in a print. A jump within the page (a "#…"+ * link, a hash change, REVEAL_EVENT, find in page) shows its target and every section above it at once, with no+ * transition, so the scroll lands on them ready. If the browser never reports where sections are within 3 s, they+ * all show. Returns a cancel that shows all.+ */+export function revealOnScroll(root: ParentNode, { reduce = reducedMotion() }: { reduce?: boolean } = {}): () => void {+ if (reduce || typeof document === "undefined" || location.hash) return () => {};+ /** Each section still waiting (on its first look or on its scroll), with what stops that wait. */+ const pending = new Map<HTMLElement, () => void>();+ for (const el of root.querySelectorAll<HTMLElement>("[data-reveal]:not([data-reveal=in]):not([data-reveal=wait]):not([data-reveal=now]):not([data-reveal=look])")) {+ el.dataset.reveal = "look";+ pending.set(+ el,+ firstSight(el, (where) => {+ if (where !== "below") {+ pending.delete(el);+ el.dataset.reveal = "in";+ return;+ }+ el.querySelectorAll<HTMLElement>("[data-reveal-item]").forEach((item, i) => item.style.setProperty("--i", String(Math.min(i, STAGGER_CAP))));+ el.dataset.reveal = "wait";+ pending.set(+ el,+ onceVisible(el, () => {+ pending.delete(el);+ el.dataset.reveal = "in";+ }),+ );+ }),+ );+ }+ if (!pending.size) return () => {};++ /** Shows `el` now, with no transition (it stays "now": the section is simply there). */+ const showNow = (el: HTMLElement) => {+ pending.get(el)?.();+ pending.delete(el);+ el.dataset.reveal = "now";+ };+ const revealTo = (t: Element | string | null | undefined) => {+ const target = targetOf(t);+ if (!target) return;+ for (const el of [...pending.keys()]) {+ // The section holds the target, or comes before it in the page.+ if (el.contains(target) || target.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_PRECEDING) showNow(el);+ }+ };+ const onClick = (e: MouseEvent) => {+ const a = (e.target as Element | null)?.closest?.("a[href]");+ if (!a) return;+ const href = a.getAttribute("href") ?? "";+ if (href.startsWith("#")) return revealTo(href);+ try {+ const url = new URL(href, location.href);+ if (url.hash && url.pathname === location.pathname && url.search === location.search) revealTo(url.hash);+ } catch {+ // Not a URL: nothing to show.+ }+ };+ const onHash = () => revealTo(location.hash);+ const onEvent = (e: Event) => revealTo((e as CustomEvent<{ target?: Element | string }>).detail?.target);+ // Find in page opens a hidden=until-found part first: whatever section holds it shows.+ const onMatch = (e: Event) => revealTo(e.target as Element);+ document.addEventListener("click", onClick, true);+ document.addEventListener(REVEAL_EVENT, onEvent);+ document.addEventListener("beforematch", onMatch, true);+ window.addEventListener("hashchange", onHash);+ const safety = window.setTimeout(() => {+ if (!observersAlive) for (const el of [...pending.keys()]) showNow(el);+ }, REVEAL_SAFETY);++ return () => {+ window.clearTimeout(safety);+ document.removeEventListener("click", onClick, true);+ document.removeEventListener(REVEAL_EVENT, onEvent);+ document.removeEventListener("beforematch", onMatch, true);+ window.removeEventListener("hashchange", onHash);+ for (const [el, stop] of pending) {+ stop();+ el.dataset.reveal = "in";+ }+ pending.clear();+ };+}++// ---------------------------------------------------------------------------------------------------------------+// Pictures that arrive after the first paint fade in when they load.++/**+ * Whether a picture should wait hidden and fade in: not loaded yet, not the page's main picture, not styled by its own+ * code, not inside something with its own motion (a result settling into its tile, its next steps following it, a+ * request rising in).+ */+export function fadesIn(img: HTMLImageElement): boolean {+ if (img.complete || img.dataset.fade !== undefined || img.dataset.noFade !== undefined) return false;+ if (img.getAttribute("fetchpriority") === "high") return false;+ // A picture whose own code fades or hides it (an inline opacity, an opacity class) keeps doing so.+ if (img.style.opacity || /(^|\s)(opacity-|transition-opacity)/.test(img.className)) return false;+ if (img.closest?.("[data-arrive], [data-follow], [data-enter], [data-own-motion]")) return false;+ return !!img.getAttribute("src") || !!img.getAttribute("srcset");+}++/**+ * Holds `img` hidden until it loads, then fades it in (CSS: img[data-fade]). An error shows the frame under it.+ * offScreenOnly: only when it is off screen now (asked of the browser's next intersection pass, never a layout read),+ * for a page's first screen, which shows as it loads.+ */+export function fadeInOnLoad(img: HTMLImageElement, { offScreenOnly = false }: { offScreenOnly?: boolean } = {}): void {+ if (!fadesIn(img)) return;+ if (offScreenOnly) {+ firstSight(img, (where) => where !== "on" && fadeInOnLoad(img));+ return;+ }+ const show = () => {+ img.removeEventListener("load", show);+ img.removeEventListener("error", fail);+ img.dataset.fade = "in";+ };+ const fail = () => {+ img.removeEventListener("load", show);+ img.removeEventListener("error", fail);+ delete img.dataset.fade;+ };+ img.addEventListener("load", show);+ img.addEventListener("error", fail);+ // It may have finished between the check and the listeners: then it simply shows.+ if (img.complete) return fail();+ img.dataset.fade = "wait";+}diff --git a/tests/__snapshots__/home-studios.html b/tests/__snapshots__/home-studios.htmlindex 6c5f6850..c6aa5d56 100644--- a/tests/__snapshots__/home-studios.html+++ b/tests/__snapshots__/home-studios.html@@ -1,7 +1,9 @@<section aria-labelledby="home-studios" class="home-cv -mx-4 mt-8 -mb-2 px-4 py-2 sm:mt-12 [--cv:529px] sm:[--cv:1597px] md:[--cv:1482px] lg:[--cv:770px] xl:[--cv:795px]"><div class="mb-4"><div class="flex items-center justify-between gap-4">-<h2 id="home-studios" class="font-heading text-[24px] leading-tight sm:text-[28px]">Studios and tools<span aria-hidden="true" class="ml-2 inline-block rounded-full bg-muted px-2 align-[0.3em] font-sans text-[13px] leading-6 tracking-normal text-muted-foreground tabular-nums">40</span>+<h2 id="home-studios" class="font-heading text-[24px] leading-tight sm:text-[28px]">Studios and tools<span aria-hidden="true" class="ml-2 inline-block rounded-full bg-muted px-2 align-[0.3em] font-sans text-[13px] leading-6 tracking-normal text-muted-foreground tabular-nums">+<span style="display:inline-block;min-width:2ch;font-variant-numeric:tabular-nums">40</span>+</span></h2><a aria-label="See all 29 studios" class="group relative inline-flex shrink-0 items-center gap-1 text-[13px] text-muted-foreground transition-colors after:absolute after:-inset-x-2 after:-inset-y-3 after:content-[''] hover:text-foreground" href="/studios">See all 29 studios <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-arrow-right size-3.5 transition-transform duration-150 group-hover:translate-x-0.5" aria-hidden="true"><path d="M5 12h14">diff --git a/tests/e2e/motion.mjs b/tests/e2e/motion.mjsnew file mode 100644index 00000000..f25a8348--- /dev/null+++ b/tests/e2e/motion.mjs@@ -0,0 +1,413 @@+// The site's motion (src/app/motion.css, src/components/page-motion.tsx): it runs where it should, on the tokens, and+// is instant under reduced motion. The app must be running, a production build with placeholder results on+// (`FUOBE_DEMO_MODE=on pnpm start`). Usage: node tests/e2e/motion.mjs [appUrl] [--only=<text>] [--engine=webkit|firefox].+// Exits 1 on a failure.+//+// At 1440 and 390, each with and without prefers-reduced-motion:+// 1. A page link (bar or tabs) fades the new page in: #content[data-page-in] from its first frame, the animation on+// the tokens, the old page never shown again, and the new page's text there within two frames. Back is instant.+// 2. Menus (desktop) open in 200 ms and close in 120 ms; the phone's sheets slide in (320 ms, no fade) and out (200 ms).+// 3. A card under the pointer (desktop) lifts 2 px, its shadow shows and its cover zooms; a press gives a little.+// 4. Pictures further down Home wait hidden and fade in as they load.+// 5. A result that finishes while the studio is open settles in (data-arrive), and only then; the feed doesn't shift.+// Reduced motion: none of the above moves (no page-in, no marks, durations ≈ 0, no lift).+// Layout shift on Home's load and scroll, and on a route change, stays at the audit's numbers or under; menu, card and+// sheet interactions add no long tasks.+import { DESKTOP, launch, loadPlaywright, PHONE } from "./_browser.mjs";++const app = (process.argv.slice(2).find((a) => !a.startsWith("--")) ?? "http://localhost:3000").replace(/\/$/, "");+const only = process.argv.find((a) => a.startsWith("--only="))?.slice(7);+// --engine=webkit runs the same checks in Safari's engine (layout shift and long tasks are Chromium-only reports there).+const engine = process.argv.find((a) => a.startsWith("--engine="))?.slice(9) ?? "chromium";+const browser = engine === "chromium" ? await launch() : await loadPlaywright()[engine].launch();+if (engine !== "chromium") console.log(`engine: ${engine} (layout shift and long tasks are not reported by this engine)`);+const failures = [];+const check = (ok, msg) => {+ console.log(` ${ok ? "ok " : "FAIL"} ${msg}`);+ if (!ok) failures.push(msg);+};+const near = (a, b, tol = 2) => Math.abs(a - b) <= tol;+/** Long-task time per interaction, compared at the end with the same run under reduce: motion adds none (80 ms of slack for one stray task, a GC or a chunk, which shows in either). */+const longs = [];+/** Home's load + scroll layout shift, with and without motion (motion may add none). */+const homeShift = {};++/** Before the page's scripts: layout shifts, long tasks, and every animation that starts (name, duration, target). */+const PROBE = () => {+ const w = window;+ w.__m = { shifts: [], longs: [], anims: [] };+ try {+ new PerformanceObserver((l) => l.getEntries().forEach((e) => !e.hadRecentInput && w.__m.shifts.push({ v: e.value, t: e.startTime }))).observe({ type: "layout-shift", buffered: true });+ new PerformanceObserver((l) => l.getEntries().forEach((e) => w.__m.longs.push({ d: e.duration, t: e.startTime }))).observe({ type: "longtask", buffered: true });+ } catch {}+ const seen = new WeakSet();+ const scan = () => {+ for (const a of document.getAnimations()) {+ if (seen.has(a)) continue;+ seen.add(a);+ const el = a.effect?.target;+ const t = a.effect?.getTiming?.() ?? {};+ w.__m.anims.push({+ name: a.animationName ?? (a.transitionProperty ? "transition:" + a.transitionProperty : "waapi"),+ dur: typeof t.duration === "number" ? t.duration : 0,+ delay: t.delay ?? 0,+ slot: el?.getAttribute?.("data-slot") ?? "",+ id: el?.id ?? "",+ inContent: !!el?.closest?.("#content"),+ t: performance.now(),+ });+ }+ };+ const loop = () => {+ try {+ scan();+ } catch {}+ requestAnimationFrame(loop);+ };+ requestAnimationFrame(loop);+ // Marks set by the page's motion code, as they happen.+ w.__marks = [];+ new MutationObserver((rs) => {+ for (const r of rs) if (r.type === "attributes" && r.target.hasAttribute(r.attributeName)) w.__marks.push({ attr: r.attributeName, value: r.target.getAttribute(r.attributeName), gen: (r.target.closest?.("[data-gen-id]") ?? r.target.querySelector?.("[data-gen-id]"))?.getAttribute("data-gen-id") ?? null, el: r.target.tagName + (r.target.closest?.("[data-arrive]") ? " in tile" : ""), t: performance.now() });+ }).observe(document, { subtree: true, attributes: true, attributeFilter: ["data-page-in", "data-arrive", "data-follow", "data-enter", "data-fade", "data-reveal", "data-motion-reveal"] });+};++const since = (page, t0) =>+ page.evaluate((t0) => {+ const m = window.__m;+ return {+ shifts: m.shifts.filter((s) => s.t >= t0).reduce((s, x) => s + x.v, 0),+ longs: m.longs.filter((l) => l.t >= t0),+ anims: m.anims.filter((a) => a.t >= t0),+ marks: window.__marks.filter((k) => k.t >= t0),+ };+ }, t0);+const now = (page) => page.evaluate(() => performance.now());+/** Records, each frame for 700 ms, the pinned (sticky or fixed) bar at the top-left of the screen: its y and its opacity. */+const TRACK_TOP = () => {+ const w = window;+ w.__top = [];+ const t0 = performance.now();+ const loop = (t) => {+ let el = document.elementFromPoint(30, 20);+ let bar = null;+ for (let n = el; n && n !== document.body; n = n.parentElement) {+ const p = getComputedStyle(n).position;+ if (p === "sticky" || p === "fixed") bar = n;+ }+ if (bar && bar.closest("#content")) {+ let op = 1;+ for (let n = bar; n && n !== document.body; n = n.parentElement) op *= +getComputedStyle(n).opacity;+ w.__top.push({ pinned: true, y: Math.round(bar.getBoundingClientRect().y * 10) / 10, op: Math.round(op * 100) / 100 });+ } else w.__top.push({ pinned: false });+ if (t - t0 < 700) requestAnimationFrame(loop);+ };+ requestAnimationFrame(loop);+};++async function context({ phone, reduce }) {+ const ctx = await browser.newContext({ ...(phone ? PHONE : DESKTOP), reducedMotion: reduce ? "reduce" : "no-preference" });+ await ctx.addInitScript(PROBE);+ const page = await ctx.newPage();+ return { ctx, page };+}++async function settle(page, url) {+ await page.goto(app + url, { waitUntil: "load", timeout: 90_000 });+ await page.locator("h1").first().waitFor({ timeout: 20_000 }).catch(() => {});+ await page.waitForTimeout(1200);+}++// A first visit warms the server's caches, so the first measured run isn't the cold one.+{+ const warm = await browser.newContext(DESKTOP);+ const p = await warm.newPage();+ for (const url of ["/", "/apps", "/library", "/effects", "/image"]) await p.goto(app + url, { waitUntil: "load", timeout: 90_000 }).catch(() => {});+ await warm.close();+}++for (const phone of [false, true]) {+ for (const reduce of [false, true]) {+ const tag = `${phone ? 390 : 1440}${reduce ? " reduce" : ""}`;+ if (only && !tag.includes(only) && !["route", "menu", "sheet", "card", "image", "result"].some((s) => only.includes(s))) continue;+ console.log(`\n# ${tag}`);+ const { ctx, page } = await context({ phone, reduce });+ const nav = () => page.getByRole("navigation", { name: "Main" });++ // Home: layout shift on load and while scrolling (reveals and fades must add none).+ await settle(page, "/");+ {+ const t0 = 0;+ for (let i = 0; i < 12; i++) {+ // Mobile WebKit has no wheel: scroll the page by script there (the reveals see the same scroll).+ if (phone && engine === "webkit") await page.evaluate(() => window.scrollBy(0, 600));+ else await page.mouse.wheel(0, 600);+ await page.waitForTimeout(150);+ }+ await page.waitForTimeout(800);+ const r = await since(page, t0);+ homeShift[tag] = r.shifts;+ const base = 0.03; // the audit's Home load at a92342c1: 0.022 at 1440 (the "What Fuobe makes" section, not motion)+ check(r.shifts <= base, `Home load + scroll layout shift ${r.shifts.toFixed(4)} ≤ ${base}`);+ const fades = r.marks.filter((k) => k.attr === "data-fade");+ const reveals = r.marks.filter((k) => k.attr === "data-reveal");+ if (reduce) check(fades.length === 0 && reveals.length === 0, `no picture fades or section reveals (${fades.length}, ${reveals.length})`);+ else {+ check(fades.some((k) => k.value === "wait") && fades.some((k) => k.value === "in"), `pictures further down wait, then fade in (${fades.length} marks)`);+ check(reveals.some((k) => k.value === "in"), `sections below the first screen reveal on scroll (${reveals.length} marks)`);+ }+ const firstScreen = await page.evaluate(() => [...document.querySelectorAll("[data-reveal=wait]")].filter((el) => el.getBoundingClientRect().bottom < 0).length);+ check(firstScreen === 0, "no section above the screen is left hidden");+ }++ // 1. A page link fades the new page in; Back is instant.+ if (!only || only.includes("route")) {+ await settle(page, "/");+ const link = phone ? nav().getByRole("link", { name: "Library" }) : nav().getByRole("link", { name: "Apps", exact: true });+ // The pinned bar at the top of a phone's page (the app bar) stays put and opaque through the change.+ if (phone) await page.evaluate(TRACK_TOP);+ const t0 = await now(page);+ const click = Date.now();+ await link.click();+ await page.waitForURL(phone ? /\/library/ : /\/apps/, { timeout: 15_000 });+ const urlMs = Date.now() - click;+ await page.waitForTimeout(900);+ const r = await since(page, t0);+ const pageIn = r.marks.filter((k) => k.attr === "data-page-in");+ const fades = r.anims.filter((a) => a.inContent && a.name === "motion-fade");+ if (reduce) {+ check(pageIn.length === 0 && fades.length === 0, `route: no page motion (${pageIn.length} marks, ${fades.length} fades)`);+ } else {+ check(pageIn.length === 1, `route: #content marked as arriving (${pageIn.length})`);+ const rise = r.anims.find((a) => a.inContent && a.name === "motion-rise-page");+ check(fades.length > 0 && near(fades[0].dur, 239, 3), `route: new page fades in on the tokens (${fades[0]?.dur} ms)`);+ check(!!rise && near(rise.dur, 320), `route: and settles 8 px over 320 ms (${rise?.dur} ms)`);+ const left = await page.evaluate(() => document.getElementById("content").hasAttribute("data-page-in"));+ check(!left, "route: the mark is gone once the page has arrived");+ }+ check(r.shifts <= 0.01, `route: layout shift ${r.shifts.toFixed(4)}`);+ if (phone) {+ const top = await page.evaluate(() => window.__top);+ const moved = top.filter((x) => x.pinned && (Math.abs(x.y) > 0.5 || x.op < 0.99));+ check(top.some((x) => x.pinned) && moved.length === 0, `route: the phone's pinned top bar stays at y 0, opacity 1 (${moved.length} of ${top.length} frames off${moved[0] ? `: y ${moved[0].y}, opacity ${moved[0].op}` : ""})`);+ }+ console.log(` info click → URL ${urlMs} ms`);+ longs.push({ tag, what: "route", ms: r.longs.reduce((s, l) => s + l.d, 0) });+ const t1 = await now(page);+ await page.goBack();+ await page.waitForTimeout(700);+ const back = await since(page, t1);+ check(back.marks.filter((k) => k.attr === "data-page-in").length === 0, "Back: instant (no page motion)");+ }++ // 1b. A tab in the page's own tab row changes the page in place, even across segments (Marketing → Ads).+ if (!only || only.includes("route")) {+ await settle(page, "/marketing");+ const tab = page.getByRole("navigation", { name: "Marketing tools" }).getByRole("link", { name: "Ads Studio" });+ if (await tab.count()) {+ const t0 = await now(page);+ await tab.click();+ await page.waitForURL(/\/ads/,{ timeout: 15_000 });+ await page.waitForTimeout(700);+ const r = await since(page, t0);+ check(r.marks.filter((k) => k.attr === "data-page-in").length === 0, "tab row: /marketing → /ads changes in place (no page motion)");+ } else check(false, "tab row: the Marketing tools row has an Ads Studio tab");+ }++ // 1c. A jump to a section lands on it shown (no section waiting to reveal at or above it).+ if (!only || only.includes("route")) {+ await settle(page, "/studios");+ const target = await page.evaluate(() => {+ const secs = [...document.querySelectorAll("#content [data-reveal][id]")];+ return secs.at(-1)?.id ?? null;+ });+ if (target) {+ await page.evaluate((id) => {+ const a = document.createElement("a");+ a.href = "#" + id;+ a.textContent = "jump";+ document.getElementById("content").prepend(a);+ a.click();+ }, target);+ await page.waitForTimeout(120);+ const hidden = await page.evaluate((id) => {+ const t = document.getElementById(id);+ return [...document.querySelectorAll("#content [data-reveal]")].filter((s) => (s === t || s.compareDocumentPosition(t) & Node.DOCUMENT_POSITION_FOLLOWING) && getComputedStyle(s).opacity !== "1").map((s) => s.id || s.tagName);+ }, target);+ check(hidden.length === 0, `section jump: #${target} and the sections above it are shown at once (${hidden.join(", ") || "none hidden"})`);+ }+ }++ // 2. Menus (desktop) and sheets (phone).+ if (!only || only.includes("menu") || only.includes("sheet")) {+ await settle(page, "/");+ if (!phone) {+ const btn = page.getByRole("button", { name: "Create menu" }).first();+ let t0 = await now(page);+ await btn.click();+ await page.waitForTimeout(400);+ let r = await since(page, t0);+ const open = r.anims.find((a) => a.slot === "dropdown-menu-content" && a.name === "enter");+ check(reduce ? !open || open.dur < 1 : !!open && near(open.dur, 200), open ? `menu opens in ${open.dur} ms` : "menu opens at once (no animation)");+ longs.push({ tag, what: "menu open", ms: r.longs.reduce((s, l) => s + l.d, 0) });+ t0 = await now(page);+ await page.keyboard.press("Escape");+ await page.waitForTimeout(400);+ r = await since(page, t0);+ const close = r.anims.find((a) => a.slot === "dropdown-menu-content" && a.name === "exit");+ check(!close || (reduce ? close.dur < 1 : near(close.dur, 120)), `menu closes in ${close?.dur ?? "no"} ms`);+ // A menu opened by resting on it stays open when its chevron is then clicked (the click pins it).+ await page.mouse.move(5, 500);+ await page.waitForTimeout(300);+ await btn.hover();+ await page.waitForTimeout(700);+ const byHover = await page.locator('[data-slot="dropdown-menu-content"]').count();+ if (byHover) {+ await btn.click();+ await page.waitForTimeout(400);+ check((await page.locator('[data-slot="dropdown-menu-content"][data-state="open"]').count()) > 0, "menu: opened by hover, a click on its chevron keeps it open");+ await page.keyboard.press("Escape");+ await page.waitForTimeout(300);+ } else console.log(" skip hover-then-click: this menu doesn't open on hover");+ await page.mouse.move(5, 500);+ // The Studios launcher goes at once when it closes (a grouped menu that replaces it never overlaps it).+ const studios = page.getByRole("button", { name: "Studios menu" }).first();+ await studios.click();+ await page.waitForTimeout(400);+ t0 = await now(page);+ await page.keyboard.press("Escape");+ await page.waitForTimeout(400);+ r = await since(page, t0);+ const fadeOut = r.anims.some((a) => a.id === "studios-launcher" && a.name.startsWith("transition:opacity"));+ check(!fadeOut, `launcher closes at once (faded: ${fadeOut})`);+ check(await page.locator("#studios-launcher").isHidden(), "launcher is gone after it closes");+ } else {+ for (const s of ["Create", "You"]) {+ let t0 = await now(page);+ await nav().getByRole("button", { name: s, exact: true }).click();+ await page.waitForTimeout(500);+ let r = await since(page, t0);+ const open = r.anims.find((a) => a.id === "phone-sheet" && a.name === "enter");+ check(reduce ? !open || open.dur < 1 : !!open && near(open.dur, 320), open ? `${s} sheet slides in over ${open.dur} ms` : `${s} sheet opens at once (no animation)`);+ const opacity = await page.locator("#phone-sheet").evaluate((el) => getComputedStyle(el).getPropertyValue("--tw-enter-opacity").trim());+ check(opacity === "1", `${s} sheet: a solid surface (no fade: --tw-enter-opacity ${opacity})`);+ longs.push({ tag, what: `${s} sheet open`, ms: r.longs.reduce((s, l) => s + l.d, 0) });+ t0 = await now(page);+ await page.keyboard.press("Escape");+ await page.waitForTimeout(500);+ r = await since(page, t0);+ const close = r.anims.find((a) => a.id === "phone-sheet" && a.name === "exit");+ check(!close || (reduce ? close.dur < 1 : near(close.dur, 200)), `${s} sheet slides out over ${close?.dur ?? "no"} ms`);+ check(await page.evaluate(() => document.activeElement && document.activeElement !== document.body), `${s} sheet: focus comes back`);+ }+ }+ }++ // 3. Cards (pointer devices only).+ if (!phone && (!only || only.includes("card"))) {+ await settle(page, "/effects");+ const card = page.locator("main a.card-motion").first();+ // The grid may re-render once after hydration: try again if the card was replaced under us.+ for (let i = 0; i < 3; i++) {+ try {+ await card.scrollIntoViewIfNeeded({ timeout: 5_000 });+ break;+ } catch {+ await page.waitForTimeout(500);+ }+ }+ const t0 = await now(page);+ await card.hover();+ await page.waitForTimeout(450);+ const s = await card.evaluate((el) => ({+ translate: getComputedStyle(el).translate,+ shadow: getComputedStyle(el, "::after").opacity,+ zoom: getComputedStyle(el.querySelector(".card-cover > :first-child")).scale,+ }));+ if (reduce) check(s.translate === "none" || s.translate === "0px" || s.translate === "0px 0px", `card: no lift (${s.translate})`);+ else {+ check(s.translate === "0px -2px", `card lifts 2 px (${s.translate})`);+ check(s.shadow === "1", `card: its shadow shows (${s.shadow})`);+ check(s.zoom === "1.03", `card: its cover leans in (${s.zoom})`);+ }+ const box = await card.boundingBox();+ await page.mouse.move(box.x + 30, box.y + 30);+ await page.mouse.down();+ // Wait for the press to settle (an engine may start its transition a frame later), at most 600 ms.+ await card.evaluate((el) => new Promise((done) => {+ const t0 = performance.now();+ const tick = () => (getComputedStyle(el).scale === "0.985" || performance.now() - t0 > 600 ? done() : requestAnimationFrame(tick));+ tick();+ }));+ const pressed = await card.evaluate((el) => getComputedStyle(el).scale);+ check(reduce ? pressed === "1" || pressed === "none" : pressed === "0.985", `card press gives a little (${pressed})`);+ await page.mouse.move(box.x - 40, box.y - 40);+ await page.mouse.up();+ const r = await since(page, t0);+ longs.push({ tag, what: "card hover and press", ms: r.longs.reduce((s, l) => s + l.d, 0) });+ const props = [...new Set(r.anims.filter((a) => a.name.startsWith("transition:")).map((a) => a.name.slice(11)))];+ check(props.every((p) => ["translate", "scale", "opacity", "background-color", "color", "box-shadow", "border-color", "outline-color"].includes(p)), `card: only compositor properties move (${props.join(", ")})`);+ }++ // 5. A result that finishes while the studio is open.+ if (!only || only.includes("result")) {+ await settle(page, "/image");+ const prompt = page.locator("main textarea").first();+ if (await prompt.count()) {+ await prompt.fill("Editorial portrait, soft window light");+ const t0 = await now(page);+ const before = await page.locator("main [data-gen-id]").first().getAttribute("data-gen-id").catch(() => null);+ await page.locator("main button[aria-label^='Generate']").first().click();+ // The new request rises in at the top; then its placeholder result arrives.+ await page+ .waitForFunction(+ (before) => {+ const top = document.querySelector("main [data-gen-id]");+ return top && top.getAttribute("data-gen-id") !== before && top.querySelector("[class*='group/tile']");+ },+ before,+ { timeout: 45_000 },+ )+ .catch(() => {});+ await page.waitForTimeout(1200);+ const r = await since(page, t0);+ const arrive = r.marks.filter((k) => k.attr === "data-arrive");+ const enter = r.marks.filter((k) => k.attr === "data-enter");+ if (reduce) check(arrive.length === 0 && enter.length === 0, `result: appears still (${arrive.length}, ${enter.length})`);+ else {+ check(enter.length >= 1, `result: the new request rises in (${enter.length})`);+ check(arrive.length >= 1, `result: the picture settles in (${arrive.length})`);+ const sweep = r.anims.find((a) => a.name === "motion-sweep");+ check(!!sweep && near(sweep.dur, 500), `result: one light passes over it (${sweep?.dur} ms)`);+ // Only the picture settles into its tile: the tile's frame never fades, and the picture has no load fade too.+ const arrived = new Set(arrive.map((k) => k.gen).filter(Boolean));+ const stacked = r.marks.filter((k) => (k.attr === "data-motion-reveal" || k.attr === "data-fade") && arrived.has(k.gen));+ check(stacked.length === 0, `result: one motion on the tile (no skeleton hand-over or load fade inside it: ${stacked.length}${stacked.length ? ": " + stacked.map((k) => `${k.attr}=${k.value} ${k.el}`).join(", ") : ""})`);+ }+ const base = phone ? 0.049 : 0.024;+ check(r.shifts <= base, `result: layout shift ${r.shifts.toFixed(4)} ≤ the audit's ${base}`);+ // A reload shows the same feed still.+ const t1 = await now(page);+ await page.reload({ waitUntil: "load" });+ await page.waitForTimeout(1500);+ const again = await page.evaluate(() => window.__marks.filter((k) => k.attr === "data-arrive" || k.attr === "data-enter").length);+ check(again === 0, `result: a reload doesn't replay it (${again}, from ${Math.round(t1)})`);+ } else console.log(" skip result: no prompt on /image");+ }+ await ctx.close();+ }+}++await browser.close();+console.log("\n# against reduced motion (the same run with motion off)");+for (const w of [1440, 390]) {+ const a = homeShift[`${w}`], b = homeShift[`${w} reduce`];+ if (a !== undefined && b !== undefined) check(a <= b + 0.005, `${w}: Home layout shift with motion ${a.toFixed(4)} vs without ${b.toFixed(4)}`);+ for (const what of [...new Set(longs.filter((l) => l.tag === `${w}`).map((l) => l.what))]) {+ const on = longs.find((l) => l.tag === `${w}` && l.what === what)?.ms ?? 0;+ const off = longs.find((l) => l.tag === `${w} reduce` && l.what === what)?.ms ?? 0;+ check(on <= off + 80, `${w} ${what}: long tasks with motion ${Math.round(on)} ms vs without ${Math.round(off)} ms`);+ }+}+console.log(failures.length ? `\n${failures.length} failure(s)` : "\nall motion checks pass");+process.exit(failures.length ? 1 : 0);diff --git a/tests/ui-motion.test.ts b/tests/ui-motion.test.tsnew file mode 100644index 00000000..88277975--- /dev/null+++ b/tests/ui-motion.test.ts@@ -0,0 +1,219 @@+import fs from "node:fs";+import path from "node:path";+import { afterEach, describe, expect, it, vi } from "vitest";+import { countAt, countFrom, counts, countUp, EASE, easeOutQuart, fadeInOnLoad, fadesIn, ms, MOTION, newPlace, stagger, STAGGER_CAP } from "@/lib/ui-motion";++const root = path.resolve(__dirname, "..");+const read = (p: string) => fs.readFileSync(path.join(root, p), "utf8");+const css = read("src/app/motion.css");++/** The custom properties set in the first block that matches `selector` (inside `within`, when given). */+function block(source: string, selector: string): Record<string, string> {+ const at = source.indexOf(selector);+ expect(at, `${selector} in motion.css`).toBeGreaterThanOrEqual(0);+ const body = source.slice(source.indexOf("{", at) + 1, source.indexOf("}", at));+ return Object.fromEntries([...body.matchAll(/(--[\w-]+):\s*([^;]+);/g)].map((m) => [m[1], m[2].trim()]));+}+const reduceAt = css.indexOf("@media (prefers-reduced-motion: reduce)");+const tokens = block(css, ":root {");+const reduced = block(css.slice(reduceAt), ":root {");++describe("motion tokens", () => {+ it("CSS and TS hold the same durations", () => {+ for (const [k, v] of Object.entries(MOTION)) {+ const name = k === "stagger" ? "--motion-stagger" : `--motion-${k}`;+ expect(tokens[name], name).toBe(`${v}ms`);+ }+ });++ it("CSS and TS hold the same easings", () => {+ const globals = read("src/app/globals.css");+ expect(globals).toContain(`--ease-enter: ${EASE.enter};`);+ expect(globals).toContain(`--ease-exit: ${EASE.exit};`);+ expect(css).toContain(`--ease-standard: ${EASE.standard};`);+ expect(css).toContain(`--ease-emphasised: ${EASE.emphasised};`);+ });++ it("small distances, no overshoot, presses that give a little", () => {+ expect(tokens["--motion-d1"]).toBe("4px");+ expect(tokens["--motion-d2"]).toBe("8px");+ expect(tokens["--motion-d3"]).toBe("16px");+ expect(Number(tokens["--motion-zoom"])).toBeLessThanOrEqual(1.03);+ for (const k of ["--motion-press", "--motion-press-card", "--motion-scale-in", "--motion-scale-out"]) expect(Number(tokens[k])).toBeGreaterThanOrEqual(0.97);+ // Every cubic-bezier stays inside 0..1 on y: nothing overshoots and springs back.+ for (const m of css.matchAll(/cubic-bezier\(([^)]+)\)/g)) {+ const [, y1, , y2] = m[1].split(",").map(Number);+ expect(y1).toBeGreaterThanOrEqual(0);+ expect(y1).toBeLessThanOrEqual(1);+ expect(y2).toBeLessThanOrEqual(1);+ }+ });++ it("reduced motion turns every duration, distance and scale off", () => {+ for (const k of ["--motion-fast", "--motion-base", "--motion-slow", "--motion-page", "--motion-count", "--motion-stagger"]) expect(reduced[k], k).toBe("0ms");+ for (const k of ["--motion-d1", "--motion-d2", "--motion-d3", "--motion-lift"]) expect(reduced[k], k).toBe("0px");+ for (const k of ["--motion-scale-in", "--motion-scale-out", "--motion-press", "--motion-press-card", "--motion-zoom"]) expect(reduced[k], k).toBe("1");+ // The safety net: animations and transitions that don't use the tokens end at once.+ const net = css.slice(reduceAt, css.indexOf("/* ----- Menus", reduceAt));+ expect(net).toMatch(/animation-duration: 0s !important/);+ expect(net).toMatch(/transition-duration: 0s !important/);+ expect(net).toMatch(/animation-iteration-count: 1 !important/);+ });++ it("motion.css moves only transform, translate, scale and opacity", () => {+ const keyframes = [...css.matchAll(/@keyframes [\w-]+ \{(.+)\}/g)].map((m) => m[1]);+ expect(keyframes.length).toBeGreaterThan(4);+ for (const k of keyframes) for (const p of k.matchAll(/([a-z-]+):/g)) expect(["opacity", "translate", "scale", "transform"]).toContain(p[1]);+ for (const t of css.matchAll(/transition:\s*([^;]+);/g)) {+ for (const part of t[1].split(",")) {+ const prop = part.trim().split(/\s+/)[0];+ // Sonner's own stack height and its focus shadow are kept from the library; background colour is a colour; none ends one at once.+ expect(["none", "opacity", "translate", "scale", "transform", "display", "height", "box-shadow", "background-color"]).toContain(prop);+ }+ }+ });++ it("is imported by globals.css, and the older keyframes use the tokens", () => {+ const globals = read("src/app/globals.css");+ expect(globals).toMatch(/@import "\.\/motion\.css";/);+ expect(globals).toContain("--animate-fade-up: fade-up var(--motion-base)");+ expect(globals).toContain("--animate-pop-in: pop-in var(--motion-fast)");+ });++ it("covers every overlay primitive by its slot", () => {+ for (const slot of ["dropdown-menu-content", "popover-content", "select-content", "context-menu-content", "hover-card-content", "tooltip-content", "dialog-overlay", "dialog-content", "alert-dialog-content", "sheet-content", "sheet-overlay"]) {+ expect(css, slot).toContain(`[data-slot="${slot}"]`);+ }+ for (const f of ["dialog", "alert-dialog", "sheet", "dropdown-menu", "popover", "tooltip"]) {+ expect(read(`src/components/ui/${f}.tsx`)).toMatch(/data-slot="[a-z-]+(content|overlay)"/);+ }+ expect(read("src/components/nav/search-palette.tsx")).toContain('data-slot="search-palette"');+ expect(read("src/components/nav/search-palette.tsx")).toContain('data-slot="search-palette-overlay"');+ });++ it("the components use the tokens, not their own numbers", () => {+ expect(read("src/components/ui/button.tsx")).toContain("active:not-aria-[haspopup]:scale-(--motion-press)");+ expect(read("src/components/preset-gallery.tsx")).toMatch(/card-motion/);+ expect(read("src/components/studio/feed.tsx")).toMatch(/useArrival/);+ expect(read("src/components/nav/studio-chrome.tsx")).toMatch(/<PageMotion \/>/);+ // Progress bars grow with transform, never by animating their width.+ const files = fs.readdirSync(path.join(root, "src/components"), { recursive: true }) as string[];+ const widthTransitions = files.filter((f) => f.endsWith(".tsx") && read(path.join("src/components", f)).includes("transition-[width]"));+ expect(widthTransitions).toEqual([]);+ });+});++describe("motion helper", () => {+ afterEach(() => vi.unstubAllGlobals());++ it("ms and stagger are 0 under reduced motion", () => {+ expect(ms("base", false)).toBe(200);+ expect(ms("base", true)).toBe(0);+ expect(stagger(3, 40, STAGGER_CAP, false)).toBe(120);+ expect(stagger(3, 40, STAGGER_CAP, true)).toBe(0);+ });++ it("stagger caps at six steps", () => {+ expect(stagger(0, 40, 6, false)).toBe(0);+ expect(stagger(6, 40, 6, false)).toBe(240);+ expect(stagger(40, 40, 6, false)).toBe(240);+ expect(stagger(2, 30, 6, false)).toBe(60);+ });++ it("counts up from about 70 % with an ease-out, ending exactly on the value", () => {+ expect(counts(9)).toBe(false);+ expect(counts(10)).toBe(true);+ expect(counts(12.5)).toBe(false);+ expect(countFrom(255)).toBe(179);+ expect(countAt(255, 0)).toBe(179);+ expect(countAt(255, MOTION.count)).toBe(255);+ expect(countAt(255, 99_999)).toBe(255);+ expect(countAt(255, MOTION.count / 2)).toBeGreaterThan(Math.round((179 + 255) / 2));+ // No crawl at the end: within 1 of the value by 70 % of the time.+ expect(255 - countAt(255, MOTION.count * 0.7)).toBeLessThanOrEqual(1);+ expect(easeOutQuart(0)).toBe(0);+ expect(easeOutQuart(1)).toBe(1);+ let last = 0;+ for (let t = 0; t <= MOTION.count; t += 35) {+ const v = countAt(108, t);+ expect(v).toBeGreaterThanOrEqual(last);+ last = v;+ }+ });++ it("countUp writes the final value at once under reduced motion or for a small number", () => {+ const el = { textContent: "" } as HTMLElement;+ countUp(el, 255, { reduce: true });+ expect(el.textContent).toBe("255");+ const small = { textContent: "" } as HTMLElement;+ countUp(small, 7, { reduce: false });+ expect(small.textContent).toBe("7");+ });++ it("countUp starts lower and lands on the value; cancel shows the value", () => {+ const frames: FrameRequestCallback[] = [];+ vi.stubGlobal("requestAnimationFrame", (cb: FrameRequestCallback) => frames.push(cb));+ vi.stubGlobal("cancelAnimationFrame", () => {});+ const el = { textContent: "" } as HTMLElement;+ const stop = countUp(el, 127, { reduce: false });+ expect(el.textContent).toBe("89");+ frames.shift()!(performance.now() + MOTION.count + 1);+ expect(el.textContent).toBe("127");+ const el2 = { textContent: "" } as HTMLElement;+ const stop2 = countUp(el2, 40, { reduce: false });+ stop2();+ expect(el2.textContent).toBe("40");+ stop();+ });++ it("a new place is another first path segment, not a hub's tab or a page's section", () => {+ expect(newPlace(null, "/apps")).toBe(false);+ expect(newPlace("/", "/apps")).toBe(true);+ expect(newPlace("/effects", "/video")).toBe(true);+ expect(newPlace("/audio", "/audio/music")).toBe(false);+ expect(newPlace("/audio/music", "/audio/sfx")).toBe(false);+ expect(newPlace("/library", "/library?tab=videos")).toBe(false);+ expect(newPlace("/apps", "/apps")).toBe(false);+ expect(newPlace("/settings/runs", "/settings")).toBe(false);+ expect(newPlace("/image", "/")).toBe(true);+ // A tab in the page's own tab row: in place, even to another segment.+ expect(newPlace("/marketing", "/ads", { fromTabRow: true })).toBe(false);+ expect(newPlace("/marketing", "/ads")).toBe(true);+ });++ it("pictures fade in only when they are still loading and nothing else styles them", () => {+ type Img = HTMLImageElement & { listeners: Record<string, () => void> };+ const img = (o: Partial<{ complete: boolean; fetchpriority: string; className: string; opacity: string; src: string }> = {}) => {+ const listeners: Record<string, () => void> = {};+ return {+ complete: o.complete ?? false,+ dataset: {} as DOMStringMap,+ style: { opacity: o.opacity ?? "" },+ className: o.className ?? "",+ closest: () => null,+ getAttribute: (n: string) => (n === "fetchpriority" ? (o.fetchpriority ?? null) : n === "src" ? (o.src ?? "/a.jpg") : null),+ addEventListener: (n: string, f: () => void) => (listeners[n] = f),+ removeEventListener: (n: string) => delete listeners[n],+ listeners,+ } as unknown as Img;+ };+ expect(fadesIn(img())).toBe(true);+ expect(fadesIn(img({ complete: true }))).toBe(false);+ expect(fadesIn(img({ fetchpriority: "high" }))).toBe(false);+ expect(fadesIn(img({ className: "opacity-0 transition-opacity" }))).toBe(false);+ expect(fadesIn(img({ opacity: "0.9" }))).toBe(false);++ const a = img();+ fadeInOnLoad(a);+ expect(a.dataset.fade).toBe("wait");+ a.listeners.load();+ expect(a.dataset.fade).toBe("in");+ const b = img();+ fadeInOnLoad(b);+ b.listeners.error();+ expect(b.dataset.fade).toBeUndefined();+ // Marked once: a second pass leaves it alone.+ fadeInOnLoad(a);+ expect(a.dataset.fade).toBe("in");+ });+});