Skip to content

armgit / fuobe

Public Imported from GitHub
0

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.

Tabs and chips: one rounded, aligned style everywhere

Adarshcec854f5dc79
diff --git a/package.json b/package.json
index 47d0398a..0fa87311 100644
--- a/package.json
+++ b/package.json
@@ -19,6 +19,7 @@
"test:e2e:mobile": "node tests/e2e/no-horizontal-scroll.mjs",
"test:e2e:shell": "node tests/e2e/shell.mjs",
"test:e2e:tabs": "node tests/e2e/instant-tabs.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",
"eval:run": "node scripts/eval/eval.mjs run",
diff --git a/src/app/globals.css b/src/app/globals.css
index 9cbdc703..4f34b2dc 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 "./tab-row.css";
@custom-variant dark (&:is(.dark *));
/* Hover for the app frame's controls: like hover:, but only while the mouse leads (nav-states.css), so a control under a
diff --git a/src/app/tab-row.css b/src/app/tab-row.css
new file mode 100644
index 00000000..0f1b24d8
--- /dev/null
+++ b/src/app/tab-row.css
@@ -0,0 +1,267 @@
+/*
+ * Tab and chip rows (src/components/ui/tab-row.tsx): one look for every row of tabs or chips on the site. A row is
+ * `.tab-row`; each item is `.tab-pill`, marked `data-on` while it is the selected one.
+ *
+ * - Every item is a fully rounded pill, 36 px tall (44 px to tap on touch), its icon and words centred.
+ * - 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.
+ */
+: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));
+}
+.dark {
+ --tab-on: oklch(1 0 0 / 14%);
+}
+@media (min-width: 768px) {
+ :root {
+ --tab-band-top: var(--chrome-top);
+ }
+}
+
+@layer components {
+ .tab-row {
+ position: relative;
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ min-width: 0;
+ /* Room for the focus ring and the 44 px hit area, without moving the pills off the page's grid. */
+ margin: -4px;
+ padding: 4px;
+ overflow-x: auto;
+ overscroll-behavior-x: contain;
+ scroll-padding-inline: 16px;
+ scrollbar-width: none;
+ isolation: isolate;
+ }
+ .tab-row::-webkit-scrollbar {
+ display: none;
+ }
+
+ .tab-pill {
+ position: relative;
+ display: inline-flex;
+ flex-shrink: 0;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ height: 36px;
+ min-width: 44px;
+ padding-inline: 14px;
+ border: 0;
+ border-radius: 9999px;
+ background-color: transparent;
+ color: var(--muted-foreground);
+ font-size: 13.5px;
+ font-weight: 500;
+ line-height: 1;
+ white-space: nowrap;
+ text-decoration: none;
+ cursor: pointer;
+ outline: none;
+ user-select: none;
+ -webkit-tap-highlight-color: transparent;
+ transition:
+ background-color 140ms var(--tab-ease),
+ color 140ms var(--tab-ease);
+ }
+ /* An icon leads: a little less room on its side, so icon and words look centred. */
+ .tab-pill:has(> svg:first-child) {
+ padding-inline: 12px 14px;
+ }
+ /* A round picture leads (Home's apps to compare): set in the pill's round end, as far from its edge as from the top. */
+ .tab-pill:has(> .tab-thumb:first-child) {
+ padding-inline: 8px 14px;
+ }
+ .tab-pill > .tab-thumb {
+ width: 20px;
+ height: 20px;
+ flex-shrink: 0;
+ overflow: hidden;
+ border-radius: 9999px;
+ background-color: var(--muted);
+ }
+ .tab-pill > .tab-thumb > img {
+ display: block;
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ }
+ .tab-pill > svg {
+ width: 16px;
+ height: 16px;
+ flex-shrink: 0;
+ color: var(--muted-foreground);
+ transition: color 140ms var(--tab-ease);
+ }
+ /* A count after the words (Library). */
+ .tab-pill .tab-count {
+ margin-left: -2px;
+ font-family: var(--font-mono);
+ font-size: 11px;
+ font-variant-numeric: tabular-nums;
+ color: var(--muted-foreground);
+ }
+ /* 44 px to tap on touch: the hit area reaches past the pill into the row's padding. */
+ @media (pointer: coarse) {
+ .tab-pill::after {
+ content: "";
+ position: absolute;
+ inset: -4px 0;
+ }
+ }
+
+ .tab-pill:is([data-on], [data-state="active"]) {
+ background-color: var(--tab-on);
+ color: var(--foreground);
+ }
+ .tab-pill:is([data-on], [data-state="active"]) > svg {
+ color: var(--brand-text);
+ }
+ /* Hover only while the mouse leads (html[data-input], nav/input-modality.ts), as in the nav: never a second fill
+ beside the keyboard's ring. */
+ @media (hover: hover) {
+ html:not([data-input="keyboard"]) .tab-pill:not([data-on], [data-state="active"]):hover {
+ background-color: var(--tab-hi);
+ color: var(--foreground);
+ }
+ /* The page scrolling under a resting mouse leaves no fill behind. */
+ html:not([data-input="keyboard"]) .tab-row[data-still] .tab-pill:not([data-on], [data-state="active"]):hover {
+ background-color: transparent;
+ color: var(--muted-foreground);
+ }
+ }
+ html .tab-pill:not([data-on], [data-state="active"]):active:active {
+ background-color: var(--tab-press);
+ transition-duration: 0ms;
+ }
+ /* The keyboard's ring, the pill's own shape (the mouse's clicks never show it). */
+ html:not([data-input="pointer"]) .tab-pill:focus-visible {
+ outline: 2px solid var(--ring);
+ outline-offset: 2px;
+ }
+ .tab-pill:disabled,
+ .tab-pill[aria-disabled="true"] {
+ opacity: 0.45;
+ cursor: not-allowed;
+ background-color: transparent;
+ }
+
+ /*
+ * The sliding fill: three parts (two round ends and a middle), moved and stretched with transforms only, so a move
+ * never lays the page out again. The row's script sets --ti-x, --ti-y (the selected pill's place), --ti-h (its
+ * height), --ti-r (where its right end starts) and --ti-s (the middle's width / 100).
+ */
+ .tab-ind {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 0;
+ height: 0;
+ pointer-events: none;
+ z-index: -1;
+ opacity: 0;
+ transition: opacity 160ms var(--tab-ease);
+ }
+ .tab-row[data-ind] > .tab-ind {
+ opacity: 1;
+ }
+ .tab-ind > span {
+ position: absolute;
+ top: 0;
+ left: 0;
+ height: var(--ti-h, 36px);
+ background-color: var(--tab-on);
+ transform-origin: 0 0;
+ will-change: transform;
+ }
+ .tab-ind > span:nth-child(1) {
+ width: calc(var(--ti-h, 36px) / 2);
+ border-radius: 9999px 0 0 9999px;
+ transform: translate(var(--ti-x, 0px), var(--ti-y, 0px));
+ }
+ .tab-ind > span:nth-child(2) {
+ width: 100px;
+ transform: translate(calc(var(--ti-x, 0px) + var(--ti-h, 36px) / 2), var(--ti-y, 0px)) scaleX(var(--ti-s, 0));
+ }
+ .tab-ind > span:nth-child(3) {
+ width: calc(var(--ti-h, 36px) / 2);
+ border-radius: 0 9999px 9999px 0;
+ transform: translate(var(--ti-r, 0px), var(--ti-y, 0px));
+ }
+ .tab-row[data-ind-moving] > .tab-ind > span {
+ transition: transform 320ms var(--tab-ease);
+ }
+ /* 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"]),
+ .tab-row[data-ind] > * > .tab-pill:is([data-on], [data-state="active"]) {
+ background-color: transparent;
+ }
+
+ /*
+ * A row of section tabs that stays under the bar while its sections scroll by: a band of the page's own background
+ * that reaches the screen's edges, the pills centred in it, and a hairline under it once it is stuck.
+ */
+ .tab-band {
+ position: sticky;
+ top: var(--tab-band-top);
+ z-index: 10;
+ display: flex;
+ align-items: center;
+ height: 52px;
+ background-color: var(--background);
+ box-shadow: 0 0 0 100vmax var(--background);
+ clip-path: inset(0 -100vmax -1px);
+ }
+ /*
+ * The hairline: its own layer over the band's reach to the screen's edges, shown once the band is stuck. The line is
+ * the band's own width; a shadow clipped to its 1 px carries it to the edges, as a shadow never widens the page.
+ */
+ .tab-band::after {
+ content: "";
+ position: absolute;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ height: 1px;
+ background-color: var(--border);
+ box-shadow: 0 0 0 100vmax var(--border);
+ clip-path: inset(0 -100vmax);
+ opacity: 0;
+ pointer-events: none;
+ transition: opacity 160ms var(--tab-ease);
+ }
+ .tab-band[data-stuck]::after {
+ opacity: 1;
+ }
+ .tab-band > .tab-row {
+ flex: 1;
+ }
+ @media (max-width: 639.98px) {
+ .tab-band {
+ margin-inline: -16px;
+ }
+ .tab-band > .tab-row {
+ margin-inline: 0;
+ padding-inline: 16px;
+ }
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .tab-pill,
+ .tab-pill > svg,
+ .tab-ind,
+ .tab-band::after,
+ .tab-row[data-ind-moving] > .tab-ind > span {
+ transition: none;
+ }
+}
diff --git a/src/components/ads/ad-editor.tsx b/src/components/ads/ad-editor.tsx
index ca848add..313ae21c 100644
--- a/src/components/ads/ad-editor.tsx
+++ b/src/components/ads/ad-editor.tsx
@@ -10,6 +10,7 @@ import { areaCls, inputCls } from "@/components/brand/fields";
import { uploadFile } from "@/lib/api";
import type { BrandKit } from "@/lib/catalog/marketing";
import { cn } from "@/lib/utils";
+import { onAttr, TAB_PILL, TabRow } from "@/components/ui/tab-row";
import { toastError } from "@/lib/refusals";
import { AdCanvas } from "./ad-canvas";
import { AD_LAYOUTS, exportName, themeFrom, type AdLayout } from "./layout";
@@ -115,13 +116,13 @@ export function AdEditor({
<div className="grid min-w-0 gap-5 p-5 md:grid-cols-[minmax(0,1fr)_320px]">
<div className="min-w-0">
{ratios.length > 1 && (
- <div role="tablist" aria-label="Format" className="mb-3 inline-flex rounded-full bg-muted p-0.5">
+ <TabRow role="tablist" aria-label="Format" fade={false} className="mb-2 w-fit">
{ratios.map((r) => (
- <button key={r} role="tab" aria-selected={r === ratio} onClick={() => setRatio(r)} className={cn("h-7 rounded-full px-3 text-[12px] font-medium text-muted-foreground", r === ratio && "bg-background text-foreground shadow-soft")}>
+ <button key={r} role="tab" aria-selected={r === ratio} onClick={() => setRatio(r)} className={TAB_PILL} {...onAttr(r === ratio)}>
{r}
</button>
))}
- </div>
+ </TabRow>
)}
<div className="mx-auto" style={{ maxWidth: ratio === "9:16" ? 300 : ratio === "4:5" ? 380 : 440 }}>
<AdCanvas input={input(ratio)} className="rounded-xl shadow-normal" label={`${title}, ${ratio}`} />
diff --git a/src/components/areas/area-islands.tsx b/src/components/areas/area-islands.tsx
index 847665d9..4a8ec383 100644
--- a/src/components/areas/area-islands.tsx
+++ b/src/components/areas/area-islands.tsx
@@ -1,14 +1,14 @@
"use client";
import { Search } from "lucide-react";
-import { useEffect, useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
import { IntentLink } from "@/components/intent-link";
import { PILL, PILL_ICON, PILL_TAP } from "@/components/home/pill";
import { useExplored } from "@/components/nav/explore-tracker";
-import { GOAL_TAB, GOAL_TAB_ON } from "@/components/nav/goal-tab";
import { useViewerKind } from "@/components/nav/nav-ui";
import { useSearchPalette } from "@/components/nav/search-context";
-import { useFadeEdges } from "@/components/use-fade-edges";
+import { onAttr, reducedMotion, TAB_PILL, TabRow } from "@/components/ui/tab-row";
+import { glideTo } from "@/lib/glide-scroll";
import { area, type AreaId } from "@/lib/nav-areas";
import { navIcon } from "@/lib/nav-icons";
import { entry, visibleTo, type NavEntry } from "@/lib/nav-model";
@@ -54,69 +54,174 @@ export interface AreaTab {
section: string;
}
+/** The parts of a section that come in one after the other: its heading, then each card, then its pills. */
+function revealParts(section: HTMLElement): Element[] {
+ const s = section.querySelector("section") ?? section;
+ const parts: Element[] = [];
+ for (const c of s.children) {
+ if (c.classList.contains("grid")) parts.push(...c.children);
+ else parts.push(c);
+ }
+ return parts;
+}
+
+/** A section's gentle arrival: opacity and a 10 px rise, staggered. It only ever plays from hidden to shown. */
+function reveal(section: HTMLElement) {
+ if (reducedMotion()) return;
+ revealParts(section).forEach((p, i) => {
+ if (typeof p.animate !== "function") return;
+ p.animate([{ opacity: 0, transform: "translateY(10px)" }, { opacity: 1, transform: "none" }], {
+ duration: 480,
+ delay: Math.min(i, 8) * 45,
+ easing: "cubic-bezier(0.25, 0.8, 0.25, 1)",
+ fill: "backwards",
+ });
+ });
+}
+
/**
- * The area's tabs in the goal row's strip, kept under the bar (the phone's or the desktop's) while its sections scroll
- * by: links, so they work before the page hydrates. The tab of the section being read is marked (aria-current), and
- * scrolled into view in the strip, which a phone scrolls sideways inside itself.
+ * The area's section tabs, kept under the bar (the phone's or the desktop's) in a band of the page's background while
+ * its sections scroll by: links, so they work before the page hydrates. The tab of the section being read is selected
+ * (aria-current), and the fill slides to it as the page scrolls; a phone's row scrolls sideways inside itself and keeps
+ * it in sight. A tap glides the page to its section (an instant jump with reduced motion), and that tab is selected from
+ * the tap on, not stepping through the sections passed on the way. Each section comes in gently the first time it
+ * reaches the screen (never the ones already there at load).
*/
export function AreaTabs({ tabs, label }: { tabs: AreaTab[]; label: string }) {
- const strip = useFadeEdges<HTMLDivElement>();
+ const band = useRef<HTMLElement>(null);
const [on, setOn] = useState<string | null>(null);
const key = tabs.map((t) => t.section).join(",");
+ // The section a tap is gliding to: the scroll-spy waits until it lands. Then `landed` keeps that tab selected until the
+ // page moves again (a last section too short to reach the top still is the one asked for).
+ const going = useRef<string | null>(null);
+ const landed = useRef<{ id: string; y: number } | null>(null);
+ const shown = useRef(new Map<string, number>());
+ const spy = useCallback(() => {
+ if (going.current) return;
+ if (landed.current && Math.abs(window.scrollY - landed.current.y) < 2) return;
+ landed.current = null;
+ const ids = key.split(",");
+ // At the very end of the page, the last section on screen: it may never reach the top.
+ const end = window.scrollY > 0 && window.scrollY + window.innerHeight >= document.documentElement.scrollHeight - 4;
+ const last = end ? ids.findLast((id) => (document.getElementById(id)?.getBoundingClientRect().top ?? Infinity) < window.innerHeight * 0.6) : undefined;
+ // Otherwise the first section (in page order) under the bar and the tabs: the one being read.
+ const first = last ?? ids.find((id) => (shown.current.get(id) ?? 0) > 0);
+ if (first) return setOn(first);
+ // None under the bar: above the first section (a page that opens with a wall), the first tab is the way in; between
+ // sections or past the last, the tab stays as it was.
+ const head = document.getElementById(ids[0]);
+ if (head && head.getBoundingClientRect().top > 120) setOn(ids[0]);
+ }, [key]);
+
+ // The end of the page changes no section's place under the bar, so the scroll itself is watched too.
+ useEffect(() => {
+ let raf = 0;
+ const onScroll = () => {
+ if (!raf)
+ raf = requestAnimationFrame(() => {
+ raf = 0;
+ spy();
+ });
+ };
+ window.addEventListener("scroll", onScroll, { passive: true });
+ return () => {
+ cancelAnimationFrame(raf);
+ window.removeEventListener("scroll", onScroll);
+ };
+ }, [spy]);
useEffect(() => {
if (!key || typeof IntersectionObserver === "undefined") return;
- const shown = new Map<string, number>();
const io = new IntersectionObserver(
(entries) => {
- for (const e of entries) shown.set(e.target.id, e.isIntersecting ? e.intersectionRatio : 0);
- // The first section (in page order) under the bar and the tabs: the one being read.
- const first = key.split(",").find((id) => (shown.get(id) ?? 0) > 0);
- setOn(first ?? null);
+ for (const e of entries) shown.current.set(e.target.id, e.isIntersecting ? e.intersectionRatio : 0);
+ spy();
},
{ rootMargin: "-120px 0px -45% 0px", threshold: [0, 0.01] },
);
+ // Arrivals: a section nearing the screen (just before it shows, so it starts hidden) for the first time.
+ const seen = new Set<Element>();
+ let initial = true;
+ const arrive = new IntersectionObserver(
+ (entries) => {
+ for (const e of entries) {
+ if (!e.isIntersecting || seen.has(e.target)) continue;
+ seen.add(e.target);
+ arrive.unobserve(e.target);
+ if (!initial) reveal(e.target as HTMLElement);
+ }
+ initial = false;
+ },
+ { rootMargin: "0px 0px 120px 0px" },
+ );
for (const id of key.split(",")) {
const el = document.getElementById(id);
- if (el) io.observe(el);
+ if (!el) continue;
+ io.observe(el);
+ arrive.observe(el);
}
- return () => io.disconnect();
- }, [key]);
+ return () => {
+ io.disconnect();
+ arrive.disconnect();
+ };
+ }, [key, spy]);
- // The marked tab stays in sight in a strip that scrolls sideways (a phone's).
+ // Stuck under the bar: the hairline under the band.
useEffect(() => {
- const row = strip.current;
- const tab = on ? row?.querySelector<HTMLElement>(`[data-section="${on}"]`) : null;
- if (!row || !tab || row.scrollWidth <= row.clientWidth) return;
- const left = tab.offsetLeft - (row.clientWidth - tab.offsetWidth) / 2;
- row.scrollTo({ left, behavior: window.matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth" });
- }, [on, strip]);
+ const el = band.current;
+ if (!el) return;
+ let raf = 0;
+ const check = () => {
+ raf = 0;
+ const top = parseFloat(getComputedStyle(el).top) || 0;
+ el.toggleAttribute("data-stuck", window.scrollY > 0 && el.getBoundingClientRect().top <= top + 0.5);
+ };
+ const onScroll = () => {
+ if (!raf) raf = requestAnimationFrame(check);
+ };
+ check();
+ window.addEventListener("scroll", onScroll, { passive: true });
+ window.addEventListener("resize", onScroll, { passive: true });
+ return () => {
+ cancelAnimationFrame(raf);
+ window.removeEventListener("scroll", onScroll);
+ window.removeEventListener("resize", onScroll);
+ };
+ }, []);
+
+ const go = (e: React.MouseEvent<HTMLAnchorElement>, t: AreaTab) => {
+ // A new tab or window (a modifier, the middle button) leaves this page as it is.
+ if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
+ const target = document.getElementById(t.section);
+ if (!target) return;
+ e.preventDefault();
+ going.current = t.section;
+ setOn(t.section);
+ if (location.hash !== t.href) history.pushState(history.state, "", t.href);
+ landed.current = null;
+ void glideTo(target).then((done) => {
+ if (going.current !== t.section) return;
+ going.current = null;
+ if (done) landed.current = { id: t.section, y: window.scrollY };
+ // Landed (or the visitor took over): the scroll-spy says again, after the last scroll has been seen.
+ requestAnimationFrame(spy);
+ });
+ };
return (
- <nav
- aria-label={label}
- // Under the phone's bar (48 px and the notch), or the desktop's (top-chrome). Its background and lower rule reach
- // the screen's edges (shadows clipped to its own height), so cards scrolling under it never show at its sides.
- className="sticky top-[calc(3.5rem+env(safe-area-inset-top))] z-10 mt-5 flex h-[52px] items-stretch border-y bg-background shadow-[0_0_0_100vmax_var(--background),0_1px_0_100vmax_var(--border)] [clip-path:inset(0_-100vmax_-1px)] max-sm:-mx-4 md:top-chrome"
- >
- <div ref={strip} className="fade-x scrollbar-none relative flex min-w-0 flex-1 snap-x items-stretch gap-0.5 overflow-x-auto max-sm:px-1">
+ <nav ref={band} aria-label={label} className="tab-band mt-5">
+ <TabRow follow>
{tabs.map((t) => {
const Icon = navIcon(t.icon);
const current = on !== null && t.section === on;
return (
- <a key={t.href} href={t.href} data-section={t.section} aria-current={current ? "true" : undefined} className={cn(GOAL_TAB, current && GOAL_TAB_ON)}>
- <Icon aria-hidden className={cn("size-4 shrink-0 md:max-lg:hidden", current ? "text-brand-text" : "text-muted-foreground")} />
- {/* The label's bold copy keeps its width, so marking a tab never moves the ones beside it. */}
- <span className="grid">
- <span className={cn("col-start-1 row-start-1", current ? "font-semibold" : "font-medium")}>{t.label}</span>
- <span aria-hidden className="invisible col-start-1 row-start-1 font-semibold">
- {t.label}
- </span>
- </span>
+ <a key={t.href} href={t.href} data-section={t.section} aria-current={current ? "true" : undefined} onClick={(e) => go(e, t)} className={TAB_PILL} {...onAttr(current)}>
+ <Icon aria-hidden />
+ {t.label}
</a>
);
})}
- </div>
+ </TabRow>
</nav>
);
}
diff --git a/src/components/areas/area-page.tsx b/src/components/areas/area-page.tsx
index 6c79600c..ce208722 100644
--- a/src/components/areas/area-page.tsx
+++ b/src/components/areas/area-page.tsx
@@ -19,10 +19,10 @@ import { AreaSearch, AreaTabs, JumpBackIn, OwnerPills, type AreaTab } from "./ar
/**
* Each section's space under the one before, as Home's (without Home's content-visibility, which needs a known height).
- * A jump to it stops under the bar and the tabs: the phone's bar and the tabs (108 px) and the notch; from md the page
- * already keeps the bar's 56 px clear (scroll-padding), so the tabs' 52 px and a little air.
+ * A jump to it stops under the bar and the tabs: the phone's bar and the tabs (108 px), 8 px of air and the notch; from md the page
+ * already keeps the bar's 56 px clear (scroll-padding), so the tabs' 52 px and 8 px of air.
*/
-export const AREA_SECTION = "-mx-4 mt-8 -mb-2 scroll-mt-[calc(7.25rem+env(safe-area-inset-top))] px-4 py-2 sm:mt-12 md:scroll-mt-16";
+export const AREA_SECTION = "-mx-4 mt-8 -mb-2 scroll-mt-[calc(7.25rem+env(safe-area-inset-top))] px-4 py-2 sm:mt-12 md:scroll-mt-[60px]";
/** The area page's heading: its name and count, its line, and its search (Create, Studios) beside it, or under it on a phone. */
export function AreaHero({ id, count, search, action }: { id: AreaId; count: number; search?: string[]; action?: React.ReactNode }) {
diff --git a/src/components/av/tool-shell.tsx b/src/components/av/tool-shell.tsx
index 8adaaac3..cf7a19c0 100644
--- a/src/components/av/tool-shell.tsx
+++ b/src/components/av/tool-shell.tsx
@@ -1,6 +1,7 @@
"use client";
import { PhoneNavButton } from "@/components/nav/phone-nav-button";
+import { useSwapFade } from "@/components/ui/tab-row";
import { EngineSwitch } from "@/components/studio/engine-switch";
import { HubHeaderExtras, useInHub } from "@/components/studio/hub-chrome";
import { useEngine } from "@/lib/api";
@@ -20,6 +21,7 @@ export function ToolShell({
selfHostedOnly,
children,
wide,
+ fadeKey,
}: {
title: string;
tabs?: React.ReactNode;
@@ -30,10 +32,13 @@ export function ToolShell({
selfHostedOnly?: boolean;
children: React.ReactNode;
wide?: boolean;
+ /** What the body shows (a mode tab): when it changes, the body fades in. */
+ fadeKey?: unknown;
}) {
const [engine, setEngine] = useEngine();
const inHub = useInHub();
- const body = <div className={cn("mx-auto w-full min-w-0 flex-1 px-4 pb-16 sm:px-6", wide ? "max-w-[1240px]" : "max-w-[1040px]")}>{children}</div>;
+ const fade = useSwapFade<HTMLDivElement>(fadeKey);
+ const body = <div ref={fade} className={cn("mx-auto w-full min-w-0 flex-1 px-4 pb-16 sm:px-6", wide ? "max-w-[1240px]" : "max-w-[1040px]")}>{children}</div>;
if (inHub)
return (
<>
diff --git a/src/components/canvas/canvas-editor.tsx b/src/components/canvas/canvas-editor.tsx
index 33d72af5..e6bfc2be 100644
--- a/src/components/canvas/canvas-editor.tsx
+++ b/src/components/canvas/canvas-editor.tsx
@@ -95,6 +95,7 @@ import type { Engine, MediaKind, ModelDef } from "@/lib/catalog/types";
import { formatCost } from "@/lib/format";
import { useModKey } from "@/lib/keys";
import { cn } from "@/lib/utils";
+import { onAttr, TAB_PILL, TabRow } from "@/components/ui/tab-row";
import { toastError } from "@/lib/refusals";
import {
buildViews,
@@ -1287,14 +1288,14 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
{isMobile && (
<div className="flex shrink-0 items-center gap-2 border-b px-4 py-2">
- <div className="inline-grid h-9 grid-cols-2 rounded-full bg-muted p-0.5 text-[13px] font-medium" role="tablist" aria-label="View">
+ <TabRow role="tablist" aria-label="View" fade={false}>
{(["board", "list"] as const).map((t) => (
- <button key={t} role="tab" aria-selected={tab === t} onClick={() => setTab(t)} className={cn("inline-flex items-center gap-1.5 rounded-full px-3.5", tab === t ? "bg-background shadow-soft" : "text-muted-foreground")}>
- {t === "board" ? <LayoutGrid className="size-3.5" /> : <List className="size-3.5" />}
+ <button key={t} role="tab" aria-selected={tab === t} onClick={() => setTab(t)} className={TAB_PILL} {...onAttr(tab === t)}>
+ {t === "board" ? <LayoutGrid aria-hidden /> : <List aria-hidden />}
{t === "board" ? "Board" : "Nodes"}
</button>
))}
- </div>
+ </TabRow>
{pages.length > 1 && (
<select value={pageId} onChange={(e) => pageOps.switchTo(e.target.value)} aria-label="Page" className="h-9 max-w-32 shrink-0 truncate rounded-full bg-muted px-3 text-[13px] font-medium outline-none">
{pages.map((p) => (
diff --git a/src/components/canvas/toolbar.tsx b/src/components/canvas/toolbar.tsx
index ea8fc545..156b54b0 100644
--- a/src/components/canvas/toolbar.tsx
+++ b/src/components/canvas/toolbar.tsx
@@ -5,6 +5,7 @@ import { memo, useState } from "react";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { Kbd } from "@/components/ui/kbd";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import { onAttr, TAB_PILL, TabRow } from "@/components/ui/tab-row";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { BOARD_LIMITS, SHAPE_LABEL, type BoardColor } from "@/lib/catalog/canvas-board";
import { useModKey } from "@/lib/keys";
@@ -172,7 +173,7 @@ export const PageTabs = memo(function PageTabs({ pages, active, ops, readOnly }:
};
return (
<div className="flex max-w-full items-center gap-0.5 rounded-full border bg-popover p-1 shadow-normal" data-board-ui>
- <div className="flex min-w-0 items-center gap-0.5 overflow-x-auto [scrollbar-width:none]" role="tablist" aria-label="Pages" onKeyDown={onKeyDown}>
+ <TabRow fade={false} role="tablist" aria-label="Pages" onKeyDown={onKeyDown}>
{pages.map((p) =>
editing === p.id ? (
<input
@@ -192,7 +193,7 @@ export const PageTabs = memo(function PageTabs({ pages, active, ops, readOnly }:
e.stopPropagation();
}}
aria-label="Page name"
- className="h-7 w-32 rounded-full border bg-background px-3 text-[13px] outline-none focus:border-primary"
+ className="h-9 w-32 shrink-0 rounded-full border bg-background px-3.5 text-[13.5px] outline-none focus:border-primary"
/>
) : (
<button
@@ -205,18 +206,19 @@ export const PageTabs = memo(function PageTabs({ pages, active, ops, readOnly }:
onClick={() => ops.switchTo(p.id)}
onDoubleClick={() => !readOnly && setEditing(p.id)}
title={readOnly ? p.name : `${p.name} · double-click to rename`}
- className={cn("h-7 max-w-36 shrink-0 truncate rounded-full px-3 text-[13px] font-medium transition-colors", p.id === active ? "bg-secondary text-foreground" : "text-muted-foreground hover:bg-accent hover:text-foreground")}
+ className={cn(TAB_PILL, "max-w-36")}
+ {...onAttr(p.id === active)}
>
- {p.name}
+ <span className="truncate">{p.name}</span>
</button>
),
)}
- </div>
+ </TabRow>
{!readOnly && (
<>
<DropdownMenu>
<DropdownMenuTrigger asChild>
- <button className="grid size-7 shrink-0 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground" aria-label="Page actions">
+ <button className="grid size-9 shrink-0 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground" aria-label="Page actions">
<MoreHorizontal className="size-4" />
</button>
</DropdownMenuTrigger>
@@ -235,7 +237,7 @@ export const PageTabs = memo(function PageTabs({ pages, active, ops, readOnly }:
</DropdownMenu>
<Tooltip>
<TooltipTrigger asChild>
- <button onClick={ops.add} disabled={full} className="grid size-7 shrink-0 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-40" aria-label="Add a page">
+ <button onClick={ops.add} disabled={full} className="grid size-9 shrink-0 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-40" aria-label="Add a page">
<Plus className="size-4" />
</button>
</TooltipTrigger>
diff --git a/src/components/cinema/director-panel.tsx b/src/components/cinema/director-panel.tsx
index a976ff9d..f11553e7 100644
--- a/src/components/cinema/director-panel.tsx
+++ b/src/components/cinema/director-panel.tsx
@@ -34,6 +34,7 @@ import {
import type { StudioElement } from "@/lib/catalog/elements";
import type { Engine } from "@/lib/catalog/types";
import { cn } from "@/lib/utils";
+import { onAttr, TAB_PILL, TabRow } from "@/components/ui/tab-row";
import { MoveChips, MoveList, prefetchMoves } from "./camera-moves";
import { PaletteEditor } from "./palette-editor";
@@ -215,7 +216,7 @@ export function CameraChip({
{missing && <TooltipContent>Stills need a camera, lens and focal length</TooltipContent>}
</Tooltip>
<PopoverContent className="w-[min(94vw,540px)] p-3" align="start" side="top" collisionPadding={12}>
- <div className="scrollbar-none mb-3 flex gap-0.5 overflow-x-auto rounded-full bg-muted p-0.5" role="tablist">
+ <TabRow className="mb-2" role="tablist" aria-label="Camera" follow>
{CAMERA_TABS.filter((t) => t.id !== "movement" || mode === "video").map((t) => (
<button
key={t.id}
@@ -224,17 +225,15 @@ export function CameraChip({
onClick={() => setTab(t.id)}
onPointerEnter={t.id === "movement" ? prefetchMoves : undefined}
onFocus={t.id === "movement" ? prefetchMoves : undefined}
- className={cn(
- "inline-flex h-7 shrink-0 items-center gap-1 rounded-full px-3 text-[12px] font-medium transition-colors",
- tab === t.id ? "bg-background text-foreground shadow-soft" : "text-muted-foreground hover:text-foreground",
- )}
+ className={TAB_PILL}
+ {...onAttr(tab === t.id)}
>
{t.label}
{needs(t.id) && <span className="size-1.5 rounded-full bg-warning" aria-label="required" />}
{t.id === "movement" && moves.length > 0 && <span className="font-mono text-[10px] text-brand-text">{moves.length}</span>}
</button>
))}
- </div>
+ </TabRow>
<div className="max-h-[min(56vh,420px)] overflow-y-auto pr-0.5">
{tab === "camera" && <OptionGrid options={CAMERA_BODIES} value={settings.camera} onChange={(camera) => onChange({ camera })} />}
{tab === "lens" && <OptionGrid options={LENSES} value={settings.lens} onChange={(lens) => onChange({ lens })} />}
@@ -516,19 +515,13 @@ export function LightingChip({ settings, onChange }: { settings: DirectorSetting
</PopoverTrigger>
<PopoverContent className="w-[min(94vw,520px)] p-3" align="start" side="top" collisionPadding={12}>
<PanelHeader title="Set up lighting" subtitle="Pick a scheme or place your own lights" />
- <div className="mb-3 inline-flex rounded-full bg-muted p-0.5" role="tablist">
+ <TabRow className="mb-2" role="tablist" aria-label="Lighting" fade={false}>
{(["presets", "custom"] as const).map((t) => (
- <button
- key={t}
- role="tab"
- aria-selected={tab === t}
- onClick={() => setTab(t)}
- className={cn("h-7 rounded-full px-3 text-[12px] font-medium", tab === t ? "bg-background shadow-soft" : "text-muted-foreground hover:text-foreground")}
- >
+ <button key={t} role="tab" aria-selected={tab === t} onClick={() => setTab(t)} className={TAB_PILL} {...onAttr(tab === t)}>
{t === "presets" ? "Presets" : "Custom rig"}
</button>
))}
- </div>
+ </TabRow>
<div className="max-h-[min(56vh,440px)] overflow-y-auto pr-0.5">
{tab === "presets" ? (
<div className="grid grid-cols-1 gap-1.5 sm:grid-cols-2" role="radiogroup">
diff --git a/src/components/cinema/palette-editor.tsx b/src/components/cinema/palette-editor.tsx
index 6ce2e9ed..68d93a39 100644
--- a/src/components/cinema/palette-editor.tsx
+++ b/src/components/cinema/palette-editor.tsx
@@ -8,6 +8,7 @@ import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, D
import { Input } from "@/components/ui/input";
import { Slider } from "@/components/ui/slider";
import { cn } from "@/lib/utils";
+import { onAttr, TAB_PILL, TabRow } from "@/components/ui/tab-row";
import { HARMONIES, harmonyPalette, hexToRgb, hslToHex, kmeans, rgbToHex, rgbToHsl, type Harmony, type RGB } from "./color-math";
interface Point {
@@ -364,7 +365,7 @@ function EditorBody({ onClose, onSave }: { onClose: () => void; onSave: (p: { na
<DialogTitle>New palette</DialogTitle>
<DialogDescription>Pull colours from a frame you like, or build a harmony on the colour wheel.</DialogDescription>
</DialogHeader>
- <div className="inline-flex w-fit rounded-full bg-muted p-0.5" role="tablist">
+ <TabRow className="w-fit" role="tablist" aria-label="Source" fade={false}>
{(
[
["image", "From image"],
@@ -379,11 +380,14 @@ function EditorBody({ onClose, onSave }: { onClose: () => void; onSave: (p: { na
setTab(id);
// The wheel starts from a harmony right away; the image tab waits for a picture.
setHex(id === "wheel" ? harmonyPalette(WHEEL_BASE, "analogous", 6) : []);
- }} className={cn("h-7 rounded-full px-3 text-[12px] font-medium", tab === id ? "bg-background shadow-soft" : "text-muted-foreground")}>
+ }}
+ className={TAB_PILL}
+ {...onAttr(tab === id)}
+ >
{label}
</button>
))}
- </div>
+ </TabRow>
{tab === "image" ? <FromImage onColors={setHex} /> : <ColorWheel onColors={setHex} />}
<div className="space-y-1.5">
<p className="text-[12px] text-muted-foreground">{hex.length ? "Click a colour to change it, drag to reorder." : "Your colours appear here."}</p>
diff --git a/src/components/cinema/side-panel.tsx b/src/components/cinema/side-panel.tsx
index 1f26ec1c..7c3aeb85 100644
--- a/src/components/cinema/side-panel.tsx
+++ b/src/components/cinema/side-panel.tsx
@@ -7,7 +7,7 @@ import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { directorSummary, moveBySlug, type CinemaProject, type DirectorMessage, type DirectorSettings, type DirectorShot } from "@/lib/catalog/cinema";
-import { cn } from "@/lib/utils";
+import { onAttr, TAB_PILL, TabRow } from "@/components/ui/tab-row";
import { toastError } from "@/lib/refusals";
import { useAutosave, useDirectorChat, useUpdateProject } from "./hooks";
@@ -230,7 +230,7 @@ export function SidePanel({
return (
<div className="flex h-full min-h-0 flex-col">
<div className="flex h-12 shrink-0 items-center gap-2 border-b px-2.5">
- <div className="inline-flex h-8 rounded-full bg-muted p-0.5" role="tablist">
+ <TabRow role="tablist" aria-label="Panel" fade={false}>
{(
[
["director", "AI Director", Bot],
@@ -243,12 +243,14 @@ export function SidePanel({
role="tab"
aria-selected={tab === id}
onClick={() => setTab(id)}
- className={cn("inline-flex items-center gap-1 rounded-full px-2.5 text-[12.5px] font-medium", tab === id ? "bg-background shadow-soft" : "text-muted-foreground hover:text-foreground")}
+ className={TAB_PILL}
+ {...onAttr(tab === id)}
>
- <Icon className="size-3.5" /> {label}
+ <Icon aria-hidden />
+ {label}
</button>
))}
- </div>
+ </TabRow>
<button type="button" onClick={onClose} className="ml-auto grid size-8 place-items-center rounded-lg text-muted-foreground hover:bg-accent hover:text-foreground" aria-label="Close panel">
<X className="size-4" />
</button>
diff --git a/src/components/cinema/soul-builders.tsx b/src/components/cinema/soul-builders.tsx
index ac3159f7..6c54979e 100644
--- a/src/components/cinema/soul-builders.tsx
+++ b/src/components/cinema/soul-builders.tsx
@@ -41,6 +41,7 @@ import { QMA_MODEL } from "@/lib/qma";
import type { Engine, Generation } from "@/lib/catalog/types";
import { formatCost } from "@/lib/format";
import { cn } from "@/lib/utils";
+import { onAttr, TAB_PILL, TabRow } from "@/components/ui/tab-row";
import { toastError } from "@/lib/refusals";
import { useCinemaGenerate, useCinemaItems } from "./hooks";
import { placeholdersOn } from "@/lib/demo-mode";
@@ -275,7 +276,7 @@ function SoulCast({ projectId, folderId, engine, context, brief, onOpenChange }:
<DialogTitle className="font-heading text-[26px] font-normal">Build your cast</DialogTitle>
<DialogDescription>Build your film&apos;s cast from scratch - genre, budget, appearance, and every detail in between.</DialogDescription>
</DialogHeader>
- <div className="scrollbar-none -mx-1 flex gap-1 overflow-x-auto px-1 pb-1" role="tablist">
+ <TabRow role="tablist" aria-label="Cast details" follow>
{SOUL_CAST_TABS.map((t) => {
const filled = SOUL_CAST_FIELDS.some((f) => f.tab === t && visible[f.key] !== undefined && !(f.default !== undefined && visible[f.key] === f.default));
return (
@@ -285,14 +286,15 @@ function SoulCast({ projectId, folderId, engine, context, brief, onOpenChange }:
role="tab"
aria-selected={tab === t}
onClick={() => setTab(t)}
- className={cn("inline-flex h-8 shrink-0 items-center gap-1 rounded-full px-3 text-[12.5px] font-medium", tab === t ? "bg-primary text-primary-foreground" : "bg-secondary hover:bg-accent")}
+ className={TAB_PILL}
+ {...onAttr(tab === t)}
>
{t}
{filled && tab !== t && <span className="size-1.5 rounded-full bg-primary" />}
</button>
);
})}
- </div>
+ </TabRow>
<div className="min-h-[200px] space-y-4">
{fields.map((f) => (
<Field key={f.key} f={f} values={values} set={set} />
diff --git a/src/components/dub/dub-studio.tsx b/src/components/dub/dub-studio.tsx
index 00642d50..262dec67 100644
--- a/src/components/dub/dub-studio.tsx
+++ b/src/components/dub/dub-studio.tsx
@@ -46,6 +46,7 @@ import {
import { languageByCode, supportsTarget, type DubRoute } from "@/lib/av/languages";
import type { Cue } from "@/lib/cues";
import { cn } from "@/lib/utils";
+import { onAttr, TAB_PILL, TabRow } from "@/components/ui/tab-row";
import { toastError } from "@/lib/refusals";
import { useDubActions, useDubPrice, useDubSessions, useVoicePrice } from "./hooks";
@@ -464,20 +465,21 @@ function SessionView({ s, onBack }: { s: DubSessionView; onBack: () => void }) {
</AlertDialog>
</div>
- <div role="tablist" aria-label="Languages" className="scrollbar-none mb-4 flex gap-1.5 overflow-x-auto">
+ <TabRow role="tablist" aria-label="Languages" follow className="mb-3">
{s.targets.map((c) => (
<button
key={c}
role="tab"
aria-selected={c === lang}
onClick={() => setLang(c)}
- className={cn("inline-flex h-8 shrink-0 items-center gap-2 rounded-full px-3 text-[13px] font-medium transition-colors", c === lang ? "bg-foreground text-background" : "bg-secondary hover:bg-accent")}
+ className={TAB_PILL}
+ {...onAttr(c === lang)}
>
{languageByCode(c)?.name ?? c}
<span className={cn("size-1.5 rounded-full", { preparing: "bg-subtle-foreground", review: "bg-highlight", voicing: "bg-primary", done: "bg-success", failed: "bg-destructive" }[languageStage(s, c)])} />
</button>
))}
- </div>
+ </TabRow>
<div className="grid gap-4 lg:grid-cols-[minmax(0,5fr)_minmax(0,6fr)]">
<div className="space-y-3 lg:sticky lg:top-[calc(var(--chrome-top)+1rem)] lg:self-start">
diff --git a/src/components/fashion/character-sheet.tsx b/src/components/fashion/character-sheet.tsx
index c1c605e8..1f14a8fc 100644
--- a/src/components/fashion/character-sheet.tsx
+++ b/src/components/fashion/character-sheet.tsx
@@ -25,6 +25,7 @@ import { castFieldVisible, castNameFor, randomCast, SHEET_MAX_REFS, type CastAns
import { sheetPictures } from "@/lib/catalog/turnaround";
import type { Generation } from "@/lib/catalog/types";
import { cn } from "@/lib/utils";
+import { onAttr, TAB_PILL, TabRow } from "@/components/ui/tab-row";
import { toastError } from "@/lib/refusals";
import { SheetExample } from "@/components/empty-examples";
@@ -42,13 +43,13 @@ function CastForm({ fields, values, set }: { fields: CastFieldData[]; values: Ca
const [tab, setTab] = useState(tabs[0]);
return (
<div className="space-y-4">
- <div role="tablist" aria-label="Soul Cast" className="scrollbar-none flex gap-1 overflow-x-auto">
+ <TabRow role="tablist" aria-label="Soul Cast" follow>
{tabs.map((t) => (
- <button key={t} role="tab" aria-selected={tab === t} onClick={() => setTab(t)} className={cn("h-8 shrink-0 rounded-full px-3 text-[12.5px] font-medium transition-colors", tab === t ? "bg-brand-faint text-brand-text" : "bg-secondary text-secondary-foreground hover:bg-accent")}>
+ <button key={t} role="tab" aria-selected={tab === t} onClick={() => setTab(t)} className={TAB_PILL} {...onAttr(tab === t)}>
{t}
</button>
))}
- </div>
+ </TabRow>
{fields
.filter((f) => f.tab === tab && castFieldVisible(f.key, values))
.map((f) => {
@@ -237,13 +238,13 @@ export function CharacterSheetView({ fields, defaults }: { fields: CastFieldData
{visitor && <SelfHostNote className="-mt-3 mb-6 max-w-2xl">Character Sheet isn&apos;t available here.</SelfHostNote>}
<div className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">
<section className="min-w-0 space-y-4">
- <div role="tablist" aria-label="How to build it" className="scrollbar-none inline-flex max-w-full overflow-x-auto rounded-full bg-muted p-0.5">
+ <TabRow role="tablist" aria-label="How to build it" follow>
{MODES.map(([id, label]) => (
- <button key={id} role="tab" aria-selected={mode === id} onClick={() => setMode(id)} className={cn("h-8 shrink-0 rounded-full px-3.5 text-[13px] font-medium text-muted-foreground transition", mode === id && "bg-background text-foreground shadow-soft")}>
+ <button key={id} role="tab" aria-selected={mode === id} onClick={() => setMode(id)} className={TAB_PILL} {...onAttr(mode === id)}>
{label}
</button>
))}
- </div>
+ </TabRow>
{mode === "reference" && (
<div className="space-y-3">
diff --git a/src/components/genjutsu/genjutsu-studio.tsx b/src/components/genjutsu/genjutsu-studio.tsx
index 7f875b2a..b554471d 100644
--- a/src/components/genjutsu/genjutsu-studio.tsx
+++ b/src/components/genjutsu/genjutsu-studio.tsx
@@ -26,7 +26,7 @@ import { VideoTrimmer, type TrimRange, type VideoTrimmerHandle } from "@/compone
import { openInStudio } from "@/components/swap-studio/hooks";
import { SelfHostNote } from "@/components/self-host-note";
import { ExampleRow } from "@/components/studio/example-row";
-import { useEdgeFade } from "@/components/studio/use-edge-fade";
+import { onAttr, TAB_PILL, TabRow } from "@/components/ui/tab-row";
import { useEngine, useGenerations, useIsOwner, useLikelyVisitor, useModelAccess, useSoundLive, useStatus } from "@/lib/api";
import { CHARACTER_SWAP, cutsInPart, cutWarning, partWords, seedProblem, type CharacterChoice, type CharacterOptions } from "@/lib/catalog/character-swap";
import {
@@ -635,7 +635,7 @@ export function GenjutsuStudio({ examples, live }: { examples?: ExampleRowData |
const tabs = <ModeTabsRow modes={GENJUTSU_MODES.filter((m) => modeOpen(m.id, open))} mode={mode} onMode={setMode} onlyYou={(m) => owner && !modeOpen(m, (f) => !!live?.[f])} />;
return (
- <ToolShell title="Genjutsu" tabs={tabs} header={<SetupCode setup={setup} onPaste={apply} />} wide selfHostedOnly>
+ <ToolShell title="Genjutsu" tabs={tabs} fadeKey={mode} header={<SetupCode setup={setup} onPaste={apply} />} wide selfHostedOnly>
{!clip && (
<ToolHero title={modeInfo.label} subtitle={`${modeInfo.hint}${visitor ? "" : " Free on your own ComfyUI."}`}>
{isCharacter && (
@@ -1195,38 +1195,20 @@ function frameHint(mode: GenjutsuMode, target: GenjutsuTarget | undefined, point
/** The modes as tabs under the header (the selected one is in the URL as ?mode=); only the ones open to this viewer. */
function ModeTabsRow({ modes, mode, onMode, onlyYou }: { modes: typeof GENJUTSU_MODES; mode: GenjutsuMode; onMode: (m: GenjutsuMode) => void; onlyYou: (m: GenjutsuMode) => boolean }) {
- const [row, fade] = useEdgeFade<HTMLDivElement>();
// The selected tab stays in view on a phone, where the row scrolls (only the row: the page stays put).
- useEffect(() => {
- const r = row.current;
- const on = r?.querySelector<HTMLElement>('[aria-selected="true"]');
- if (r && on) r.scrollTo({ left: Math.max(0, on.offsetLeft - (r.clientWidth - on.offsetWidth) / 2) });
- }, [mode, row]);
return (
<div className="border-b">
- <div ref={row} style={fade} role="tablist" aria-label="Genjutsu modes" onKeyDown={tabKeys} className="scrollbar-none flex gap-1 overflow-x-auto px-4 sm:px-6">
+ <TabRow role="tablist" aria-label="Genjutsu modes" onKeyDown={tabKeys} follow className="m-0 px-4 py-1.5 sm:px-6">
{modes.map((m) => {
const on = m.id === mode;
return (
- <button
- key={m.id}
- type="button"
- role="tab"
- aria-selected={on}
- tabIndex={on ? 0 : -1}
- onClick={() => onMode(m.id)}
- className={cn(
- "relative flex h-11 shrink-0 items-center gap-1.5 px-2.5 text-[13px] font-medium whitespace-nowrap text-muted-foreground transition-colors outline-none hover:text-foreground focus-visible:text-foreground",
- "after:absolute after:inset-x-2.5 after:bottom-0 after:h-0.5 after:rounded-full after:transition-colors focus-visible:after:bg-ring",
- on && "text-foreground after:bg-foreground",
- )}
- >
+ <button key={m.id} type="button" role="tab" aria-selected={on} tabIndex={on ? 0 : -1} onClick={() => onMode(m.id)} className={TAB_PILL} {...onAttr(on)}>
{m.label}
{onlyYou(m.id) && <OnlyYou />}
</button>
);
})}
- </div>
+ </TabRow>
</div>
);
}
diff --git a/src/components/genjutsu/look-picker.tsx b/src/components/genjutsu/look-picker.tsx
index a3d108b9..0cf0aace 100644
--- a/src/components/genjutsu/look-picker.tsx
+++ b/src/components/genjutsu/look-picker.tsx
@@ -13,6 +13,7 @@ import { GENJUTSU, type GenjutsuLook } from "@/lib/catalog/genjutsu";
import { coveredFirst, SHORTS_PRESETS, shortsPreview } from "@/lib/catalog/shorts";
import { SOUL_LOOK_CARDS } from "@/lib/catalog/soul-cards";
import { cn } from "@/lib/utils";
+import { onAttr, TAB_PILL, TabRow } from "@/components/ui/tab-row";
export type LookSource = "fuobe" | "soul" | "custom";
@@ -50,7 +51,7 @@ export function LookPicker({
const souls = useMemo(() => (words_ ? SOUL_LOOK_CARDS.filter((l) => `${l.name} ${l.description} ${l.categories.join(" ")}`.toLowerCase().includes(words_)) : SOUL_LOOK_CARDS), [words_]);
return (
<div className="space-y-3">
- <div role="tablist" aria-label="Where the look comes from" onKeyDown={tabKeys} className="flex w-full rounded-full bg-muted p-0.5">
+ <TabRow role="tablist" aria-label="Where the look comes from" onKeyDown={tabKeys} fade={false}>
{tabs.map((t) => (
<button
key={t.id}
@@ -61,15 +62,13 @@ export function LookPicker({
aria-controls={`look-panel-${t.id}`}
tabIndex={source === t.id ? 0 : -1}
onClick={() => onSource(t.id)}
- className={cn(
- "flex h-8 min-w-0 flex-1 items-center justify-center rounded-full px-2 text-[13px] font-medium whitespace-nowrap text-muted-foreground transition-colors outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",
- source === t.id && "bg-background text-foreground shadow-soft",
- )}
+ className={cn(TAB_PILL, "min-w-0 flex-1 px-2")}
+ {...onAttr(source === t.id)}
>
{t.label}
</button>
))}
- </div>
+ </TabRow>
{source !== "custom" && (
<div className="relative">
diff --git a/src/components/home/before-after.tsx b/src/components/home/before-after.tsx
index 6bdd4dc3..eb008fba 100644
--- a/src/components/home/before-after.tsx
+++ b/src/components/home/before-after.tsx
@@ -3,6 +3,7 @@
import { ArrowRight } from "lucide-react";
import { useEffect, useId, useRef, useState } from "react";
import { IntentLink } from "@/components/intent-link";
+import { onAttr, TAB_PILL, TabRow } from "@/components/ui/tab-row";
import { cn } from "@/lib/utils";
/** One side's picture: a 512 px still, and with HD stills its 960 and 1280 px copies (each with its version). */
@@ -246,10 +247,11 @@ export function BeforeAfter({ pairs }: { pairs: BeforeAfterPair[] }) {
</span>
</div>
<div className="min-w-0 lg:max-xl:flex-1">
- <div
+ <TabRow
role="tablist"
aria-label="Apps to compare"
- className="mt-2 flex gap-1.5 lg:max-xl:mt-0 lg:max-xl:flex-col"
+ fade={false}
+ className="mt-2 lg:max-xl:mt-0 lg:max-xl:flex-col lg:max-xl:items-stretch"
onKeyDown={(e) => {
const keys = ["ArrowRight", "ArrowLeft", "ArrowDown", "ArrowUp"];
if (!keys.includes(e.key)) return;
@@ -270,21 +272,20 @@ export function BeforeAfter({ pairs }: { pairs: BeforeAfterPair[] }) {
onClick={() => pick(i)}
onPointerEnter={() => preload(p)}
onFocus={() => preload(p)}
- className={cn(
- "relative flex min-w-0 flex-1 items-center justify-center gap-2 rounded-lg p-1 text-[12px] after:absolute after:inset-x-0 after:-inset-y-1 after:content-[''] font-medium text-muted-foreground transition-colors outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring max-sm:h-9 sm:justify-start sm:pr-2 xl:flex-col xl:items-stretch xl:gap-1 xl:pr-1 xl:pb-1.5",
- i === tab && "bg-muted text-foreground",
- )}
+ // Each tab takes an equal share of the row (stacked from lg to xl). A phone's tabs are words alone, so each
+ // name fits whole.
+ className={cn(TAB_PILL, "min-w-0 flex-1 max-sm:px-3.5 lg:max-xl:flex-none lg:max-xl:justify-start")}
+ {...onAttr(i === tab)}
>
- {/* A phone's tabs are words alone, and from xl (a narrower picture) the thumb stands over the name, so each
- name fits whole. The sketch's paper edge is cropped as in the picture. */}
- <span className="hidden shrink-0 overflow-hidden rounded-md sm:block sm:h-[42px] sm:w-14 xl:h-10 xl:w-full">
+ {/* The sketch's paper edge is cropped as in the picture. */}
+ <span className="tab-thumb max-sm:hidden">
{/* eslint-disable-next-line @next/next/no-img-element */}
- <img src={p.thumb} alt="" width={56} height={42} loading="lazy" decoding="async" className="size-full object-cover" style={{ scale: p.zoom }} />
+ <img src={p.thumb} alt="" width={20} height={20} loading="lazy" decoding="async" style={{ scale: p.zoom }} />
</span>
- <span className="truncate leading-tight xl:text-center">{p.name}</span>
+ <span className="truncate">{p.name}</span>
</button>
))}
- </div>
+ </TabRow>
<div className="mt-2 flex items-center justify-between gap-3 text-[12px] text-muted-foreground lg:max-xl:mt-4 lg:max-xl:flex-col lg:max-xl:items-start lg:max-xl:gap-1.5 lg:max-xl:px-1">
<span>Drag to compare</span>
<IntentLink
diff --git a/src/components/influencer/influencer-builder.tsx b/src/components/influencer/influencer-builder.tsx
index 0a0101dc..32fc1f01 100644
--- a/src/components/influencer/influencer-builder.tsx
+++ b/src/components/influencer/influencer-builder.tsx
@@ -41,6 +41,7 @@ import {
type InfluencerState,
} from "@/lib/influencer";
import { cn } from "@/lib/utils";
+import { onAttr, TAB_PILL, TabRow, useSwapFade } from "@/components/ui/tab-row";
import { toastError } from "@/lib/refusals";
import { CATEGORY_ICON, LockButton, OptionTiles, pickRule, TierPanel } from "./option-panel";
@@ -142,6 +143,7 @@ export function InfluencerBuilder() {
const categories = useMemo(() => categoriesFor(state.tier), [state.tier]);
const category = categories.find((c) => c.id === active);
const tab = category ? category.id : "tier";
+ const panel = useSwapFade<HTMLElement>(tab);
// The rail scrolls sideways on phones: keep the open category in view (a summary chip can open any).
const railMoved = useRef(false);
useEffect(() => {
@@ -209,12 +211,13 @@ export function InfluencerBuilder() {
<div className="grid gap-4 lg:grid-cols-[212px_minmax(0,1fr)] xl:grid-cols-[212px_minmax(0,1fr)_340px]">
{/* The rail: Character type, then the categories this type shows. Phones scroll it sideways inside itself. */}
- <div
+ <TabRow
role="tablist"
aria-label="Categories"
aria-orientation={wide ? "vertical" : "horizontal"}
onKeyDown={tabKeys}
- className="scrollbar-none -mx-4 flex min-w-0 gap-1 overflow-x-auto px-4 lg:mx-0 lg:flex-col lg:overflow-visible lg:px-0"
+ follow
+ className="max-lg:-mx-4 max-lg:px-4 lg:flex-col lg:items-stretch lg:overflow-visible"
>
{[{ id: "tier", label: "Character type" }, ...categories].map((c) => {
const Icon = CATEGORY_ICON[c.id];
@@ -230,12 +233,10 @@ export function InfluencerBuilder() {
aria-controls="ib-panel"
tabIndex={on ? 0 : -1}
onClick={() => setActive(c.id)}
- className={cn(
- "flex h-9 shrink-0 items-center gap-2 rounded-full px-3 text-[13px] font-medium whitespace-nowrap text-muted-foreground transition-colors outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring lg:h-8 lg:rounded-lg lg:px-2.5",
- on && "bg-brand-faint text-brand-text hover:bg-brand-faint-hover hover:text-brand-text",
- )}
+ className={cn(TAB_PILL, "lg:justify-start")}
+ {...onAttr(on)}
>
- {Icon && <Icon className="size-3.5 shrink-0" aria-hidden />}
+ {Icon && <Icon aria-hidden />}
<span className="lg:min-w-0 lg:flex-1 lg:truncate lg:text-left">{c.label}</span>
{c.id === "tier" ? (
<span className="text-[11.5px] text-muted-foreground">{tierLabel}</span>
@@ -248,9 +249,9 @@ export function InfluencerBuilder() {
</button>
);
})}
- </div>
+ </TabRow>
- <section id="ib-panel" role="tabpanel" aria-labelledby={`ib-tab-${tab}`} className="min-w-0 space-y-4 rounded-2xl border bg-background p-4 sm:p-5">
+ <section ref={panel} id="ib-panel" role="tabpanel" aria-labelledby={`ib-tab-${tab}`} className="min-w-0 space-y-4 rounded-2xl border bg-background p-4 sm:p-5">
<div className="flex flex-wrap items-center gap-2">
<div className="mr-auto min-w-0">
<h2 className="font-heading text-[22px] leading-tight">{category?.label ?? "Character type"}</h2>
diff --git a/src/components/library-view.tsx b/src/components/library-view.tsx
index 5138a4be..8fd528de 100644
--- a/src/components/library-view.tsx
+++ b/src/components/library-view.tsx
@@ -19,7 +19,6 @@ import { useShare } from "@/components/share/share-provider";
import { SharedLinks } from "@/components/share/shared-links";
import { useSkillBuilder } from "@/components/skills/skill-builder-provider";
import { downloadUrl, ForeverConfirmProvider, useConfirmForever } from "@/components/studio/result-actions";
-import { useEdgeFade } from "@/components/studio/use-edge-fade";
import { Viewer } from "@/components/studio/viewer";
import {
AlertDialog,
@@ -51,6 +50,7 @@ import { isExpired } from "@/lib/share";
import { StarterSection, useStarters } from "@/components/starters/starter-section";
import { starterShown, type StarterCardData } from "@/lib/starters/types";
import { cn } from "@/lib/utils";
+import { onAttr, TAB_PILL, TabRow, useSwapFade } from "@/components/ui/tab-row";
import { toastError } from "@/lib/refusals";
type TabId = "all" | "images" | "videos" | "audio" | "text" | "3d" | "favorites" | "uploads" | "shared" | "trash";
@@ -444,7 +444,7 @@ function Inner({ starters: given }: { starters: StarterCardData[] }) {
const missingFolder = !!folderId && !!folders.data && !folder && !trash;
// The tab strip scrolls sideways on phones: fade the hidden edge and keep the active tab in view.
- const [tabsRef, tabsFade] = useEdgeFade<HTMLDivElement>();
+ const tabsRef = useRef<HTMLElement>(null);
const activeTab = useRef<HTMLButtonElement>(null);
const focusTab = useRef(false);
// Again once the counts load: tabs for kinds you have (Text, 3D) appear and shift the rest.
@@ -457,6 +457,8 @@ function Inner({ starters: given }: { starters: StarterCardData[] }) {
const loading = uploadsTab ? uploads.isLoading : lib.isLoading;
const refreshing = !uploadsTab && lib.isPlaceholderData;
+ // The results fade in when another section's (or folder's) arrive, not while the last ones still show.
+ const resultsRef = useSwapFade<HTMLDivElement>(refreshing ? null : `${tab.id}:${folderId ?? ""}`);
const count = (t: (typeof TABS)[number]) => {
const f = facets.data;
if (!f) return undefined;
@@ -643,12 +645,11 @@ function Inner({ starters: given }: { starters: StarterCardData[] }) {
</div>
{!folder && !foldersLoading && !missingFolder && (
- <div
+ <TabRow
ref={tabsRef}
- style={tabsFade}
role="tablist"
aria-label="Library sections"
- className="scrollbar-none mb-4 flex gap-4 overflow-x-auto border-b"
+ className="mb-4"
onKeyDown={(e) => {
// Arrow keys move between tabs (and open them), as in any tab strip.
if (e.key !== "ArrowRight" && e.key !== "ArrowLeft") return;
@@ -670,21 +671,19 @@ function Inner({ starters: given }: { starters: StarterCardData[] }) {
aria-selected={on}
tabIndex={on ? 0 : -1}
onClick={() => go({ tab: t.id === "all" ? undefined : t.id, folder: undefined })}
- className={cn(
- "-mb-px inline-flex shrink-0 items-center gap-1.5 border-b-2 border-transparent px-1 pb-2 text-[14px] whitespace-nowrap text-muted-foreground transition-colors outline-none hover:text-foreground focus-visible:text-foreground focus-visible:ring-2 focus-visible:ring-ring",
- on && "border-foreground font-medium text-foreground",
- )}
+ className={TAB_PILL}
+ {...onAttr(on)}
>
{t.label}
{n ? (
- <span className="min-w-4 font-mono text-[11px] text-muted-foreground tabular-nums" aria-label={`${n} items`}>
+ <span className="tab-count min-w-4" aria-label={`${n} items`}>
{n}
</span>
) : null}
</button>
);
})}
- </div>
+ </TabRow>
)}
{/* The folder row has its place from the first paint: arriving later, it pushed the filters and the cards down. */}
@@ -721,6 +720,7 @@ function Inner({ starters: given }: { starters: StarterCardData[] }) {
</div>
)}
+ <div ref={resultsRef}>
{sharedTab ? (
<SharedLinks />
) : missingFolder ? (
@@ -816,6 +816,7 @@ function Inner({ starters: given }: { starters: StarterCardData[] }) {
</div>
</div>
)}
+ </div>
{(selecting || selected.size > 0) && !uploadsTab && !sharedTab && (
<div className="pointer-events-none fixed inset-x-0 bottom-chrome z-30 flex justify-center px-3 pb-[max(1rem,env(safe-area-inset-bottom))]">
diff --git a/src/components/marketing/marketing-studio.tsx b/src/components/marketing/marketing-studio.tsx
index deb843c6..bf68aa73 100644
--- a/src/components/marketing/marketing-studio.tsx
+++ b/src/components/marketing/marketing-studio.tsx
@@ -34,6 +34,7 @@ import { EmptyIcon, MarketingHeader, useMarketingEngine } from "./shell";
import { TemplateGallery, type MediaFilter } from "./template-gallery";
import { TemplatePreview } from "./template-preview";
import { plainTagline } from "@/lib/plain-tagline";
+import { onAttr, TAB_PILL, TabRow, useSwapFade } from "@/components/ui/tab-row";
const IMAGE_FORMATS: FormatId[] = ["product-standalone", "product-with-model", "ads", "poster", "marketplace"];
const VIDEO_FORMATS: FormatId[] = ["motion-hyper", "motion-2d", "motion-mixed", "motion-saas", "ugc-talking", "tiktok"];
@@ -316,6 +317,7 @@ export function MarketingStudio({ models, starters = [] }: { models: Record<stri
const qc = useQueryClient();
const { engine, setEngine } = useMarketingEngine();
const [tab, setTab] = useState<"templates" | "generations">("templates");
+ const viewRef = useSwapFade<HTMLDivElement>(tab);
const [category, setCategory] = useState<MarketingCategory | "all">("all");
const [media, setMedia] = useState<MediaFilter>("all");
const [draft, setDraft] = useState<Draft>(BLANK);
@@ -452,14 +454,14 @@ export function MarketingStudio({ models, starters = [] }: { models: Record<stri
{!code && noProducts && <StarterSection surface="marketing" starters={starters} center compact className="mt-6 mb-4" />}
{/* Under the ready shoots, so it doesn't read as an answer to them. */}
{visitor && !code && <SelfHostNote className="mx-auto mt-3 max-w-xl text-center">Marketing Studio isn&apos;t available here.</SelfHostNote>}
- <div role="tablist" aria-label="View" className="mx-auto mt-4 flex w-fit rounded-full bg-muted p-0.5">
+ <TabRow role="tablist" aria-label="View" fade={false} className="mx-auto mt-4 w-fit">
{(["templates", "generations"] as const).map((t) => (
- <button key={t} role="tab" aria-selected={tab === t} onClick={() => setTab(t)} className={cn("h-8 rounded-full px-4 text-[13px] font-medium text-muted-foreground", tab === t && "bg-background text-foreground shadow-soft")}>
+ <button key={t} role="tab" aria-selected={tab === t} onClick={() => setTab(t)} className={TAB_PILL} {...onAttr(tab === t)}>
{t === "templates" ? "Templates" : "My generations"}
</button>
))}
- </div>
- <div className="mt-6">
+ </TabRow>
+ <div ref={viewRef} className="mt-6">
{tab === "templates" ? (
<>
{/* Once there are products of your own, the ready shoots are one row above the templates. */}
diff --git a/src/components/marketing/shell.tsx b/src/components/marketing/shell.tsx
index c55ff5ca..3e0d7d4b 100644
--- a/src/components/marketing/shell.tsx
+++ b/src/components/marketing/shell.tsx
@@ -8,7 +8,7 @@ import { EngineSwitch } from "@/components/studio/engine-switch";
import { useEngine } from "@/lib/api";
import type { Engine } from "@/lib/catalog/types";
import { useIdlePrefetch } from "@/lib/idle-prefetch";
-import { cn } from "@/lib/utils";
+import { onAttr, TAB_PILL, TabRow } from "@/components/ui/tab-row";
import { isPlainClick, useTappedTab } from "@/lib/use-tapped-tab";
export type SuiteTab = "studio" | "click" | "ads" | "multiplier";
@@ -67,23 +67,21 @@ export function MarketingHeader({
</div>
<PhoneNavButton />
</div>
- <nav ref={nav} aria-label="Marketing tools" className="scrollbar-none -mb-px flex gap-1 overflow-x-auto px-4 sm:px-6">
+ <TabRow ref={nav} as="nav" memory="marketing-suite" aria-label="Marketing tools" className="m-0 px-4 pt-0.5 pb-1.5 sm:px-6">
{TABS.map((t) => (
<Link
key={t.id}
href={t.href}
aria-current={t.id === current ? "page" : undefined}
onClick={(e) => isPlainClick(e) && tap(t.id)}
- className={cn(
- "inline-flex h-9 shrink-0 items-center gap-1.5 border-b-2 border-transparent px-2.5 text-[13px] font-medium whitespace-nowrap text-muted-foreground transition-colors hover:text-foreground",
- t.id === current && "border-primary text-foreground",
- )}
+ className={TAB_PILL}
+ {...onAttr(t.id === current)}
>
- <t.icon className="size-3.5" />
+ <t.icon />
{t.label}
</Link>
))}
- </nav>
+ </TabRow>
</header>
);
}
diff --git a/src/components/mixed-media/mixed-studio.tsx b/src/components/mixed-media/mixed-studio.tsx
index 81f06b1b..36886526 100644
--- a/src/components/mixed-media/mixed-studio.tsx
+++ b/src/components/mixed-media/mixed-studio.tsx
@@ -42,6 +42,7 @@ import type { Engine, Generation } from "@/lib/catalog/types";
import { downloadHref, downloadName } from "@/lib/library";
import type { TrimRange } from "@/lib/trim-range";
import { cn } from "@/lib/utils";
+import { onAttr, TAB_PILL, TabRow, useSwapFade } from "@/components/ui/tab-row";
import { toastError } from "@/lib/refusals";
import type { StudioExampleRow } from "@/lib/studio-examples";
import { MixedHistory } from "./history";
@@ -89,6 +90,7 @@ export function MixedStudio({
how?: StudioExampleRow;
}) {
const [tab, setTab] = useState<Tab>("presets");
+ const body = useSwapFade<HTMLDivElement>(tab);
const [engine, setEngine, engineMode] = useEngine();
// A render doesn't run on an account's own GPU or key yet (only the studios' generations do): said up front, and the
// upload, the preview and Generate are off, instead of a run the server refuses.
@@ -109,7 +111,7 @@ export function MixedStudio({
<div className="flex min-h-content min-w-0 flex-col">
<header className="max-md:sticky top-chrome z-20 flex h-14 items-center gap-2 bg-background/85 px-4 backdrop-blur sm:px-6">
<h1 className="sr-only font-heading text-[22px] leading-none sm:not-sr-only sm:truncate">Mixed Media</h1>
- <div role="tablist" aria-label="Mixed Media" onKeyDown={tabKeys} className="fade-x scrollbar-none flex h-8 min-w-0 items-center overflow-x-auto rounded-full bg-muted p-0.5 sm:ml-4">
+ <TabRow role="tablist" aria-label="Mixed Media" onKeyDown={tabKeys} follow className="sm:ml-3">
{TABS.map((t) => (
<button
key={t.id}
@@ -118,19 +120,20 @@ export function MixedStudio({
aria-selected={tab === t.id}
tabIndex={tab === t.id ? 0 : -1}
onClick={() => pick(t.id)}
- className={cn("h-7 shrink-0 rounded-full px-3 text-[13px] font-medium whitespace-nowrap text-muted-foreground transition-colors hover:text-foreground", tab === t.id && "bg-background text-foreground shadow-soft")}
+ className={TAB_PILL}
+ {...onAttr(tab === t.id)}
>
{t.label}
</button>
))}
- </div>
+ </TabRow>
<div className="ml-auto shrink-0">
{/* A phone's header has room for the tabs, not "Add key" too. */}
<EngineSwitch value={engine} onChange={setEngine} wordless selfHostedOnly />
</div>
<PhoneNavButton />
</header>
- <div className="mx-auto w-full max-w-[1240px] min-w-0 flex-1 px-4 pb-28 sm:px-6 lg:pb-16">
+ <div ref={body} className="mx-auto w-full max-w-[1240px] min-w-0 flex-1 px-4 pb-28 sm:px-6 lg:pb-16">
{tab === "history" ? (
<MixedHistory onStart={() => pick("presets")} />
) : tab === "how" ? (
diff --git a/src/components/moodboards/moodboard-panel.tsx b/src/components/moodboards/moodboard-panel.tsx
index 6e175185..0c434950 100644
--- a/src/components/moodboards/moodboard-panel.tsx
+++ b/src/components/moodboards/moodboard-panel.tsx
@@ -8,6 +8,7 @@ import { Skeleton } from "@/components/ui/skeleton";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import type { MoodboardPick } from "@/lib/catalog/palettes";
import { cn } from "@/lib/utils";
+import { onAttr, TAB_PILL, TabRow } from "@/components/ui/tab-row";
import { BoardCover, CuratedCover, StatusBadge } from "./cards";
import { CreateMoodboardDialog } from "./create-moodboard";
import { useCuratedSet, useMoodboards } from "./hooks";
@@ -42,7 +43,7 @@ export function MoodboardPanel({ value, onPick }: { value?: MoodboardPick; onPic
return (
<div className="min-w-0 space-y-2.5">
<div className="flex items-center gap-2">
- <div role="tablist" aria-label="Moodboards" className="inline-flex rounded-full bg-muted p-0.5">
+ <TabRow role="tablist" aria-label="Moodboards" fade={false}>
{(
[
["curated", "Curated"],
@@ -54,12 +55,13 @@ export function MoodboardPanel({ value, onPick }: { value?: MoodboardPick; onPic
role="tab"
aria-selected={tab === id}
onClick={() => setTab(id)}
- className={cn("h-7 rounded-full px-3 text-[12px] font-medium text-muted-foreground transition", tab === id && "bg-background text-foreground shadow-soft")}
+ className={TAB_PILL}
+ {...onAttr(tab === id)}
>
{label}
</button>
))}
- </div>
+ </TabRow>
<button
type="button"
onClick={() => setCreating(true)}
diff --git a/src/components/moodboards/moodboards-view.tsx b/src/components/moodboards/moodboards-view.tsx
index bc8cd4ef..8fe3b273 100644
--- a/src/components/moodboards/moodboards-view.tsx
+++ b/src/components/moodboards/moodboards-view.tsx
@@ -24,6 +24,7 @@ import { Skeleton } from "@/components/ui/skeleton";
import { EngineSwitch } from "@/components/studio/engine-switch";
import { useEngine } from "@/lib/api";
import { cn } from "@/lib/utils";
+import { onAttr, TAB_PILL, TabRow } from "@/components/ui/tab-row";
import { toastError } from "@/lib/refusals";
import { BoardCover, CuratedCover, StatusBadge } from "./cards";
import { CreateMoodboardDialog } from "./create-moodboard";
@@ -183,7 +184,7 @@ export function MoodboardsView() {
</PageHeader>
<div className="mb-5 flex flex-wrap items-center gap-3">
- <div role="tablist" aria-label="Moodboards" className="inline-flex rounded-full bg-muted p-0.5">
+ <TabRow role="tablist" aria-label="Moodboards" fade={false}>
{(
[
["mine", `My moodboards${data ? ` · ${data.items.length}` : ""}`],
@@ -195,12 +196,13 @@ export function MoodboardsView() {
role="tab"
aria-selected={tab === id}
onClick={() => setTab(id)}
- className={cn("h-8 rounded-full px-3.5 text-[13px] font-medium text-muted-foreground transition", tab === id && "bg-background text-foreground shadow-soft")}
+ className={TAB_PILL}
+ {...onAttr(tab === id)}
>
{label}
</button>
))}
- </div>
+ </TabRow>
<label className="flex h-9 w-full min-w-0 items-center gap-2 rounded-full border bg-background px-3 focus-within:border-primary sm:w-auto sm:max-w-xs sm:flex-1">
<Search className="size-4 text-muted-foreground" />
<input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search moodboards..." aria-label="Search moodboards" className="min-w-0 flex-1 bg-transparent text-[13px] outline-none" />
diff --git a/src/components/nav/goal-row.tsx b/src/components/nav/goal-row.tsx
index 02a2ba64..b85faa6c 100644
--- a/src/components/nav/goal-row.tsx
+++ b/src/components/nav/goal-row.tsx
@@ -9,7 +9,8 @@ import { area } from "@/lib/nav-areas";
import { NAV_ICONS } from "@/lib/nav-icons";
import { GOALS, goalBand, isNew, tapHref, type GoalId, type NavEntry, type ViewerKind } from "@/lib/nav-model";
import { cn } from "@/lib/utils";
-import { GOAL_STRIP, GOAL_TAB, GOAL_TAB_ON } from "./goal-tab";
+import { onAttr, TAB_PILL, TabRow } from "@/components/ui/tab-row";
+import { GOAL_STRIP } from "./goal-tab";
/**
* Home's goal row: six goals under the hero, each a button that opens a band of that goal's studios, one-tap presets
@@ -248,7 +249,7 @@ export function GoalRow({ names }: { names: Readonly<Record<string, string>> })
// The goal that holds the row's one tab stop (the last one focused or opened).
const [stop, setStop] = useState(0);
const buttons = useRef<(HTMLButtonElement | null)[]>([]);
- const scroller = useFadeEdges<HTMLDivElement>();
+ const scroller = useRef<HTMLDivElement>(null);
/** Scrolls the row (only the row, never the page) so a goal that sits past its edge comes fully into view. */
const reveal = (b: HTMLElement) => {
@@ -290,13 +291,7 @@ export function GoalRow({ names }: { names: Readonly<Record<string, string>> })
>
<div className={GOAL_STRIP}>
{/* A phone scrolls the goals sideways inside the row, never the page. */}
- <div
- ref={scroller}
- role="toolbar"
- aria-label="Start from a goal"
- onKeyDown={onRowKey}
- className="fade-x scrollbar-none relative flex min-w-0 flex-1 snap-x items-stretch gap-0.5 overflow-x-auto"
- >
+ <TabRow ref={scroller} role="toolbar" aria-label="Start from a goal" onKeyDown={onRowKey} className="flex-1 max-sm:mx-0 max-sm:px-4">
{GOALS.map((g, i) => {
const on = open === g.id;
const Icon = NAV_ICONS[g.icon as keyof typeof NAV_ICONS] ?? LayoutGrid;
@@ -318,27 +313,22 @@ export function GoalRow({ names }: { names: Readonly<Record<string, string>> })
setOpen(on ? null : g.id);
if (!on) reveal(e.currentTarget);
}}
- className={cn(GOAL_TAB, on && GOAL_TAB_ON)}
+ className={TAB_PILL}
+ {...onAttr(on)}
>
- <Icon aria-hidden className={cn("size-4 shrink-0 md:max-lg:hidden", on ? "text-brand-text" : "text-muted-foreground")} />
- {/* The label's bold copy keeps its width, so opening a goal never moves the ones beside it. */}
- <span className="grid">
- <span className={cn("col-start-1 row-start-1", on ? "font-semibold" : "font-medium")}>{g.label}</span>
- <span aria-hidden className="invisible col-start-1 row-start-1 font-semibold">
- {g.label}
- </span>
- </span>
+ <Icon aria-hidden />
+ {g.label}
</button>
);
})}
- </div>
+ </TabRow>
{/* Every studio and tool on one page, with covers (the bar's Studios menu is the quick way). */}
<IntentLink
href={area("studios").href}
className={cn(
- "flex shrink-0 items-center justify-center gap-2 self-center rounded-[10px] text-[13.5px] font-medium text-brand-text",
+ "flex shrink-0 items-center justify-center gap-2 self-center rounded-full text-[13.5px] font-medium text-brand-text",
// Its words from xl; narrower, its icon (with the words for screen readers) leaves the goals the room.
- "ml-1 size-11 max-sm:mr-1 xl:ml-2 xl:h-10 xl:w-auto xl:px-3",
+ "ml-1 size-11 max-sm:mr-3 xl:ml-2 xl:h-9 xl:w-auto xl:px-3.5",
FOCUS,
)}
>
diff --git a/src/components/nav/goal-tab.ts b/src/components/nav/goal-tab.ts
index 46dadae8..041d3913 100644
--- a/src/components/nav/goal-tab.ts
+++ b/src/components/nav/goal-tab.ts
@@ -1,21 +1,7 @@
/**
- * The goal row's look (Home, under the composer), shared with the area pages' section tabs so both read as one row:
- * a 52 px strip between two rules, and tabs that underline the one that is on. Plain strings, so a server component
- * can use them too.
+ * The goal row's strip (Home, under the composer): the goals as the site's tab pills (src/components/ui/tab-row.tsx),
+ * then "All studios and tools", over a rule the goal's band opens from. A plain string, so a server component can use it.
*/
-/** The strip: 52 px between two rules, reaching a phone's edges. */
-export const GOAL_STRIP = "flex h-[52px] items-stretch border-y max-sm:-mx-4";
-
-/**
- * A tab in the strip (an icon, then its label), with the nav's states (nav-states.css): the highlight on hover or keyboard
- * focus, pressed. `GOAL_TAB_ON` marks the open one with the tab's underline, never a fill, so it never reads as a second
- * highlight.
- */
-export const GOAL_TAB = [
- "nav-row flex shrink-0 snap-start items-center gap-2 rounded-t-[10px] border-b-2 border-transparent px-4 text-[14px] whitespace-nowrap text-foreground/80 nav-hover:text-foreground",
- // A tablet's row holds all six as words alone (a phone's scrolls, with the icons).
- "md:max-lg:px-2.5 md:max-lg:text-[13.5px]",
-].join(" ");
-
-export const GOAL_TAB_ON = "border-[var(--nav-mark)] text-foreground";
+/** The strip: 52 px over a rule, reaching a phone's edges. */
+export const GOAL_STRIP = "flex h-[52px] items-center border-b max-sm:-mx-4";
diff --git a/src/components/nav/search-palette.tsx b/src/components/nav/search-palette.tsx
index 14d7d82a..91f928d0 100644
--- a/src/components/nav/search-palette.tsx
+++ b/src/components/nav/search-palette.tsx
@@ -16,6 +16,7 @@ import { useModKey } from "@/lib/keys";
import { entriesFor, entry, LAUNCHER_GROUPS, launcherEntries, studioCount, visibleTo, type LauncherGroupId, type NavEntry } from "@/lib/nav-model";
import { isExternal, isThemeAction, navSearchEntries, searchNav, type NavHit, type SearchResult } from "@/lib/nav-search";
import { cn } from "@/lib/utils";
+import { onAttr, TAB_PILL, TabRow } from "@/components/ui/tab-row";
import { useViewerKind } from "./nav-ui";
import { fetchPaletteIndex, PALETTE_INDEX_KEY, type PaletteScope, type PaletteSession } from "./search-context";
import { AlsoTile, BestRow, HitRow, RecentRow, sectionHeading, StudioTile } from "./search-results";
@@ -306,16 +307,12 @@ export function PaletteBody({
studios right under them; while searching the studios come last, under their own heading. */}
{!searching && !scoped && (
<div className="shrink-0 px-5 pt-2.5 max-md:px-3">
- <div className="flex flex-wrap items-center gap-x-2.5 py-1 md:h-10 md:flex-nowrap md:py-0">
+ <div className="flex flex-wrap items-center gap-x-2.5 py-1 md:h-11 md:flex-nowrap md:py-0">
<span aria-hidden className="ml-2 text-[11px] leading-[14px] font-semibold tracking-[.08em] text-brand-text uppercase">
Every studio
</span>
<span className="text-[12px] text-muted-foreground">{groupLabel ? `${tiles.length} in ${groupLabel}` : studioCount()}</span>
- <div
- role="group"
- aria-label="Show the studios for one goal"
- className="-mx-1 flex w-full items-center gap-0.5 overflow-x-auto px-1 scrollbar-none md:ml-auto md:w-auto md:overflow-visible"
- >
+ <TabRow role="group" aria-label="Show the studios for one goal" follow className="mt-1 w-[calc(100%+8px)] md:mt-0 md:ml-auto md:w-auto md:overflow-visible">
{(["all", ...LAUNCHER_GROUPS.map((g) => g.id)] as Group[]).map((id) => {
const g = LAUNCHER_GROUPS.find((x) => x.id === id);
const on = group === id;
@@ -327,20 +324,14 @@ export function PaletteBody({
aria-label={g ? g.label : "All studios"}
onKeyDown={keepKeys}
onClick={() => setGroup(id)}
- className={cn("group/chip flex h-11 min-w-11 shrink-0 items-center justify-center rounded-full px-0.5 md:h-10", focusRing)}
+ className={TAB_PILL}
+ {...onAttr(on)}
>
- <span
- className={cn(
- "inline-flex h-7 items-center rounded-full border px-[11px] text-[12px] font-medium motion-safe:transition-colors",
- on ? "border-brand-text/40 bg-brand-faint text-brand-text" : "border-border text-muted-foreground group-hover/chip:text-foreground",
- )}
- >
- {g ? g.chip : "All"}
- </span>
+ {g ? g.chip : "All"}
</button>
);
})}
- </div>
+ </TabRow>
</div>
</div>
)}
diff --git a/src/components/nav/studios-sheet.tsx b/src/components/nav/studios-sheet.tsx
index 0600fb79..7ac96c75 100644
--- a/src/components/nav/studios-sheet.tsx
+++ b/src/components/nav/studios-sheet.tsx
@@ -7,10 +7,7 @@ import { CoverThumb } from "@/components/nav/cover-thumb";
import { useNavUi, useViewerKind } from "@/components/nav/nav-ui";
import { IntentLink } from "@/components/intent-link";
import { isNew, LAUNCHER_GROUPS, launcherActive, launcherEntries, type LauncherGroupId, type NavEntry } from "@/lib/nav-model";
-
-/** A goal chip: 32 px to look at, 44 px to tap (the row's padding holds the larger hit area). */
-const CHIP =
- "nav-focus relative h-8 min-w-11 shrink-0 rounded-full border border-border bg-secondary px-[7px] text-[12px] font-medium text-secondary-foreground after:absolute after:inset-x-0 after:-inset-y-1.5 after:content-[''] active:bg-[var(--nav-press)] aria-pressed:border-transparent aria-pressed:bg-foreground aria-pressed:text-background aria-pressed:active:bg-foreground/85 motion-safe:transition-colors";
+import { onAttr, TAB_PILL, TabRow, useSwapFade } from "@/components/ui/tab-row";
function Tile({ entry, current }: { entry: NavEntry; current: boolean }) {
const fresh = isNew(entry);
@@ -86,17 +83,19 @@ export function StudiosSheet({ group: initial, onSearch }: { group?: LauncherGro
const tiles = launcherEntries(kind, group ?? undefined);
const current = launcherActive(pathname);
const chips: { id: LauncherGroupId | null; label: string }[] = [{ id: null, label: "All" }, ...LAUNCHER_GROUPS.map((g) => ({ id: g.id, label: g.chip }))];
+ // A goal tapped: its studios fade in (they are there at once).
+ const tilesRef = useSwapFade<HTMLDivElement>(group);
return (
<>
<Shortcuts onSearch={onSearch} />
- <div role="group" aria-label="Show the studios for one goal" className="flex shrink-0 gap-1 overflow-x-auto px-4 py-1.5 scrollbar-none">
+ <TabRow role="group" aria-label="Show the studios for one goal" follow className="m-0 shrink-0 px-4 py-1.5">
{chips.map((c) => (
- <button key={c.id ?? "all"} type="button" aria-pressed={group === c.id} className={CHIP} onClick={() => setGroup(c.id)}>
+ <button key={c.id ?? "all"} type="button" aria-pressed={group === c.id} className={TAB_PILL} {...onAttr(group === c.id)} onClick={() => setGroup(c.id)}>
{c.label}
</button>
))}
- </div>
- <div className="min-h-0 flex-1 overflow-y-auto overscroll-contain px-4">
+ </TabRow>
+ <div ref={tilesRef} className="min-h-0 flex-1 overflow-y-auto overscroll-contain px-4">
<ul aria-label={group ? LAUNCHER_GROUPS.find((g) => g.id === group)?.label : "All studios"} className="grid grid-cols-5 gap-x-1 gap-y-0.5 pb-1">
{tiles.map((e) => (
<Tile key={e.id} entry={e} current={e.id === current} />
diff --git a/src/components/photodump/photodump-view.tsx b/src/components/photodump/photodump-view.tsx
index 38c2e401..28fbf023 100644
--- a/src/components/photodump/photodump-view.tsx
+++ b/src/components/photodump/photodump-view.tsx
@@ -18,6 +18,7 @@ import { customPack, DEFAULT_ASPECT, MAX_PACK_REFS, MAX_SELFIE_MB, PACKS, PHOTOD
import type { Generation } from "@/lib/catalog/types";
import { timeAgo } from "@/lib/format";
import { cn } from "@/lib/utils";
+import { onAttr, TAB_PILL, TabRow } from "@/components/ui/tab-row";
import { toastError } from "@/lib/refusals";
import { PackCover } from "./covers";
import { useRun, useRunPreview, usePackActions, useUserPacks } from "./hooks";
@@ -236,13 +237,13 @@ export function PhotodumpView() {
{step === 0 && (
<section aria-label="Choose a pack" className="space-y-4">
<div className="flex flex-wrap items-center gap-3">
- <div role="tablist" aria-label="Packs" className="scrollbar-none inline-flex max-w-full overflow-x-auto rounded-full bg-muted p-0.5">
+ <TabRow role="tablist" aria-label="Packs" follow className="max-w-full">
{TABS.map(([id, label]) => (
- <button key={id} role="tab" aria-selected={tab === id} onClick={() => setTab(id)} className={cn("h-8 shrink-0 rounded-full px-3 text-[13px] font-medium text-muted-foreground transition", tab === id && "bg-background text-foreground shadow-soft")}>
+ <button key={id} role="tab" aria-selected={tab === id} onClick={() => setTab(id)} className={TAB_PILL} {...onAttr(tab === id)}>
{label}
</button>
))}
- </div>
+ </TabRow>
<label className="flex h-9 w-full min-w-0 items-center gap-2 rounded-full border bg-background px-3 focus-within:border-primary sm:w-auto sm:max-w-xs sm:flex-1">
<Search className="size-4 text-muted-foreground" />
<input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search packs" aria-label="Search packs" className="min-w-0 flex-1 bg-transparent text-[13px] outline-none" />
diff --git a/src/components/preset-gallery.tsx b/src/components/preset-gallery.tsx
index d974c3c5..bb2c23ff 100644
--- a/src/components/preset-gallery.tsx
+++ b/src/components/preset-gallery.tsx
@@ -7,7 +7,7 @@ import { CardPending, IntentLink } from "@/components/intent-link";
import { PRESET_ICONS } from "@/components/preset-icons";
import { PresetPreview, usePreviewPlayback } from "@/components/preset-preview";
import { GALLERY_GRID } from "@/components/skeletons";
-import { useFadeEdges } from "@/components/use-fade-edges";
+import { onAttr, TAB_PILL, TabRow, useFadeOn } from "@/components/ui/tab-row";
import { useProgressive } from "@/components/use-progressive";
import { CardChip, badgeKey, parseBadgeKey } from "@/components/gpu/readiness-chip";
import { useGpuBadges } from "@/hooks/use-gpu";
@@ -274,8 +274,9 @@ export function PresetGallery({
// Cards render a page at a time; a new filter starts from the first page again.
const { shown, hasMore, moreFrom, sentinel, left } = useProgressive(list.length, `${cat}|${query}|${runsOn}`, FIRST_PAGE, PAGE);
const grid = useRef<HTMLDivElement>(null);
+ // A category tapped: its cards fade in (they are there at once).
+ useFadeOn(grid, cat);
- const strip = useFadeEdges<HTMLDivElement>();
const stale = q.trim().toLowerCase() !== query;
const lead = (leading ?? []).filter((c) => cat === "All" && runsOn !== "cloud" && (!query || matchesSearch(`${c.title} ${c.line} ${c.words ?? ""}`.toLowerCase(), query)));
// One fetch of the viewer's chips (the GPU pre-flight); each card gets one string.
@@ -324,12 +325,11 @@ export function PresetGallery({
to see what runs on it.
</p>
)}
- <div
- ref={strip}
+ <TabRow
role="group"
aria-label="Categories"
// From sm up every category shows (wrapped): a mouse can't scroll a row whose scrollbar is hidden.
- className="fade-x scrollbar-none -mx-1 flex snap-x scroll-px-1 gap-1 overflow-x-auto px-1 sm:flex-wrap sm:overflow-visible"
+ className="sm:flex-wrap sm:overflow-visible"
>
{cats.map((c) => (
<button
@@ -341,15 +341,13 @@ export function PresetGallery({
setCat(c);
e.currentTarget.scrollIntoView({ block: "nearest", inline: "nearest", behavior: "smooth" });
}}
- className={cn(
- "h-8 shrink-0 snap-start rounded-full px-3 text-[13px] font-medium whitespace-nowrap text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",
- cat === c && "bg-secondary text-foreground",
- )}
+ className={TAB_PILL}
+ {...onAttr(cat === c)}
>
{c}
</button>
))}
- </div>
+ </TabRow>
</div>
{list.length || lead.length ? (
<>
diff --git a/src/components/shorts/shorts-studio.tsx b/src/components/shorts/shorts-studio.tsx
index 05baeca0..28650b95 100644
--- a/src/components/shorts/shorts-studio.tsx
+++ b/src/components/shorts/shorts-studio.tsx
@@ -32,6 +32,7 @@ import type { Engine } from "@/lib/catalog/types";
import type { TrimRange } from "@/lib/trim-range";
import { keepOffered, offered } from "@/lib/model-access";
import { cn } from "@/lib/utils";
+import { onAttr, TAB_PILL, TabRow, useSwapFade } from "@/components/ui/tab-row";
import { toastError } from "@/lib/refusals";
import { CustomPresetDialog } from "./custom-preset-dialog";
import { useShortsActions, useShortsEstimate, useShortsPresets, useSubmitGuard, type ShortsBody } from "./hooks";
@@ -49,6 +50,7 @@ const CUSTOM = "Created by you";
/** Shorts Studio: choose a preset → upload and trim a clip → generate a session (then /shorts/[id]). */
export function ShortsStudio({ models }: { models: Record<Engine, ModelChoice[]> }) {
const [tab, setTab] = useState<"presets" | "history">("presets");
+ const body = useSwapFade<HTMLDivElement>(tab);
const [engine, setEngine] = useEngine();
// Restyle models switched off in Settings → Models & licences leave the menu (the default is the first one on).
const access = useModelAccess();
@@ -87,7 +89,7 @@ export function ShortsStudio({ models }: { models: Record<Engine, ModelChoice[]>
<div className="flex min-h-content min-w-0 flex-col">
<header className="max-md:sticky top-chrome z-20 flex h-14 items-center gap-2 bg-background/85 px-4 backdrop-blur sm:px-6">
<h1 className="min-w-0 truncate font-heading text-[22px] leading-none">Shorts Studio</h1>
- <div role="tablist" aria-label="Shorts Studio" onKeyDown={tabKeys} className="ml-2 flex h-8 shrink-0 items-center rounded-full bg-muted p-0.5 sm:ml-4">
+ <TabRow role="tablist" aria-label="Shorts Studio" onKeyDown={tabKeys} fade={false} className="ml-1 shrink-0 sm:ml-3">
{(["presets", "history"] as const).map((t) => (
<button
key={t}
@@ -96,19 +98,20 @@ export function ShortsStudio({ models }: { models: Record<Engine, ModelChoice[]>
aria-selected={tab === t}
tabIndex={tab === t ? 0 : -1}
onClick={() => pickTab(t)}
- className={cn("h-7 rounded-full px-3 text-[13px] font-medium text-muted-foreground transition-colors hover:text-foreground", tab === t && "bg-background text-foreground shadow-soft")}
+ className={TAB_PILL}
+ {...onAttr(tab === t)}
>
{t === "presets" ? "Presets" : "History"}
</button>
))}
- </div>
+ </TabRow>
<div className="ml-auto shrink-0">
{/* A phone's header has room for the title and the tabs, not "Add key" too. */}
<EngineSwitch value={engine} onChange={setEngine} wordless selfHostedOnly />
</div>
<PhoneNavButton />
</header>
- <div className="mx-auto w-full max-w-[1240px] min-w-0 flex-1 px-4 pb-28 sm:px-6 lg:pb-16">
+ <div ref={body} className="mx-auto w-full max-w-[1240px] min-w-0 flex-1 px-4 pb-28 sm:px-6 lg:pb-16">
{tab === "history" ? (
<ShortsHistory onStart={() => pickTab("presets")} />
) : (
@@ -239,6 +242,7 @@ function PresetGrid({
}) {
const [q, setQ] = useState("");
const [cat, setCat] = useState<string>("All");
+ const grid = useSwapFade<HTMLDivElement>(cat);
const query = useDeferredValue(q.trim().toLowerCase());
const cats = ["All", ...(custom.length ? [CUSTOM] : []), ...SHORTS_CATEGORIES];
const list = useMemo(
@@ -271,20 +275,14 @@ function PresetGrid({
)}
</div>
</div>
- <div role="group" aria-label="Categories" className="fade-x scrollbar-none -mx-1 flex gap-1 overflow-x-auto px-1">
+ <TabRow role="group" aria-label="Categories" follow>
{cats.map((c) => (
- <button
- key={c}
- type="button"
- aria-pressed={cat === c}
- onClick={() => setCat(c)}
- className={cn("h-8 shrink-0 rounded-full px-3 text-[13px] font-medium whitespace-nowrap text-muted-foreground transition-colors hover:bg-accent hover:text-foreground", cat === c && "bg-secondary text-foreground")}
- >
+ <button key={c} type="button" aria-pressed={cat === c} onClick={() => setCat(c)} className={TAB_PILL} {...onAttr(cat === c)}>
{c}
</button>
))}
- </div>
- <div className="grid grid-cols-2 gap-1 sm:grid-cols-3 xl:grid-cols-4">
+ </TabRow>
+ <div ref={grid} className="grid grid-cols-2 gap-1 sm:grid-cols-3 xl:grid-cols-4">
{onCreate && !query && (cat === "All" || cat === CUSTOM) && <CreateCard onClick={onCreate} />}
{mine.map((p) => (
<CustomCard key={p.id} {...p} selected={presetId === p.id} onSelect={onSelect} onEdit={onEdit} />
diff --git a/src/components/studio/hub-chrome.tsx b/src/components/studio/hub-chrome.tsx
index 6c5d86d1..22e4cd2d 100644
--- a/src/components/studio/hub-chrome.tsx
+++ b/src/components/studio/hub-chrome.tsx
@@ -9,9 +9,8 @@ import { EngineSwitch } from "@/components/studio/engine-switch";
import { useEngine, useLikelyVisitor } from "@/lib/api";
import { HUB_MODES, HUB_TITLE, hubOfPath, modeHref, modeOfPath, type HubKind } from "@/lib/hubs";
import { prefetchOptions, useIdlePrefetch } from "@/lib/idle-prefetch";
-import { cn } from "@/lib/utils";
import { isPlainClick, useTappedTab } from "@/lib/use-tapped-tab";
-import { useEdgeFade } from "./use-edge-fade";
+import { onAttr, reducedMotion, TAB_PILL, TabRow } from "@/components/ui/tab-row";
/**
* The frame of a hub (Audio, Video tools, Upscale): the sticky title bar and the mode tabs live in the hub's layout, shared
@@ -101,7 +100,7 @@ function HubTabs({
onWaiting?: (waiting: boolean) => void;
}) {
const router = useRouter();
- const [ref, fade] = useEdgeFade<HTMLDivElement>();
+ const ref = useRef<HTMLElement>(null);
const activeRef = useRef<HTMLAnchorElement>(null);
const visitor = useLikelyVisitor();
// The tab just tapped: the current one from the next frame on, until the route moves (then the path says).
@@ -138,7 +137,7 @@ function HubTabs({
return (
<nav aria-label="Modes" className="border-b">
- <div ref={ref} style={fade} className="scrollbar-none flex gap-1 overflow-x-auto px-4 sm:px-6">
+ <TabRow ref={ref} className="m-0 px-4 py-1.5 sm:px-6">
{modes.map((m) => {
const on = m.id === active;
const href = modeHref(kind, m.id);
@@ -154,18 +153,15 @@ function HubTabs({
// A new tab or window (modifier, middle button) leaves this page as it is.
onClick={(e) => isPlainClick(e) && tap(m.id)}
aria-current={on ? "page" : undefined}
- className={cn(
- "relative flex h-11 shrink-0 items-center rounded-md px-2.5 text-[13px] font-medium whitespace-nowrap text-muted-foreground transition-colors outline-none hover:text-foreground focus-visible:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset",
- "after:absolute after:inset-x-2.5 after:bottom-0 after:h-0.5 after:rounded-full focus-visible:after:bg-ring",
- on && "text-foreground after:bg-foreground",
- )}
+ className={TAB_PILL}
+ {...onAttr(on)}
>
{m.label}
<TabWaiting onWaiting={onWaiting} />
</Link>
);
})}
- </div>
+ </TabRow>
</nav>
);
}
@@ -176,6 +172,23 @@ function PathTabs({ kind, onActive, onWaiting }: { kind: HubKind; onActive: (mod
return <HubTabs kind={kind} pathname={pathname} onActive={onActive} onWaiting={onWaiting} />;
}
+/**
+ * The hub body fades in when a mode's page arrives (the path changes with it): the page is there in that frame and only
+ * its opacity eases, so a switch is never slower. Inside Suspense (the path is runtime data while a route prerenders).
+ */
+function PathFade({ body }: { body: React.RefObject<HTMLDivElement | null> }) {
+ const pathname = usePathname();
+ const last = useRef(pathname);
+ useLayoutEffect(() => {
+ if (last.current === pathname) return;
+ last.current = pathname;
+ const el = body.current;
+ if (!el || reducedMotion() || typeof el.animate !== "function") return;
+ el.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 200, easing: "cubic-bezier(0.25, 0.8, 0.25, 1)" });
+ }, [pathname, body]);
+ return null;
+}
+
/** How long a tapped tab's page may keep the old one on screen before the skeleton replaces it. */
export const HUB_SKELETON_AFTER_MS = 60;
@@ -207,6 +220,7 @@ export function HubFrame({ kind, skeleton, children }: { kind: HubKind; skeleton
}, [waiting]);
// `waiting` ends before paint when the page arrives, so the skeleton never covers the new page.
const skeletonShown = waiting && late;
+ const body = useRef<HTMLDivElement>(null);
return (
<div className="flex min-h-content min-w-0 flex-col" data-hub={kind}>
<div className="max-md:sticky top-chrome z-20 bg-background/85 backdrop-blur" data-hub-chrome>
@@ -223,7 +237,10 @@ export function HubFrame({ kind, skeleton, children }: { kind: HubKind; skeleton
</Suspense>
</div>
<HubCtx.Provider value={store}>
- <div className="flex min-w-0 flex-1 flex-col" data-hub-body>
+ <Suspense fallback={null}>
+ <PathFade body={body} />
+ </Suspense>
+ <div ref={body} className="flex min-w-0 flex-1 flex-col" data-hub-body>
{skeletonShown && skeleton}
<div className={skeletonShown ? "hidden" : "contents"}>{children}</div>
</div>
diff --git a/src/components/studio/media-slot.tsx b/src/components/studio/media-slot.tsx
index aa556048..17996677 100644
--- a/src/components/studio/media-slot.tsx
+++ b/src/components/studio/media-slot.tsx
@@ -14,6 +14,7 @@ import { postFile } from "@/lib/upload";
import type { MediaKind } from "@/lib/catalog/types";
import { slotCaption } from "@/lib/composer";
import { cn } from "@/lib/utils";
+import { onAttr, TAB_PILL, TabRow } from "@/components/ui/tab-row";
import type { SketchMode, Stroke } from "./sketch-editor";
export interface SlotValue {
@@ -151,19 +152,20 @@ export function LibraryGrid({ kinds, onPick }: { kinds: MediaKind[]; onPick: (v:
return (
<div className="space-y-2">
{kinds.length > 1 && (
- <div role="tablist" aria-label="Kind" className="inline-flex rounded-full bg-muted p-0.5">
+ <TabRow role="tablist" aria-label="Kind" fade={false} className="w-fit">
{kinds.map((k) => (
<button
key={k}
role="tab"
aria-selected={k === kind}
onClick={() => setKind(k)}
- className={cn("h-7 rounded-full px-3 text-[12px] font-medium text-muted-foreground capitalize transition", k === kind && "bg-background text-foreground shadow-soft")}
+ className={cn(TAB_PILL, "capitalize")}
+ {...onAttr(k === kind)}
>
{k === "image" ? "Images" : k === "video" ? "Videos" : k === "audio" ? "Audio" : k}
</button>
))}
- </div>
+ </TabRow>
)}
{assets.isLoading ? (
<div className="grid h-40 place-items-center">
diff --git a/src/components/studio/preset-chips.tsx b/src/components/studio/preset-chips.tsx
index 3de22366..5a7fc32e 100644
--- a/src/components/studio/preset-chips.tsx
+++ b/src/components/studio/preset-chips.tsx
@@ -8,6 +8,7 @@ import type { Preset } from "@/lib/catalog/types";
import { presetCover } from "@/lib/preset-covers";
import { featuredAll } from "@/lib/preset-featured";
import { cn } from "@/lib/utils";
+import { onAttr, TAB_PILL, TabRow } from "@/components/ui/tab-row";
import { CoverScrollBox, CoverTile, usePickerPlayback } from "@/components/cover-tile";
import { PRESET_ICONS } from "@/components/preset-icons";
import { loadFullCatalog, useCatalog } from "./catalog";
@@ -57,19 +58,13 @@ export function PresetGrid({ list, value, onPick, noneLabel }: { list: Preset[]
const cats = ["All", ...new Set(list.map((p) => p.category))];
return (
<>
- <div className="scrollbar-none mb-2 flex shrink-0 gap-1 overflow-x-auto" role="tablist" aria-label="Categories">
+ <TabRow className="mb-1 shrink-0" role="tablist" aria-label="Categories" follow>
{cats.map((c) => (
- <button
- key={c}
- role="tab"
- aria-selected={cat === c}
- onClick={() => setCat(c)}
- className={cn("h-7 shrink-0 rounded-full px-2.5 text-[12px] font-medium text-muted-foreground hover:bg-accent", cat === c && "bg-secondary text-foreground")}
- >
+ <button key={c} role="tab" aria-selected={cat === c} onClick={() => setCat(c)} className={TAB_PILL} {...onAttr(cat === c)}>
{c}
</button>
))}
- </div>
+ </TabRow>
<CoverScrollBox value={box}>
{/* The box scrolls and gives way in the picker (min-h-0); the grid inside keeps its rows whole. */}
<div ref={box} className="max-h-[28rem] min-h-0 overflow-y-auto overscroll-contain">
diff --git a/src/components/swap-studio/workbench.tsx b/src/components/swap-studio/workbench.tsx
index e750188d..dff35499 100644
--- a/src/components/swap-studio/workbench.tsx
+++ b/src/components/swap-studio/workbench.tsx
@@ -13,6 +13,7 @@ import { EngineSwitch } from "@/components/studio/engine-switch";
import { uploadFile } from "@/lib/api";
import { clipExtension, clipNeedsPreview, clipProblem, jobState, MODE_LABELS, pageClip, secondsLabel, SWAP_STUDIO, type GenSummary, type StudioEstimate, type SwapClip, type SwapProject, type SwapShot } from "@/lib/catalog/swap-studio";
import { cn } from "@/lib/utils";
+import { onAttr, TAB_PILL, TabRow } from "@/components/ui/tab-row";
import { toastError } from "@/lib/refusals";
import { decisionsHref, useAddClip, usePrepareClip, useSwapEdit, useSwapEstimate, useSwapProject, type EditInput } from "./hooks";
import { GenChip, JobError, Note, priceText, SavedText } from "./parts";
@@ -175,7 +176,7 @@ export function SwapWorkbench({ id }: { id: string }) {
) : (
<section aria-label={`Clip ${clip.name}`} className="min-w-0 space-y-3">
<ClipHeader {...props} />
- <div role="tablist" aria-label="Stages" onKeyDown={tabKeys} className="-mx-1 flex gap-1 overflow-x-auto px-1 pb-1">
+ <TabRow role="tablist" aria-label="Stages" onKeyDown={tabKeys} follow>
{STAGES.map((s) => (
<button
key={s.id}
@@ -186,15 +187,13 @@ export function SwapWorkbench({ id }: { id: string }) {
aria-controls={`${tabsId}-panel`}
tabIndex={stage === s.id ? 0 : -1}
onClick={() => setStage(s.id)}
- className={cn(
- "h-8 shrink-0 rounded-full px-3 text-[13px] font-medium whitespace-nowrap transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring",
- stage === s.id ? "bg-foreground text-background" : "bg-muted text-muted-foreground hover:text-foreground",
- )}
+ className={TAB_PILL}
+ {...onAttr(stage === s.id)}
>
{s.label}
</button>
))}
- </div>
+ </TabRow>
{stage !== "shots" && stage !== "words" && stage !== "assemble" && <ShotStrip clip={clip} shot={shot} onPick={setShotId} gens={v.gens} />}
<div role="tabpanel" id={`${tabsId}-panel`} aria-labelledby={`${tabsId}-${stage}`} className="min-w-0">
{stage === "shots" && <ShotsStage key={clip.id} {...props} />}
diff --git a/src/components/ui/tab-row.tsx b/src/components/ui/tab-row.tsx
new file mode 100644
index 00000000..8033d405
--- /dev/null
+++ b/src/components/ui/tab-row.tsx
@@ -0,0 +1,231 @@
+"use client";
+
+import { forwardRef, useCallback, useEffect, useImperativeHandle, useLayoutEffect, useRef } from "react";
+import { cn } from "@/lib/utils";
+
+/*
+ * One look for every row of tabs or chips (src/app/tab-row.css): a `TabRow` holds `tabPill` items, and the selected one
+ * carries `data-on` (`onAttr(on)`). The row adds the fill that slides from the old selection to the new one, keeps
+ * hover from lighting a pill the page scrolled under a resting mouse, and fades its edges while it scrolls sideways.
+ * Each row keeps its own behaviour: links or buttons, roles, keys.
+ */
+
+/** A tab or chip in a row. */
+export const TAB_PILL = "tab-pill";
+
+/** The class of a row (for a row that is not a TabRow, such as a Radix TabsList). */
+export const TAB_ROW = "tab-row";
+
+/** The selected pill: marked data-on, or data-state="active" (a Radix tab). */
+const ON = ".tab-pill[data-on], .tab-pill[data-state=\"active\"]";
+
+/** The selected item's mark: spread on the item (`{...onAttr(on)}`). */
+export const onAttr = (on: boolean) => (on ? { "data-on": "" } : {});
+
+const useIsoLayoutEffect = typeof window === "undefined" ? useEffect : useLayoutEffect;
+
+export const reducedMotion = () => typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
+
+/**
+ * The sliding fill of a row: put on the row element (it renders `<TabIndicator />` inside). It follows the item marked
+ * `data-on`, also when the mark moves by itself (a scroll-spy) or a pill changes size (fonts loading).
+ */
+export function useTabIndicator(row: React.RefObject<HTMLElement | null>, { follow = false, memory }: { follow?: boolean; memory?: string } = {}) {
+ useIsoLayoutEffect(() => {
+ const el = row.current;
+ if (!el) return;
+ let placed = false;
+ let lastOn: Element | null = null;
+ // A row drawn again by the next page (a suite whose pages each draw the header): the fill starts where it was left.
+ const from = memory ? REMEMBERED.get(memory) : undefined;
+ if (from) {
+ setVars(el, from);
+ el.setAttribute("data-ind", "");
+ placed = true;
+ lastOn = el;
+ }
+ let raf = 0;
+ const place = () => {
+ raf = 0;
+ const on = el.querySelector<HTMLElement>(ON);
+ if (!on || !on.checkVisibility()) {
+ el.removeAttribute("data-ind");
+ lastOn = null;
+ return;
+ }
+ const r = el.getBoundingClientRect();
+ const p = on.getBoundingClientRect();
+ if (!p.width) return;
+ const x = Math.round(p.left - r.left - el.clientLeft + el.scrollLeft);
+ const y = Math.round(p.top - r.top - el.clientTop + el.scrollTop);
+ const w = Math.round(p.width);
+ const h = Math.round(p.height);
+ // Slides only from one pill to another; the first placing (and a pill that only resized) just sets it.
+ const moving = placed && lastOn !== null && lastOn !== on && !reducedMotion();
+ if (moving && !el.hasAttribute("data-ind-moving")) {
+ // The old place has to be drawn once before the transition can start from it.
+ void el.offsetWidth;
+ }
+ el.toggleAttribute("data-ind-moving", moving);
+ setVars(el, { x, y, w, h });
+ if (memory) REMEMBERED.set(memory, { x, y, w, h });
+ el.setAttribute("data-ind", "");
+ if (follow && lastOn !== on && el.scrollWidth > el.clientWidth + 1) {
+ // The selected pill stays in sight in a row that scrolls sideways (only the row moves, never the page).
+ const left = x - (el.clientWidth - w) / 2;
+ el.scrollTo({ left: Math.max(0, left), behavior: placed && !reducedMotion() ? "smooth" : "auto" });
+ }
+ placed = true;
+ lastOn = on;
+ };
+ const schedule = () => {
+ if (!raf) raf = requestAnimationFrame(place);
+ };
+ place();
+ const mo = new MutationObserver((list) => {
+ // A new selection is placed in this frame (before paint), so the old fill never lingers for a frame.
+ if (list.some((m) => m.type === "attributes" || m.addedNodes.length || m.removedNodes.length)) {
+ if (raf) cancelAnimationFrame(raf);
+ place();
+ }
+ });
+ mo.observe(el, { subtree: true, childList: true, attributes: true, attributeFilter: ["data-on", "data-state", "hidden", "class"] });
+ const ro = new ResizeObserver(schedule);
+ ro.observe(el);
+ for (const p of el.querySelectorAll(".tab-pill")) ro.observe(p);
+ const onEnd = (e: TransitionEvent) => {
+ if (e.propertyName === "transform") el.removeAttribute("data-ind-moving");
+ };
+ el.addEventListener("transitionend", onEnd);
+ return () => {
+ if (raf) cancelAnimationFrame(raf);
+ mo.disconnect();
+ ro.disconnect();
+ el.removeEventListener("transitionend", onEnd);
+ };
+ }, [row, follow, memory]);
+}
+
+interface Place {
+ x: number;
+ y: number;
+ w: number;
+ h: number;
+}
+
+/** Where each remembered row last had its fill. */
+const REMEMBERED = new Map<string, Place>();
+
+function setVars(el: HTMLElement, { x, y, w, h }: Place) {
+ el.style.setProperty("--ti-x", `${x}px`);
+ el.style.setProperty("--ti-y", `${y}px`);
+ el.style.setProperty("--ti-h", `${h}px`);
+ el.style.setProperty("--ti-r", `${x + w - h / 2}px`);
+ el.style.setProperty("--ti-s", `${Math.max(0, w - h) / 100}`);
+}
+
+/** The fill that slides under the selected pill (inside a row that uses useTabIndicator). */
+export function TabIndicator() {
+ return (
+ <span aria-hidden className="tab-ind">
+ <span />
+ <span />
+ <span />
+ </span>
+ );
+}
+
+/**
+ * A row scrolled under a resting mouse (the page moving, the mouse still) lights no pill: hover waits until the mouse
+ * moves again. Also marks the ends of a row that scrolls sideways (.fade-x), when `fade` is on.
+ */
+function useRowHoverAndEdges(row: React.RefObject<HTMLElement | null>, fade: boolean) {
+ useEffect(() => {
+ const el = row.current;
+ if (!el) return;
+ let still = false;
+ const onScroll = () => {
+ if (still) return;
+ still = true;
+ el.setAttribute("data-still", "");
+ };
+ const onMove = () => {
+ if (!still) return;
+ still = false;
+ el.removeAttribute("data-still");
+ };
+ window.addEventListener("scroll", onScroll, { passive: true });
+ el.addEventListener("pointermove", onMove, { passive: true });
+ let ro: ResizeObserver | undefined;
+ const edges = () => {
+ el.toggleAttribute("data-fade-start", el.scrollLeft > 2);
+ el.toggleAttribute("data-fade-end", el.scrollLeft + el.clientWidth < el.scrollWidth - 2);
+ };
+ if (fade) {
+ edges();
+ el.addEventListener("scroll", edges, { passive: true });
+ ro = new ResizeObserver(edges);
+ ro.observe(el);
+ }
+ return () => {
+ window.removeEventListener("scroll", onScroll);
+ el.removeEventListener("pointermove", onMove);
+ el.removeEventListener("scroll", edges);
+ ro?.disconnect();
+ };
+ }, [row, fade]);
+}
+
+type RowProps = React.HTMLAttributes<HTMLElement> & {
+ /** The element: a `nav` for links to pages or sections, a `div` (default) for tabs or chips. */
+ as?: "div" | "nav" | "ul";
+ /** Keep the selected pill in sight when the row scrolls sideways. */
+ follow?: boolean;
+ /** Fade the row's ends while there is more past them (a row that scrolls sideways). */
+ fade?: boolean;
+ /** A name for a row each page draws again: its fill slides on from where the last page left it. */
+ memory?: string;
+};
+
+/** A row of tabs or chips: one look, a fill that slides to the selected pill, and no hover left behind by a scroll. */
+export const TabRow = forwardRef<HTMLElement, RowProps>(function TabRow({ as = "div", follow, fade = true, memory, className, children, ...props }, ref) {
+ const own = useRef<HTMLElement | null>(null);
+ useImperativeHandle(ref, () => own.current as HTMLElement);
+ useTabIndicator(own, { follow, memory });
+ useRowHoverAndEdges(own, fade);
+ const set = useCallback((el: HTMLElement | null) => {
+ own.current = el;
+ }, []);
+ const Tag = as as "div";
+ return (
+ <Tag ref={set as React.Ref<HTMLDivElement>} data-tab-row="" className={cn(TAB_ROW, fade && "fade-x", className)} {...(props as React.HTMLAttributes<HTMLDivElement>)}>
+ <TabIndicator />
+ {children}
+ </Tag>
+ );
+});
+
+/**
+ * Fades a content area in when what it shows changes (a mode tab, a chip that filters a grid): the new content is there
+ * at once and only its opacity eases, so a switch is never slower. Nothing on the first render or with reduced motion.
+ */
+export function useSwapFade<T extends HTMLElement>(key: unknown) {
+ const ref = useRef<T>(null);
+ useFadeOn(ref, key);
+ return ref;
+}
+
+/** useSwapFade on an element that already has a ref. */
+export function useFadeOn(ref: React.RefObject<HTMLElement | null>, key: unknown) {
+ const first = useRef(true);
+ useIsoLayoutEffect(() => {
+ if (first.current) {
+ first.current = false;
+ return;
+ }
+ const el = ref.current;
+ // null: the content is still the old one (its replacement is on the way); it fades when the new one comes.
+ if (key === null || !el || reducedMotion() || typeof el.animate !== "function") return;
+ el.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 200, easing: "cubic-bezier(0.25, 0.8, 0.25, 1)" });
+ }, [key, ref]);
+}
diff --git a/src/components/ui/tabs.tsx b/src/components/ui/tabs.tsx
index b1705f8f..021d1571 100644
--- a/src/components/ui/tabs.tsx
+++ b/src/components/ui/tabs.tsx
@@ -4,6 +4,7 @@ import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "cn"
import { Tabs as TabsPrimitive } from "radix-ui"
+import { TAB_PILL, TAB_ROW, TabIndicator, useTabIndicator } from "@/components/ui/tab-row"
function Tabs({
className,
@@ -23,13 +24,17 @@ function Tabs({
)
}
+/*
+ * The site's one look for tabs (src/components/ui/tab-row.tsx, src/app/tab-row.css): pills in a row, the selected one
+ * with a soft fill that slides between them. Both variants look the same; the prop stays for older callers.
+ */
const tabsListVariants = cva(
- "group/tabs-list inline-flex w-fit items-center justify-center rounded-lg p-[3px] text-muted-foreground group-data-horizontal/tabs:h-8 group-data-vertical/tabs:h-fit group-data-vertical/tabs:flex-col data-[variant=line]:rounded-none",
+ `${TAB_ROW} w-fit group-data-vertical/tabs:flex-col group-data-vertical/tabs:items-stretch`,
{
variants: {
variant: {
- default: "bg-muted",
- line: "gap-1 bg-transparent",
+ default: "",
+ line: "",
},
},
defaultVariants: {
@@ -41,16 +46,23 @@ const tabsListVariants = cva(
function TabsList({
className,
variant = "default",
+ children,
...props
}: React.ComponentProps<typeof TabsPrimitive.List> &
VariantProps<typeof tabsListVariants>) {
+ const ref = React.useRef<HTMLDivElement>(null)
+ useTabIndicator(ref)
return (
<TabsPrimitive.List
+ ref={ref}
data-slot="tabs-list"
data-variant={variant}
className={cn(tabsListVariants({ variant }), className)}
{...props}
- />
+ >
+ <TabIndicator />
+ {children}
+ </TabsPrimitive.List>
)
}
@@ -62,10 +74,8 @@ function TabsTrigger({
<TabsPrimitive.Trigger
data-slot="tabs-trigger"
className={cn(
- "relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-1.5 py-0.5 text-sm font-medium whitespace-nowrap text-foreground/60 transition-all group-data-vertical/tabs:w-full group-data-vertical/tabs:justify-start hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-50 has-data-[icon=inline-end]:pr-1 has-data-[icon=inline-start]:pl-1 dark:text-muted-foreground dark:hover:text-foreground group-data-[variant=default]/tabs-list:data-active:shadow-sm group-data-[variant=line]/tabs-list:data-active:shadow-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
- "group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-active:bg-transparent dark:group-data-[variant=line]/tabs-list:data-active:border-transparent dark:group-data-[variant=line]/tabs-list:data-active:bg-transparent",
- "data-active:bg-background data-active:text-foreground dark:data-active:border-input dark:data-active:bg-input/30 dark:data-active:text-foreground",
- "after:absolute after:bg-foreground after:opacity-0 after:transition-opacity group-data-horizontal/tabs:after:inset-x-0 group-data-horizontal/tabs:after:bottom-[-5px] group-data-horizontal/tabs:after:h-0.5 group-data-vertical/tabs:after:inset-y-0 group-data-vertical/tabs:after:-right-1 group-data-vertical/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-active:after:opacity-100",
+ TAB_PILL,
+ "group-data-vertical/tabs:w-full group-data-vertical/tabs:justify-start",
className
)}
{...props}
diff --git a/src/lib/glide-scroll.ts b/src/lib/glide-scroll.ts
new file mode 100644
index 00000000..a76812e6
--- /dev/null
+++ b/src/lib/glide-scroll.ts
@@ -0,0 +1,78 @@
+/*
+ * 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
+ * scroll-margin-top). A long way starts nearer, so the page never races past screens of pictures. The target is
+ * measured again every frame, so content that settles above it on the way can't make the end jump. Any wheel, touch,
+ * key or press stops it where it is. Reduced motion: an instant jump.
+ */
+
+const ease = (t: number) => 1 - Math.pow(1 - t, 3);
+
+/** How long a glide over `distance` px takes in a viewport `vh` px tall. */
+export function glideDuration(distance: number, vh: number): number {
+ const screens = Math.abs(distance) / Math.max(1, vh);
+ return Math.round(Math.min(650, 450 + 100 * Math.sqrt(Math.min(screens, 4))));
+}
+
+/** Where a jump to `el` would put the page's scroll (its top under the sticky bars), clamped to the page. */
+export function landingY(el: Element): number {
+ const html = document.documentElement;
+ const pad = parseFloat(getComputedStyle(html).scrollPaddingTop) || 0;
+ const margin = parseFloat(getComputedStyle(el).scrollMarginTop) || 0;
+ const y = el.getBoundingClientRect().top + window.scrollY - pad - margin;
+ const max = html.scrollHeight - window.innerHeight;
+ return Math.max(0, Math.min(max, Math.round(y)));
+}
+
+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?.();
+ const instant = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
+ if (instant) {
+ window.scrollTo({ top: landingY(el), behavior: "instant" });
+ return Promise.resolve(true);
+ }
+ return new Promise((resolve) => {
+ const vh = window.innerHeight;
+ let from = window.scrollY;
+ const to = landingY(el);
+ // A long way starts a screen and a half off, so the glide itself stays short and smooth.
+ const near = vh * 1.5;
+ if (Math.abs(to - from) > vh * 3) {
+ from = to - Math.sign(to - from) * near;
+ window.scrollTo({ top: from, behavior: "instant" });
+ }
+ const duration = glideDuration(to - from, vh);
+ let raf = 0;
+ let t0 = 0;
+ const end = (landed: boolean) => {
+ cancelAnimationFrame(raf);
+ for (const t of STOPS) window.removeEventListener(t, interrupt, true);
+ if (stopCurrent === stop) stopCurrent = null;
+ resolve(landed);
+ };
+ const interrupt = () => end(false);
+ const stop = () => end(false);
+ const STOPS = ["wheel", "touchstart", "pointerdown", "keydown"] as const;
+ for (const t of STOPS) window.addEventListener(t, interrupt, { capture: true, passive: true });
+ stopCurrent = stop;
+ let pos = from;
+ let done = 0;
+ const frame = (now: number) => {
+ if (!t0) t0 = now;
+ const t = Math.min(1, (now - t0) / duration);
+ // The target is measured each frame (a picture above it may have settled). Each frame covers its share of the way
+ // still left, so a target that moves is spread over the rest of the glide instead of jumping.
+ const target = landingY(el);
+ const e = ease(t);
+ pos += (target - pos) * (t >= 1 ? 1 : (e - done) / (1 - done));
+ done = e;
+ window.scrollTo({ top: Math.round(pos), behavior: "instant" });
+ if (t < 1) raf = requestAnimationFrame(frame);
+ else end(true);
+ };
+ raf = requestAnimationFrame(frame);
+ });
+}
diff --git a/tests/e2e/tab-rows.mjs b/tests/e2e/tab-rows.mjs
new file mode 100644
index 00000000..848e9617
--- /dev/null
+++ b/tests/e2e/tab-rows.mjs
@@ -0,0 +1,213 @@
+// Tab and chip rows in a real browser (a production build: `pnpm build && pnpm start`).
+// Usage: node tests/e2e/tab-rows.mjs [appUrl] Exits 1 if any check fails.
+//
+// 1. Every row of tabs or chips (the area pages' section tabs, Home's goals, Library, the hubs, the Marketing suite, the
+// galleries' categories, the studios' modes, the phone's Studios sheet and search) at 390 and 1440, light and dark:
+// it is the shared row (data-tab-row), its pills share one height and are fully rounded, exactly one is selected (a
+// row with nothing open yet, Home's goals, after a tap), and the page never scrolls sideways at 390.
+// 2. The area tabs: stuck under the bar in a band with a hairline; a tap glides (450 to 650 ms, ease-out, no jump at the
+// end) and lands the section right under the band; the tapped tab is selected from the next frame and stays selected
+// when the last section can't reach the top; the fill slides (transform only) and only one pill ever looks selected.
+// 3. Reduced motion: the tap jumps at once and nothing slides.
+import { DESKTOP, launch, openRoute, PHONE } from "./_browser.mjs";
+
+const app = (process.argv.slice(2).find((a) => !a.startsWith("--")) ?? "http://localhost:3000").replace(/\/$/, "");
+const browser = await launch();
+const failures = [];
+const check = (ok, what, detail = "") => {
+ console.log(`${ok ? "✓" : "✗"} ${what}${detail ? ` (${detail})` : ""}`);
+ if (!ok) failures.push(what);
+};
+
+const ROWS = [
+ { name: "Home goals", route: "/", sel: "[data-goal-row] [data-tab-row]", none: true },
+ { name: "Create sections", route: "/create", sel: 'nav[aria-label="Create sections"] [data-tab-row]' },
+ { name: "Studios sections", route: "/studios", sel: 'nav[aria-label="Studios sections"] [data-tab-row]' },
+ { name: "Motions & effects sections", route: "/motions-and-effects", sel: 'nav[aria-label="Motions & effects sections"] [data-tab-row]' },
+ { name: "Apps categories", route: "/apps", sel: '[data-tab-row][aria-label="Categories"]' },
+ { name: "Effects categories", route: "/effects", sel: '[data-tab-row][aria-label="Categories"]' },
+ { name: "Library sections", route: "/library", sel: '[data-tab-row][aria-label="Library sections"]' },
+ { name: "Audio modes", route: "/audio", sel: "[data-hub-chrome] [data-tab-row]" },
+ { name: "Video tools modes", route: "/video-tools", sel: "[data-hub-chrome] [data-tab-row]" },
+ { name: "Upscale modes", route: "/upscale", sel: "[data-hub-chrome] [data-tab-row]" },
+ { name: "Marketing tools", route: "/marketing", sel: '[data-tab-row][aria-label="Marketing tools"]' },
+ { name: "Marketing view", route: "/marketing", sel: '[data-tab-row][aria-label="View"]' },
+ { name: "Genjutsu modes", route: "/genjutsu", sel: '[data-tab-row][aria-label="Genjutsu modes"]' },
+ { name: "Shorts tabs", route: "/shorts", sel: '[data-tab-row][aria-label="Shorts Studio"]' },
+ { name: "Mixed Media tabs", route: "/mixed-media", sel: '[data-tab-row][aria-label="Mixed Media"]' },
+ { name: "Photodump packs", route: "/photodump", sel: '[data-tab-row][aria-label="Packs"]' },
+ { name: "Studios sheet goals", route: "/", sel: '[role=dialog] [data-tab-row][aria-label="Show the studios for one goal"]', phoneOnly: true, setup: "sheet" },
+ { name: "Search goals", route: "/", sel: '[role=dialog] [data-tab-row][aria-label="Show the studios for one goal"]', setup: "search" },
+];
+
+/** The row's pills: their heights, radii and how many are selected; the page's sideways overflow. */
+const measure = (sel) => {
+ const row = [...document.querySelectorAll(sel)].find((r) => r.checkVisibility());
+ if (!row) return null;
+ const pills = [...row.querySelectorAll(".tab-pill")].filter((p) => p.checkVisibility());
+ const rr = row.getBoundingClientRect();
+ return {
+ n: pills.length,
+ heights: [...new Set(pills.map((p) => Math.round(p.getBoundingClientRect().height)))],
+ rounded: pills.every((p) => parseFloat(getComputedStyle(p).borderTopLeftRadius) >= p.getBoundingClientRect().height / 2 - 0.5),
+ on: pills.filter((p) => p.matches('[data-on], [data-state="active"]')).length,
+ pageOverflow: document.documentElement.scrollWidth - window.innerWidth,
+ rowInside: rr.left >= -1 && rr.right <= window.innerWidth + 1,
+ // What paints a fill: the pills (a selected one paints none while the sliding fill is there) and the fill itself.
+ lit: pills.filter((p) => getComputedStyle(p).backgroundColor !== "rgba(0, 0, 0, 0)").length + (row.hasAttribute("data-ind") ? 1 : 0),
+ };
+};
+
+async function setup(page, r) {
+ if (r.setup === "sheet") await page.locator('nav[aria-label="Main"]').last().getByRole("button", { name: "Studios" }).click();
+ if (r.setup === "search") await page.keyboard.press("Control+k");
+ if (r.setup) await page.waitForTimeout(800);
+}
+
+// 1. Every row, at both widths and in both themes.
+for (const device of [PHONE, DESKTOP]) {
+ const w = device.viewport.width;
+ for (const scheme of ["light", "dark"]) {
+ const ctx = await browser.newContext({ ...device, colorScheme: scheme });
+ await ctx.addInitScript((d) => {
+ try {
+ localStorage.setItem("theme", d);
+ } catch {}
+ }, scheme);
+ const page = await ctx.newPage();
+ for (const r of ROWS) {
+ if (r.phoneOnly && w !== 390) continue;
+ const tag = `${r.name} at ${w} ${scheme}`;
+ try {
+ await openRoute(page, `${app}${r.route}`);
+ await setup(page, r);
+ let m = await page.evaluate(measure, r.sel);
+ if (!m) {
+ check(false, `${tag}: the row is the shared row`, "not found");
+ continue;
+ }
+ if (r.none) {
+ check(m.on === 0, `${tag}: nothing open before a tap`, `${m.on}`);
+ await page.locator(r.sel).locator(".tab-pill").nth(1).click();
+ await page.waitForTimeout(400);
+ m = await page.evaluate(measure, r.sel);
+ }
+ check(m.n > 1 && m.heights.length === 1, `${tag}: ${m.n} pills of one height`, m.heights.join(","));
+ check(m.rounded, `${tag}: every pill fully rounded`);
+ check(m.on === 1, `${tag}: exactly one selected`, `${m.on}`);
+ check(m.lit === 1, `${tag}: one fill on screen`, `${m.lit}`);
+ if (w === 390) check(m.pageOverflow <= 0 && m.rowInside, `${tag}: nothing scrolls the page sideways`, `${m.pageOverflow}px`);
+ } catch (e) {
+ check(false, tag, e.message.split("\n")[0]);
+ }
+ }
+ await ctx.close();
+ }
+}
+
+// 2. The area tabs: the band, the glide, the landing, the slide.
+for (const device of [PHONE, DESKTOP]) {
+ const w = device.viewport.width;
+ const ctx = await browser.newContext(device);
+ const page = await ctx.newPage();
+ await openRoute(page, `${app}/create`);
+ const band = 'nav[aria-label="Create sections"]';
+ const tabs = page.locator(`${band} .tab-pill`);
+ const n = await tabs.count();
+ // A middle section: one that can reach the top.
+ const target = await tabs.nth(1).getAttribute("data-section");
+ const run = await page.evaluate(
+ async ({ band, i }) => {
+ const pill = document.querySelectorAll(`${band} .tab-pill`)[i];
+ const row = pill.closest("[data-tab-row]");
+ const frames = [];
+ const t0 = performance.now();
+ pill.click();
+ const selectedAt = [];
+ await new Promise((res) => {
+ const tick = () => {
+ const t = performance.now() - t0;
+ const ind = row.querySelector(".tab-ind > span");
+ frames.push({ t, y: scrollY, moving: row.hasAttribute("data-ind-moving"), transform: getComputedStyle(ind).transform, on: row.querySelectorAll("[data-on]").length });
+ if (pill.hasAttribute("data-on") && !selectedAt.length) selectedAt.push(frames.length);
+ if (t < 1200) requestAnimationFrame(tick);
+ else res();
+ };
+ requestAnimationFrame(tick);
+ });
+ const sec = document.getElementById(pill.dataset.section);
+ const b = document.querySelector(band).getBoundingClientRect();
+ const ys = frames.map((f) => f.y);
+ const start = ys[0];
+ const end = ys.at(-1);
+ const settled = frames.find((f) => f.y === end).t;
+ // The largest step between frames in the last fifth of the way: an ease-out ends in small steps, never a jump.
+ const steps = ys.slice(1).map((y, k) => Math.abs(y - ys[k]));
+ const tailFrom = ys.findIndex((y) => Math.abs(end - y) <= Math.abs(end - start) / 5);
+ const tail = Math.max(0, ...steps.slice(Math.max(0, tailFrom)));
+ return {
+ steps: steps.filter((d) => d > 0).map(Math.round).join(","),
+ settled,
+ travel: Math.abs(end - start),
+ tail,
+ firstStep: steps[0],
+ gap: sec.getBoundingClientRect().top - b.bottom,
+ stuck: document.querySelector(band).hasAttribute("data-stuck"),
+ selectedFrame: selectedAt[0],
+ maxOn: Math.max(...frames.map((f) => f.on)),
+ slid: frames.some((f) => f.moving),
+ hash: location.hash,
+ };
+ },
+ { band, i: 1 },
+ );
+ check(run.travel > 0 && run.settled >= 380 && run.settled <= 720, `/create at ${w}: the glide takes 450-650 ms`, `${Math.round(run.settled)} ms over ${run.travel}px`);
+ check(run.tail <= Math.max(6, run.travel / 25), `/create at ${w}: the glide eases out with no jump at the end`, `last steps ≤ ${run.tail}px; steps ${run.steps}`);
+ check(run.gap >= 0 && run.gap <= 24, `/create at ${w}: the section lands right under the band`, `${Math.round(run.gap)}px below it`);
+ check(run.stuck, `/create at ${w}: the band is stuck under the bar with its hairline`);
+ check(run.selectedFrame !== undefined && run.selectedFrame <= 2, `/create at ${w}: the tapped tab is selected from the next frame`, `frame ${run.selectedFrame}`);
+ check(run.maxOn === 1, `/create at ${w}: one tab selected all the way`);
+ check(run.slid, `/create at ${w}: the fill slides to the tapped tab`);
+ check(run.hash === `#${target}`, `/create at ${w}: the address names the section`, run.hash);
+ // The last section: too short to reach the top, still the one selected.
+ await tabs.nth(n - 1).click();
+ await page.waitForTimeout(1100);
+ const last = await page.evaluate((band) => [...document.querySelectorAll(`${band} .tab-pill[data-on]`)].map((p) => p.dataset.section), band);
+ const lastId = await tabs.nth(n - 1).getAttribute("data-section");
+ check(last.length === 1 && last[0] === lastId, `/create at ${w}: the last tab stays selected at the end of the page`, last.join(","));
+ // Wheel back up: the scroll-spy follows again, one tab at a time.
+ await page.mouse.move(w / 2, 400);
+ await page.mouse.wheel(0, -100000);
+ await page.waitForTimeout(900);
+ const top = await page.evaluate((band) => [...document.querySelectorAll(`${band} .tab-pill[data-on]`)].map((p) => p.dataset.section), band);
+ const firstId = await tabs.nth(0).getAttribute("data-section");
+ check(top.length === 1 && top[0] === firstId, `/create at ${w}: back at the top the first tab is selected`, top.join(","));
+ await ctx.close();
+}
+
+// 3. Reduced motion: an instant jump, nothing slides.
+{
+ const ctx = await browser.newContext({ ...DESKTOP, reducedMotion: "reduce" });
+ const page = await ctx.newPage();
+ await openRoute(page, `${app}/create`);
+ const band = 'nav[aria-label="Create sections"]';
+ const r = await page.evaluate(async (band) => {
+ const pill = document.querySelectorAll(`${band} .tab-pill`)[1];
+ const row = pill.closest("[data-tab-row]");
+ const y0 = scrollY;
+ pill.click();
+ await new Promise((res) => requestAnimationFrame(() => requestAnimationFrame(res)));
+ const sec = document.getElementById(pill.dataset.section);
+ return { moved: scrollY !== y0, gap: sec.getBoundingClientRect().top - document.querySelector(band).getBoundingClientRect().bottom, sliding: row.hasAttribute("data-ind-moving"), transition: getComputedStyle(row.querySelector(".tab-ind > span")).transitionDuration };
+ }, band);
+ check(r.moved && r.gap >= 0 && r.gap <= 24, "reduced motion: the tap jumps straight to the section", `${Math.round(r.gap)}px below the band`);
+ check(!r.sliding && r.transition === "0s", "reduced motion: the fill does not slide");
+ await ctx.close();
+}
+
+await browser.close();
+if (failures.length) {
+ console.log(`\n${failures.length} failed:\n- ${failures.join("\n- ")}`);
+ process.exit(1);
+}
+console.log("\nall tab-row checks passed");
diff --git a/tests/tab-rows.test.ts b/tests/tab-rows.test.ts
new file mode 100644
index 00000000..c8cb0a58
--- /dev/null
+++ b/tests/tab-rows.test.ts
@@ -0,0 +1,137 @@
+import fs from "node:fs";
+import path from "node:path";
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { describe, expect, it } from "vitest";
+import { AreaTabs } from "@/components/areas/area-islands";
+import { onAttr, TAB_PILL, TabRow } from "@/components/ui/tab-row";
+import { glideDuration } from "@/lib/glide-scroll";
+
+/*
+ * Every row of tabs or chips on the site has one look (src/components/ui/tab-row.tsx, src/app/tab-row.css): pills in a
+ * TabRow, the selected one marked data-on, a fill that slides between them. These checks keep each row on it.
+ */
+
+const src = (f: string) => fs.readFileSync(path.join(__dirname, "..", f), "utf8");
+
+/** Each row: the file that draws it and the row's own words (its aria-label), so a row can't leave the shared look. */
+const ROWS: [file: string, label: string][] = [
+ ["src/components/areas/area-islands.tsx", "<TabRow follow>"],
+ ["src/components/nav/goal-row.tsx", 'aria-label="Start from a goal"'],
+ ["src/components/library-view.tsx", 'aria-label="Library sections"'],
+ ["src/components/studio/hub-chrome.tsx", "<TabRow ref={ref}"],
+ ["src/components/marketing/shell.tsx", 'aria-label="Marketing tools"'],
+ ["src/components/marketing/marketing-studio.tsx", 'aria-label="View"'],
+ ["src/components/preset-gallery.tsx", 'aria-label="Categories"'],
+ ["src/components/genjutsu/genjutsu-studio.tsx", 'aria-label="Genjutsu modes"'],
+ ["src/components/shorts/shorts-studio.tsx", 'aria-label="Shorts Studio"'],
+ ["src/components/mixed-media/mixed-studio.tsx", 'aria-label="Mixed Media"'],
+ ["src/components/influencer/influencer-builder.tsx", 'aria-label="Categories"'],
+ ["src/components/fashion/character-sheet.tsx", 'aria-label="How to build it"'],
+ ["src/components/fashion/character-sheet.tsx", 'aria-label="Soul Cast"'],
+ ["src/components/photodump/photodump-view.tsx", 'aria-label="Packs"'],
+ ["src/components/moodboards/moodboards-view.tsx", 'aria-label="Moodboards"'],
+ ["src/components/moodboards/moodboard-panel.tsx", 'aria-label="Moodboards"'],
+ ["src/components/swap-studio/workbench.tsx", 'aria-label="Stages"'],
+ ["src/components/studio/preset-chips.tsx", 'aria-label="Categories"'],
+ ["src/components/dub/dub-studio.tsx", 'aria-label="Languages"'],
+ ["src/components/cinema/soul-builders.tsx", 'aria-label="Cast details"'],
+ ["src/components/cinema/director-panel.tsx", 'aria-label="Camera"'],
+ ["src/components/cinema/director-panel.tsx", 'aria-label="Lighting"'],
+ ["src/components/cinema/palette-editor.tsx", 'aria-label="Source"'],
+ ["src/components/cinema/side-panel.tsx", 'aria-label="Panel"'],
+ ["src/components/canvas/canvas-editor.tsx", 'aria-label="View"'],
+ ["src/components/ads/ad-editor.tsx", 'aria-label="Format"'],
+ ["src/components/studio/media-slot.tsx", 'aria-label="Kind"'],
+ ["src/components/genjutsu/look-picker.tsx", 'aria-label="Where the look comes from"'],
+ ["src/components/nav/studios-sheet.tsx", 'aria-label="Show the studios for one goal"'],
+ ["src/components/nav/search-palette.tsx", 'aria-label="Show the studios for one goal"'],
+];
+
+describe("tab and chip rows", () => {
+ it.each(ROWS)("%s draws %s as a TabRow of tab pills", (file, label) => {
+ const s = src(file);
+ expect(s).toContain('from "@/components/ui/tab-row"');
+ // The row's opening tag is a TabRow (the label is on it, maybe a few lines down; other elements may share it).
+ let at = -1;
+ for (let i = s.indexOf(label); i > -1; i = s.indexOf(label, i + 1)) {
+ if (/^<TabRow\s/.test(s.slice(s.lastIndexOf("<", i), s.lastIndexOf("<", i) + 8))) {
+ at = i;
+ break;
+ }
+ }
+ expect(at, `${file}: ${label} is on a TabRow`).toBeGreaterThan(-1);
+ // Its items are pills with the shared mark, and none keeps an underline or a segmented track of its own.
+ const close = s.indexOf("</TabRow>", at);
+ const row = s.slice(at, close);
+ expect(row).toContain("TAB_PILL");
+ expect(row).toMatch(/onAttr\(/);
+ expect(row).not.toMatch(/border-b-2|after:h-0\.5|bg-background text-foreground shadow-soft|rounded-t-/);
+ });
+
+ it("leaves no role=tablist outside the shared row", () => {
+ const dir = path.join(__dirname, "..", "src/components");
+ const files = fs.readdirSync(dir, { recursive: true }).map(String).filter((f) => f.endsWith(".tsx"));
+ // A picker of pictures (Home's before and after) and the canvas's page tabs (rename, reorder) are not tab rows.
+ const exempt = new Set(["home/before-after.tsx", "canvas/toolbar.tsx", "ui/tabs.tsx"].map((f) => path.normalize(f)));
+ const left = files.filter((f) => !exempt.has(path.normalize(f)) && /<div[^>]*role="tablist"/.test(fs.readFileSync(path.join(dir, f), "utf8")));
+ expect(left).toEqual([]);
+ });
+
+ it("the Radix tabs (ui/tabs) use the same pills and row", () => {
+ const s = src("src/components/ui/tabs.tsx");
+ expect(s).toContain("TAB_ROW");
+ expect(s).toContain("TAB_PILL");
+ expect(s).toContain("useTabIndicator");
+ });
+
+ it("a row renders its sliding fill, and the selected pill carries data-on", () => {
+ const html = renderToStaticMarkup(
+ createElement(TabRow, { role: "tablist", "aria-label": "Test" }, [
+ createElement("button", { key: "a", role: "tab", "aria-selected": true, className: TAB_PILL, ...onAttr(true) }, "A"),
+ createElement("button", { key: "b", role: "tab", "aria-selected": false, className: TAB_PILL, ...onAttr(false) }, "B"),
+ ]),
+ );
+ expect(html).toContain('class="tab-row fade-x"');
+ expect(html).toContain('<span aria-hidden="true" class="tab-ind"><span></span><span></span><span></span></span>');
+ expect(html.match(/data-on=""/g)?.length).toBe(1);
+ });
+
+ it("the area tabs are links in a sticky band, no tab selected before the page is read", () => {
+ const html = renderToStaticMarkup(
+ createElement(AreaTabs, {
+ label: "Create sections",
+ tabs: [
+ { href: "#make", label: "Make", icon: "sparkles", section: "make" },
+ { href: "#edit", label: "Edit a picture", icon: "wand", section: "edit" },
+ ],
+ }),
+ );
+ expect(html).toMatch(/<nav[^>]*class="tab-band/);
+ expect(html.match(/<a [^>]*class="tab-pill"/g)?.length).toBe(2);
+ expect(html).not.toContain("data-on");
+ });
+
+ it("the shared style: fully rounded pills of one height, a fill that moves by transform only, motion off when reduced", () => {
+ const css = src("src/app/tab-row.css");
+ const pill = css.slice(css.indexOf(".tab-pill {"), css.indexOf("}", css.indexOf(".tab-pill {")));
+ expect(pill).toContain("height: 36px");
+ expect(pill).toContain("border-radius: 9999px");
+ expect(pill).toContain("align-items: center");
+ // 44 px to tap on touch.
+ expect(css).toMatch(/@media \(pointer: coarse\)[\s\S]*?inset: -4px 0/);
+ // The fill's parts move with transforms only, never left or width.
+ const moving = css.slice(css.indexOf("[data-ind-moving] > .tab-ind > span {"));
+ expect(moving.slice(0, moving.indexOf("}"))).toContain("transition: transform");
+ expect(css).toMatch(/@media \(prefers-reduced-motion: reduce\)[\s\S]*transition: none/);
+ expect(css).not.toMatch(/transition:[^;]*\b(left|width)\b/);
+ });
+
+ it("a section glide takes 450 to 650 ms, longer for a longer way", () => {
+ expect(glideDuration(0, 800)).toBe(450);
+ expect(glideDuration(800, 800)).toBe(550);
+ expect(glideDuration(-3200, 800)).toBe(650);
+ expect(glideDuration(80_000, 800)).toBe(650);
+ expect(glideDuration(400, 800)).toBeLessThan(glideDuration(1600, 800));
+ });
+});