# Still UI: full reference > Quiet, carefully built React components. Copy the source or install with the shadcn CLI. ## Setup Still UI components are React 19 + Tailwind CSS v4 + motion (`motion/react`). Each one is a single file that you own after installing. They use shadcn's color tokens (`bg-background`, `text-foreground`, `bg-muted`, `bg-primary`, ...) and import one helper, `cn`, from `@/lib/utils`. 1. If the project has no shadcn setup yet, run `npx shadcn@latest init` (or the pnpm, yarn or bun equivalent below). 2. Once per project, add the registry to `components.json`: ```json { "registries": { "@stillui": "https://stillui.netlify.app/r/{name}.json" } } ``` 3. Add a component by name. Use the line for the project's package manager (look for `pnpm-lock.yaml`, `yarn.lock`, `bun.lock` or `package-lock.json`): - npm: `npx shadcn@latest add @stillui/` - pnpm: `pnpm dlx shadcn@latest add @stillui/` - yarn: `yarn dlx shadcn@latest add @stillui/` - bun: `bunx --bun shadcn@latest add @stillui/` The CLI writes the file to `components/ui/.tsx` and installs its npm dependencies. Import from there, e.g. `import { Button } from "@/components/ui/button"`. ## Paid components Components marked paid install from `@stillui-pro` instead. They need an account with access and its token (made on https://stillui.netlify.app/account): 1. Put the token in the project's `.env.local` as `STILLUI_TOKEN=...`. Never commit it. 2. Add the paid registry next to the free one in `components.json`: ```json "@stillui-pro": { "url": "https://stillui.netlify.app/r/pro/{name}.json", "headers": { "Authorization": "Bearer ${STILLUI_TOKEN}" } } ``` 3. Install with `npx shadcn@latest add @stillui-pro/` (same runners as above). A 401 means the token is missing or wrong; a 403 means the account's access has ended. Without shadcn: install `motion clsx tailwind-merge`, add the `cn` helper and the theme tokens from https://stillui.netlify.app/docs/installation, then copy a component's source from its registry JSON. ## Rules when writing code with these components - Keep the component file as installed; pass props instead of editing it, unless the user asks for a change. - Every component handles reduced motion, keyboard use and screen readers already. Don't wrap them in extra motion or ARIA. - Use the theme tokens for color. Don't hardcode hex values next to them. - Navigation components take `linkComponent` (pass Next.js `Link`) so routing stays client-side. ## Accordion: Surface Collapsible sections separated by space, not lines. The open section sits on its own surface. - Install: `@stillui/accordion` - Import: `import { Accordion } from "@/components/ui/accordion"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/accordion States it handles: - **Closed**: Just the title and a chevron. A soft background appears on hover. - **Opening**: Height grows first; the text fades in once there is room for it. - **Open**: The section gets a muted surface so title and content read as one unit. - **Single / multiple**: By default opening one closes the others. Pass multiple to allow several. - **Keyboard**: Each title is a button inside a heading, with aria-expanded and a linked region. - **Reduced motion**: Sections open and close instantly. Notes: - Good for FAQs and settings people rarely need. Don’t hide something most visitors need to read. ```tsx "use client"; // stillui.dev/components/accordion import { AnimatePresence, motion, useReducedMotion } from "motion/react"; import { useId, useState, type ReactNode } from "react"; import { cn } from "@/lib/utils"; // Height opens on an on-screen ease; content fades in just after the space exists. const HEIGHT = { duration: 0.28, ease: [0.65, 0, 0.35, 1] } as const; const CONTENT = { duration: 0.2, ease: [0.16, 1, 0.3, 1] } as const; export type AccordionItem = { value: string; title: ReactNode; content: ReactNode; }; type AccordionProps = { items: AccordionItem[]; /** Allow several sections open at once. */ multiple?: boolean; defaultOpen?: string[]; className?: string; }; export function Accordion({ items, multiple = false, defaultOpen = [], className }: AccordionProps) { const [open, setOpen] = useState(defaultOpen); const toggle = (value: string) => setOpen((current) => { if (current.includes(value)) return current.filter((v) => v !== value); return multiple ? [...current, value] : [value]; }); return (
{items.map((item) => (
toggle(item.value)} /> ))}
); } function Section({ item, open, onToggle }: { item: AccordionItem; open: boolean; onToggle: () => void }) { const reduce = useReducedMotion(); const id = useId(); const panelId = `${id}-panel`; const triggerId = `${id}-trigger`; return (

{open ? ( {item.content} ) : null}
); } ``` ## Accordion: Cards Each section is its own raised card. The open card grows on a weighted spring and its neighbours glide aside. - Install: `@stillui/accordion-cards` - Import: `import { AccordionCards } from "@/components/ui/accordion-cards"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/accordion States it handles: - **Closed**: A card with the title and a round chevron button. - **Open**: The chevron fills with the primary color and turns; a little extra space separates the open card. - **Switching**: One card closes as the next opens, and every card below moves with one spring. - **Keyboard**: Titles are buttons inside headings, with aria-expanded and a linked region. - **Reduced motion**: Cards open and close instantly, without layout movement. Notes: - Works best with three to six short questions, such as a pricing FAQ. ```tsx "use client"; // stillui.dev/components/accordion#cards import { AnimatePresence, motion, useReducedMotion } from "motion/react"; import { useId, useState, type ReactNode } from "react"; import { cn } from "@/lib/utils"; // A weighted spring: the open card pushes its neighbours and they settle together. const SPRING = { type: "spring", stiffness: 260, damping: 30, mass: 0.9 } as const; export type AccordionCardItem = { value: string; title: ReactNode; content: ReactNode; }; type AccordionCardsProps = { items: AccordionCardItem[]; defaultOpen?: string; className?: string; }; /** Each section is its own card. One opens at a time and the others glide out of the way. */ export function AccordionCards({ items, defaultOpen, className }: AccordionCardsProps) { const [open, setOpen] = useState(defaultOpen); return (
{items.map((item) => ( setOpen((current) => (current === item.value ? undefined : item.value))} /> ))}
); } function Card({ item, open, onToggle }: { item: AccordionCardItem; open: boolean; onToggle: () => void }) { const reduce = useReducedMotion(); const id = useId(); const transition = reduce ? { duration: 0 } : SPRING; return ( {open ? (
{item.content}
) : null}
); } ``` ## Accordion: Plus Large titles with a plus that folds into a minus. While one answer is open, the other titles step back. - Install: `@stillui/accordion-plus` - Import: `import { AccordionPlus } from "@/components/ui/accordion-plus"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/accordion States it handles: - **Closed**: Only titles, at a size that works on marketing pages. - **Open**: The plus’s vertical bar turns flat into a minus while the answer unfolds. - **Focus on one**: Other titles fade to the muted color, and come back on hover. - **Keyboard**: Titles are buttons inside headings, with aria-expanded and a linked region. - **Reduced motion**: Answers appear and disappear instantly. Notes: - Separated only by space, so give it room. It suits FAQ sections more than dense settings. ```tsx "use client"; // stillui.dev/components/accordion#plus import { AnimatePresence, motion, useReducedMotion } from "motion/react"; import { useId, useState, type ReactNode } from "react"; import { cn } from "@/lib/utils"; const EASE = { duration: 0.32, ease: [0.65, 0, 0.35, 1] } as const; export type AccordionPlusItem = { value: string; title: ReactNode; content: ReactNode; }; type AccordionPlusProps = { items: AccordionPlusItem[]; defaultOpen?: string; className?: string; }; /** Large titles with a plus that folds into a minus. While one is open, the other titles step back. */ export function AccordionPlus({ items, defaultOpen, className }: AccordionPlusProps) { const [open, setOpen] = useState(defaultOpen); return (
{items.map((item) => ( setOpen((current) => (current === item.value ? undefined : item.value))} /> ))}
); } type RowProps = { item: AccordionPlusItem; open: boolean; dimmed: boolean; onToggle: () => void; }; function Row({ item, open, dimmed, onToggle }: RowProps) { const reduce = useReducedMotion(); const id = useId(); const transition = reduce ? { duration: 0 } : EASE; return (

{open ? (
{item.content}
) : null}
); } ``` ## Accordion: Icon rows Rows with an icon and a one-line summary, like a settings list. Several can be open, and content lines up under the text. - Install: `@stillui/accordion-icons` - Import: `import { AccordionIcons } from "@/components/ui/accordion-icons"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/accordion States it handles: - **Closed**: Icon, title and a summary of the current value, so people often don’t need to open it. - **Open**: The icon tile fills with the primary color and the arrow turns down. - **Multiple**: Several rows can be open by default. Pass multiple={false} to allow only one. - **Keyboard**: Titles are buttons inside headings, with aria-expanded and a linked region. - **Reduced motion**: Rows open and close instantly. Notes: - Write the summary as the current state (“Pro plan, renews 3 March”), not a description of the section. ```tsx "use client"; // stillui.dev/components/accordion#icons import { AnimatePresence, motion, useReducedMotion } from "motion/react"; import { useId, useState, type ReactNode } from "react"; import { cn } from "@/lib/utils"; const HEIGHT = { duration: 0.26, ease: [0.65, 0, 0.35, 1] } as const; export type AccordionIconItem = { value: string; icon: ReactNode; title: ReactNode; /** One line under the title, visible while closed. */ summary?: ReactNode; content: ReactNode; }; type AccordionIconsProps = { items: AccordionIconItem[]; multiple?: boolean; defaultOpen?: string[]; className?: string; }; /** Rows with an icon and a one-line summary, like a settings list. Content lines up under the text. */ export function AccordionIcons({ items, multiple = true, defaultOpen = [], className }: AccordionIconsProps) { const [open, setOpen] = useState(defaultOpen); const toggle = (value: string) => setOpen((current) => { if (current.includes(value)) return current.filter((v) => v !== value); return multiple ? [...current, value] : [value]; }); return (
{items.map((item) => ( toggle(item.value)} /> ))}
); } function Row({ item, open, onToggle }: { item: AccordionIconItem; open: boolean; onToggle: () => void }) { const reduce = useReducedMotion(); const id = useId(); const transition = reduce ? { duration: 0 } : HEIGHT; return (

{open ? ( {/* Indented to the text column so the content reads as part of the row. */}
{item.content}
) : null}
); } ``` ## Accordion: Glass (paid) One sheet of frosted glass. The open section lifts out as its own card, catches a passing light, and its answer comes into focus. - Install: `@stillui-pro/accordion-glass` with an account token (see "Paid components" above) - Page: https://stillui.netlify.app/components/accordion ## Button: Standard Primary, secondary and tertiary actions with press feedback and a loading state that keeps its width. - Install: `@stillui/button` - Import: `import { Button } from "@/components/ui/button"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/button States it handles: - **Idle**: Variant sets its place in the action hierarchy: one primary per view. - **Hover**: Background shifts one step. No movement. - **Pressed**: Scales to 97% on a stiff spring, felt within about 100ms. - **Focus**: Visible outline from the ring token, keyboard only. - **Loading**: Label blurs out in place, spinner fades in, width stays fixed. Announced as busy. - **Disabled**: Half opacity, no press response. Notes: - Destructive is for confirmation steps. On the page that starts a destructive flow, use secondary or tertiary. - Sizes change padding more than font size, so a large button feels larger rather than zoomed. ```tsx "use client"; // stillui.dev/components/button import { AnimatePresence, motion, useReducedMotion } from "motion/react"; import { forwardRef, type ComponentProps, type ReactNode } from "react"; import { cn } from "@/lib/utils"; // Press feedback lands inside ~100ms and settles without a visible wobble. const PRESS = { type: "spring", stiffness: 700, damping: 40, mass: 0.6 } as const; const SWAP = { duration: 0.16, ease: [0.16, 1, 0.3, 1] } as const; // One primary action per view; secondary is quieter; tertiary reads like a link. const variants = { primary: "bg-primary text-primary-foreground shadow-raised hover:bg-primary/90", secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/70", tertiary: "bg-transparent text-muted-foreground hover:text-foreground hover:bg-secondary/60", destructive: "bg-destructive text-white shadow-raised hover:bg-destructive/90", } as const; // Padding grows faster than the font so a large button feels larger, not zoomed. const sizes = { sm: "h-8 gap-1.5 px-3 text-[13px]", md: "h-10 gap-2 px-4 text-sm", lg: "h-12 gap-2.5 px-6 text-[15px]", } as const; type ButtonProps = Omit, "children"> & { variant?: keyof typeof variants; size?: keyof typeof sizes; /** Keeps the button's width while showing a spinner in place of the label. */ loading?: boolean; children?: ReactNode; }; export const Button = forwardRef(function Button( { variant = "primary", size = "md", loading = false, disabled, className, children, ...props }, ref, ) { const reduce = useReducedMotion(); const inactive = disabled || loading; return ( {/* The label stays in the layout so the width never jumps. */} {children} {loading ? ( Loading ) : null} ); }); function Spinner() { return ( ); } ``` ## Button: Hold to confirm A destructive action that asks for a deliberate press-and-hold instead of a confirmation dialog. - Install: `@stillui/button-hold` - Import: `import { ButtonHold } from "@/components/ui/button-hold"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/button States it handles: - **Idle**: A quiet button with the label in the destructive color. - **Holding**: Red fills from the left at a steady pace; the label turns white exactly where the fill has reached. - **Let go early**: The fill drains back quickly and nothing happens. - **Confirmed**: Runs onConfirm and shows the done label for a moment, then resets. - **Keyboard**: Hold Space or Enter. Moving focus away cancels. - **Screen readers**: Described as “Press and hold to confirm” through aria-describedby, and the result is announced. Notes: - Use it for actions that are hard to undo. For everyday actions, a normal button with an undo toast is kinder. - The fill keeps moving with reduced motion turned on, because it is the only sign of progress. ```tsx "use client"; // stillui.dev/components/button#hold import { animate, motion, useMotionValue, useTransform, type AnimationPlaybackControls } from "motion/react"; import { useId, useRef, useState, type KeyboardEvent, type ReactNode } from "react"; import { cn } from "@/lib/utils"; type ButtonHoldProps = { children: ReactNode; /** Runs once the button has been held for the full duration. */ onConfirm: () => void; /** How long to hold, in milliseconds. */ duration?: number; /** Shown briefly after confirming. */ doneLabel?: ReactNode; className?: string; }; /** A destructive action that needs a deliberate press-and-hold. Letting go early cancels it. */ export function ButtonHold({ children, onConfirm, duration = 1200, doneLabel = "Done", className }: ButtonHoldProps) { const progress = useMotionValue(0); const controls = useRef(null); const [done, setDone] = useState(false); const hintId = useId(); // The filled layer is clipped from the right, so the label changes color exactly where the fill is. const clipPath = useTransform(progress, (p) => `inset(0 ${100 - p * 100}% 0 0)`); const start = () => { if (done) return; controls.current?.stop(); controls.current = animate(progress, 1, { duration: (duration / 1000) * (1 - progress.get()), ease: "linear", onComplete: () => { setDone(true); onConfirm(); window.setTimeout(() => { setDone(false); animate(progress, 0, { duration: 0.3 }); }, 1400); }, }); }; const cancel = () => { if (done) return; controls.current?.stop(); controls.current = animate(progress, 0, { duration: 0.25, ease: [0.16, 1, 0.3, 1], }); }; const onKeyDown = (event: KeyboardEvent) => { if ((event.key === " " || event.key === "Enter") && !event.repeat) { event.preventDefault(); start(); } }; const onKeyUp = (event: KeyboardEvent) => { if (event.key === " " || event.key === "Enter") cancel(); }; const label = done ? doneLabel : children; return ( <> ); } ``` ## Button: Stateful Follows its own request: idle, loading, then success or error. The button reshapes around each label. - Install: `@stillui/button-stateful` - Import: `import { ButtonStateful } from "@/components/ui/button-stateful"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/button States it handles: - **Idle**: A normal primary button. - **Loading**: A spinner and a present-tense label. Further clicks are ignored. - **Success**: Turns green with a check that draws itself. - **Error**: Turns red with a short reason, so people know it didn’t work. - **Reset**: Returns to idle after 1.8 seconds. - **Screen readers**: Each new label is announced through a live region. Notes: - Pass a function that returns a promise. A thrown error or rejection shows the error label. ```tsx "use client"; // stillui.dev/components/button#stateful import { AnimatePresence, motion, useReducedMotion } from "motion/react"; import { useState, type ReactNode } from "react"; import { cn } from "@/lib/utils"; const SPRING = { type: "spring", stiffness: 420, damping: 34 } as const; const RESET_AFTER = 1800; type Phase = "idle" | "loading" | "success" | "error"; type ButtonStatefulProps = { /** Return a promise; the button follows it to success or error. */ onClick: () => Promise; labels: Partial> & { idle: ReactNode }; className?: string; }; /** A button that shows its own result. The width reshapes around each label. */ export function ButtonStateful({ onClick, labels, className }: ButtonStatefulProps) { const reduce = useReducedMotion(); const [phase, setPhase] = useState("idle"); const transition = reduce ? { duration: 0 } : SPRING; const run = async () => { if (phase !== "idle") return; setPhase("loading"); let next: Phase = "success"; try { await onClick(); } catch { next = "error"; } setPhase(next); window.setTimeout(() => setPhase("idle"), RESET_AFTER); }; const label = labels[phase] ?? labels.idle; return ( {label} {phase === "idle" ? "" : label} ); } function PhaseIcon({ phase }: { phase: Phase }) { if (phase === "idle") return null; if (phase === "loading") { return ( ); } return ( {phase === "success" ? ( ) : ( )} ); } ``` ## Button: Expand A round icon button that reveals its label when you hover or focus it, so toolbars stay compact without guessing. - Install: `@stillui/button-expand` - Import: `import { ButtonExpand } from "@/components/ui/button-expand"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/button States it handles: - **Resting**: Just the icon in a round, raised button. - **Reaching**: On hover or keyboard focus the label slides out and the button widens on a spring. - **Leaving**: The label tucks back in when the pointer or focus moves on. - **Screen readers**: The label is always the accessible name, even while hidden. - **Reduced motion**: The label appears and disappears without sliding. Notes: - Touch screens have no hover, so pick icons people recognise without the label. ```tsx "use client"; // stillui.dev/components/button#expand import { AnimatePresence, motion, useReducedMotion } from "motion/react"; import { useState, type ComponentProps, type ReactNode } from "react"; import { cn } from "@/lib/utils"; const SPRING = { type: "spring", stiffness: 500, damping: 38 } as const; type ButtonExpandProps = Omit, "children"> & { icon: ReactNode; /** Always used as the accessible name; shown beside the icon on hover and focus. */ label: string; }; /** An icon button that reveals its label when you reach for it. */ export function ButtonExpand({ icon, label, className, ...props }: ButtonExpandProps) { const reduce = useReducedMotion(); const [open, setOpen] = useState(false); const transition = reduce ? { duration: 0 } : SPRING; return ( ); } ``` ## Button: Download (paid) Fills with light as the download runs, and buds off a cancel button that rejoins the pill when it’s done. - Install: `@stillui-pro/button-download` with an account token (see "Paid components" above) - Page: https://stillui.netlify.app/components/button ## Button: Progress (paid) A download button whose outline draws itself as the download runs, closing into a full ring when it’s done. - Install: `@stillui-pro/button-progress` with an account token (see "Paid components" above) - Page: https://stillui.netlify.app/components/button ## Button: Icon An icon-only download button. The arrow and tray pull apart into a spinner, which turns into a check when it’s done. - Install: `@stillui/button-download-icon` - Import: `import { ButtonDownloadIcon } from "@/components/ui/button-download-icon"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/button States it handles: - **Idle**: A download arrow over a tray. - **Loading**: The tray pulls back to its ends and the arrow shrinks to a dot, which stretches into a spinning arc. - **Done**: The arc lets go and a check draws itself. After 1.6 seconds the arrow drops back in and the tray redraws. - **Failed**: A small shake, then back to idle. Screen readers hear that it failed. - **Screen readers**: The label names the button; each state is announced through a live region. - **Reduced motion**: The icons swap without drawing, and the spinner holds still. Notes: - Pass a function that returns a promise. The spinner runs until it settles. Give it a label that says what downloads. ```tsx "use client"; // stillui.dev/components/button#icon import { motion, useAnimate, useReducedMotion } from "motion/react"; import { useEffect, useRef, useState } from "react"; import { cn } from "@/lib/utils"; const DONE_FOR = 1600; const EASE = [0.16, 1, 0.3, 1] as const; type Phase = "idle" | "loading" | "done"; type ButtonDownloadIconProps = { /** Start the download. The icon spins until the promise settles. */ onDownload: () => Promise; /** The accessible name. */ label?: string; className?: string; }; /** An icon-only download button. The arrow and tray pull apart into a spinner, which then becomes a check. */ export function ButtonDownloadIcon({ onDownload, label = "Download", className, }: ButtonDownloadIconProps) { const reduce = !!useReducedMotion(); const [phase, setPhase] = useState("idle"); const [scope, animate] = useAnimate(); const [status, setStatus] = useState(""); const alive = useRef(true); useEffect(() => { alive.current = true; return () => { alive.current = false; }; }, []); const start = async () => { if (phase !== "idle") return; setPhase("loading"); setStatus("Downloading"); try { await onDownload(); if (!alive.current) return; setPhase("done"); setStatus("Downloaded"); window.setTimeout(() => alive.current && setPhase("idle"), DONE_FOR); } catch { if (!alive.current) return; setPhase("idle"); // A small shake, so people notice it didn’t work. if (!reduce) animate(scope.current, { x: [0, -4, 4, -3, 2, 0] }, { duration: 0.4 }); setStatus("Download failed"); } }; const idle = phase === "idle"; const t = (duration: number, delay = 0) => reduce ? { duration: 0 } : { duration, delay, ease: EASE }; return ( ); } ``` ## Button: Liquid (paid) A round add button that splits like a drop of liquid into the actions it holds, and melts back together when closed. - Install: `@stillui-pro/button-liquid` with an account token (see "Paid components" above) - Page: https://stillui.netlify.app/components/button ## Destination Card A photo card for a trip. The flight sits over the photo, and the buttons at the bottom switch places: the photo blurs into the next one and the route draws itself again. - Install: `@stillui/card-destination` - Import: `import { CardDestination } from "@/components/ui/card-destination"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/card-destination States it handles: - **Switching**: The old photo blurs and grows away while the new one sharpens. The codes, times and cities blur through in a short stagger. - **Route**: The wavy line draws from left to right and the plane glides in over it on every switch. - **Shadow**: A blurred copy of the photo sits under the card, so the shadow takes on each place's colours. - **Keyboard**: The buttons are a radio group. Tab lands on the chosen place and the arrow keys move between them. - **Reduced motion**: Photos and text crossfade without blurring, and the line appears already drawn. Notes: - Give each destination its own photo. Portrait images around 3:4 fit best; the bottom is softly blurred and darkened so the text stays readable on busy or light photos. - Works with two to four places. Pass value and onValueChange to control it from outside. ```tsx "use client"; // stillui.dev/components/card-destination import { AnimatePresence, motion, useReducedMotion } from "motion/react"; import { useId, useRef, useState, type KeyboardEvent } from "react"; import { cn } from "@/lib/utils"; const EASE = [0.16, 1, 0.3, 1] as const; // The pill stays inside the card, so it glides without overshoot. const GLIDE = { type: "spring", stiffness: 420, damping: 40, mass: 0.8 } as const; type Stop = { code: string; time: string; city: string }; export type Destination = { value: string; /** The name at the top of the card and on its button. */ city: string; image: string; alt: string; from: Stop; to: Stop; }; type CardDestinationProps = { destinations: Destination[]; value?: string; defaultValue?: string; onValueChange?: (value: string) => void; className?: string; }; /** A destination card: a full-bleed photo with the flight over it, and buttons to switch between places. */ export function CardDestination({ destinations, value, defaultValue, onValueChange, className, }: CardDestinationProps) { const reduce = !!useReducedMotion(); const [internal, setInternal] = useState(defaultValue ?? destinations[0]?.value); const current = value ?? internal; const active = destinations.find((d) => d.value === current) ?? destinations[0]; const select = (next: string) => { if (value === undefined) setInternal(next); onValueChange?.(next); }; return (
{/* A blurred copy of the photo under the card, so its shadow takes the photo's colours. */}

); } // Each layer blurs a little more and starts a little lower, so the photo goes soft gradually instead of at a line. const BLUR_LAYERS = [ { blur: 1, from: 0, to: 30 }, { blur: 2, from: 10, to: 45 }, { blur: 4, from: 25, to: 60 }, { blur: 8, from: 40, to: 80 }, { blur: 16, from: 60, to: 100 }, ]; /** A soft blur over the bottom of the photo, behind the flight and the buttons. */ function SoftBlur() { return (
{BLUR_LAYERS.map(({ blur, from, to }) => { const mask = `linear-gradient(to bottom, transparent ${from}%, black ${to}%)`; return (
); })}
); } /** Every photo stays mounted, so switching is instant; the old one blurs away as the new one sharpens. */ function Photos({ destinations, current, reduce, alt = false, }: { destinations: Destination[]; current: string; reduce: boolean; alt?: boolean; }) { return (
{destinations.map((d) => { const shown = d.value === current; return ( ); })}
); } /** Text that blurs out and in when it changes. */ function Swap({ text, reduce, delay = 0 }: { text: string; reduce: boolean; delay?: number }) { return ( {text} ); } function StopInfo({ stop, reduce, end = false }: { stop: Stop; reduce: boolean; end?: boolean }) { return (
); } /** A plane over a wavy line. Keyed by destination, so the line draws itself again on every switch. */ function Route({ reduce }: { reduce: boolean }) { return (
); } /** The switch between places. A radio group, so arrow keys move between them like native radios. */ function Picker({ destinations, current, onSelect, reduce, }: { destinations: Destination[]; current: string; onSelect: (value: string) => void; reduce: boolean; }) { const pill = useId(); const refs = useRef<(HTMLButtonElement | null)[]>([]); const onKeyDown = (event: KeyboardEvent) => { const step = event.key === "ArrowRight" || event.key === "ArrowDown" ? 1 : event.key === "ArrowLeft" || event.key === "ArrowUp" ? -1 : 0; if (!step) return; event.preventDefault(); const index = destinations.findIndex((d) => d.value === current); const next = (index + step + destinations.length) % destinations.length; onSelect(destinations[next].value); refs.current[next]?.focus(); }; return (
{destinations.map((d, i) => { const selected = d.value === current; return ( ); })}
); } ``` ## Carousel: Depth Photos in a row. The one in focus stands tall in the middle while its neighbours turn away and bunch up toward the edges. - Install: `@stillui/carousel` - Import: `import { Carousel } from "@/components/ui/carousel"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/carousel States it handles: - **In focus**: The middle card is full size and faces you. Tap any other card to bring it to the middle. - **Neighbours**: Each step away is smaller, turned a little further, and closer to the next, so many fit in a narrow space. - **Drag and flick**: Cards follow the pointer, then settle on the nearest one. A quick flick carries a little further. - **Keyboard**: The stage takes focus; the arrow keys move one card. The count is announced as it changes. - **Scroll**: Sideways scrolling on a trackpad moves through the cards. Scrolling up and down still scrolls the page. - **Loop**: The last card leads back to the first, always the shortest way round. - **Autoplay**: Off by default. Pass autoPlay in milliseconds; it pauses while hovered, focused or dragged. - **Narrow screens**: Cards shrink with the container so the shape holds on a phone. - **Reduced motion**: Cards jump to their places, and autoplay stays off. Notes: - Images fill a 3:4 card with object-fit cover. Use photos at least twice the card width for sharp screens. ```tsx "use client"; // stillui.dev/components/carousel import { animate, motion, useMotionValue, useReducedMotion, useTransform, type MotionValue, type PanInfo } from "motion/react"; import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState, type KeyboardEvent } from "react"; import { cn } from "@/lib/utils"; // Settles on a slide without bouncing past it. const SETTLE = { type: "spring", stiffness: 260, damping: 34, mass: 0.9 } as const; export type CarouselItem = { src: string; alt: string }; type CarouselProps = { items: CarouselItem[]; /** Width of the card in focus, in pixels. Shrinks to fit narrow containers. */ cardWidth?: number; defaultIndex?: number; index?: number; onIndexChange?: (index: number) => void; /** Moves to the next card every this many milliseconds. Pauses while hovered, focused or dragged. */ autoPlay?: number; /** Shows previous and next buttons with a count under the cards. */ controls?: boolean; label?: string; className?: string; }; /** Where a card sits when it is `d` places from the one in focus (negative: before it). */ type Place = { x: number; y: number; scale: number; rotate: number; rotateY: number; opacity: number }; // The focused card is full size; neighbours shrink, turn slightly away, and close up as they go. function layout(d: number, w: number): Place { const a = Math.abs(d); const near = Math.min(a, 1); const far = Math.max(a - 1, 0); const x = Math.sign(d) * w * (0.86 * near + 0.42 * far - 0.035 * far * far); const scale = Math.max(0.5, 1 - 0.22 * near - 0.05 * far); return { x, y: 0, scale, rotate: 0, rotateY: -Math.sign(d) * 16 * near, opacity: a > 4.5 ? 0 : Math.min(1, 4.5 - a) }; } /** * Photos in a row. The one in focus stands tall in the middle while its neighbours turn away and bunch up toward the edges. */ export function Carousel({ items, cardWidth = 220, defaultIndex = 0, index, onIndexChange, autoPlay, controls = true, label = "Photos", className, }: CarouselProps) { const reduce = useReducedMotion() ?? false; const ids = useId(); const count = items.length; const stageRef = useRef(null); const [width, setWidth] = useState(cardWidth); const [internal, setInternal] = useState(defaultIndex); const current = index ?? internal; const [paused, setPaused] = useState(false); // One continuous position drives every card: 2.5 means halfway between the third and fourth. const position = useMotionValue(current); const target = useRef(current); const dragStart = useRef(0); const dragged = useRef(false); // The card shrinks with its container, so the layout keeps its shape on phones. useLayoutEffect(() => { const stage = stageRef.current; if (!stage) return; const measure = () => setWidth(Math.min(cardWidth, stage.offsetWidth * 0.42)); measure(); const observer = new ResizeObserver(measure); observer.observe(stage); return () => observer.disconnect(); }, [cardWidth]); const settle = useCallback( (to: number) => { target.current = Math.round(to); const next = ((target.current % count) + count) % count; if (reduce) position.set(target.current); else animate(position, target.current, SETTLE); if (index === undefined) setInternal(next); onIndexChange?.(next); }, [count, reduce, position, index, onIndexChange], ); // A controlled index set from outside: travel there the shortest way round. useEffect(() => { if (((target.current % count) + count) % count === current) return; target.current += Math.round(wrap(current - target.current, count)); if (reduce) position.set(target.current); else animate(position, target.current, SETTLE); }, [current, count, position, reduce]); const step = (by: number) => settle(target.current + by); useEffect(() => { if (!autoPlay || paused || reduce) return; const timer = window.setInterval(() => settle(target.current + 1), autoPlay); return () => window.clearInterval(timer); }, [autoPlay, paused, reduce, settle]); // Sideways scrolling (trackpads, shift+wheel) moves through the cards; up and down still scroll the page. useEffect(() => { const stage = stageRef.current; if (!stage) return; let timer: number | undefined; const onWheel = (event: WheelEvent) => { if (Math.abs(event.deltaX) <= Math.abs(event.deltaY)) return; event.preventDefault(); position.stop(); position.set(position.get() + event.deltaX / (width * 0.62)); window.clearTimeout(timer); timer = window.setTimeout(() => settle(position.get()), 120); }; stage.addEventListener("wheel", onWheel, { passive: false }); return () => { stage.removeEventListener("wheel", onWheel); window.clearTimeout(timer); }; }, [position, settle, width]); const onPanStart = () => { position.stop(); dragStart.current = position.get(); dragged.current = true; setPaused(true); }; const onPan = (_: PointerEvent, info: PanInfo) => position.set(dragStart.current - info.offset.x / (width * 0.62)); const onPanEnd = (_: PointerEvent, info: PanInfo) => { // A flick carries on a little, in the direction it was thrown, but never more than three cards. const carry = (info.velocity.x / (width * 0.62)) * 0.18; settle(position.get() - Math.max(-3, Math.min(3, carry))); setPaused(false); }; const onKeyDown = (event: KeyboardEvent) => { if (event.key === "ArrowRight" || event.key === "ArrowDown") step(1); else if (event.key === "ArrowLeft" || event.key === "ArrowUp") step(-1); else return; event.preventDefault(); }; return (
setPaused(true)} onPointerLeave={() => setPaused(false)} onFocus={() => setPaused(true)} onBlur={() => setPaused(false)} > (dragged.current = false)} onPanStart={onPanStart} onPan={onPan} onPanEnd={onPanEnd} aria-describedby={`${ids}-hint`} className="relative w-full cursor-grab touch-pan-y select-none overflow-hidden rounded-2xl outline-none active:cursor-grabbing focus-visible:ring-2 focus-visible:ring-ring" style={{ height: width * 1.6 }} > Use the arrow keys or drag to move between photos. {items.map((item, i) => ( { // The click that ends a drag isn't a choice of card. if (dragged.current) return; settle(target.current + Math.round(wrap(i - target.current, count))); }} /> ))} {controls ? (
step(-1)} />

{current + 1} / {count}

step(1)} />
) : null}
); } /** Rounds for the transform string, so server and browser write the same numbers. */ function r(value: number, precision = 100) { return Math.round(value * precision) / precision; } /** The signed distance from a to b round a loop of n, between -n/2 and n/2. */ function wrap(d: number, n: number) { return ((((d + n / 2) % n) + n) % n) - n / 2; } type CardProps = { item: CarouselItem; i: number; count: number; width: number; position: MotionValue; current: boolean; onSelect: () => void; }; function Card({ item, i, count, width, position, current, onSelect }: CardProps) { const place = (p: number) => layout(wrap(i - p, count), width); const transform = useTransform(position, (p) => { const { x, y, scale, rotate, rotateY } = place(p); return `translate(-50%, -50%) translate3d(${r(x)}px, ${r(y)}px, 0) perspective(${r(width * 6)}px) rotateY(${r(rotateY)}deg) rotate(${r(rotate)}deg) scale(${r(scale, 1000)})`; }); const opacity = useTransform(position, (p) => r(place(p).opacity)); const zIndex = useTransform(position, (p) => Math.round(1000 - Math.abs(wrap(i - p, count)) * 10)); const visibility = useTransform(opacity, (o) => (o < 0.01 ? "hidden" : "visible")); return ( {/* A plain img keeps the component free of Next.js; pass already-sized images. */} {/* eslint-disable-next-line @next/next/no-img-element */} {item.alt} ); } function Arrow({ direction, onClick }: { direction: 1 | -1; onClick: () => void }) { return ( ); } ``` ## Carousel: Fan (paid) Photos fanned out like a hand of cards. Each one leans with the arc, and the hand slides round as you move. - Install: `@stillui-pro/carousel-fan` with an account token (see "Paid components" above) - Page: https://stillui.netlify.app/components/carousel ## Carousel: Stairs (paid) Photos climbing a diagonal. The one in focus is largest, and the rest step down and away toward each corner. - Install: `@stillui-pro/carousel-stairs` with an account token (see "Paid components" above) - Page: https://stillui.netlify.app/components/carousel ## Carousel: Spiral (paid) Photos winding into a spiral. The one in focus sits large in front; the rest curl away behind it, smaller with every turn. - Install: `@stillui-pro/carousel-spiral` with an account token (see "Paid components" above) - Page: https://stillui.netlify.app/components/carousel ## Carousel: Warp (paid) Photos in a column of pills. The one in focus sits sharp in the middle; cards stretch, flare and split into colour as they slide off the top and bottom. - Install: `@stillui-pro/carousel-warp` with an account token (see "Paid components" above) - Page: https://stillui.netlify.app/components/carousel ## Carousel: Backdrop A row of thumbnails over a full-bleed photo. Sweep across the row and the photo behind cuts to each one; the chosen thumbnail grows and its neighbours make room. - Install: `@stillui/carousel-backdrop` - Import: `import { CarouselBackdrop } from "@/components/ui/carousel-backdrop"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/carousel States it handles: - **Hover**: With a mouse, passing over a thumbnail chooses it, so sweeping the row flips through the photos. - **Chosen**: The chosen thumbnail grows by a fifth and the row spreads to fit it. The photo behind cuts with no fade. - **Touch**: A tap chooses a thumbnail. Nothing changes on a stray touch while scrolling. - **Keyboard**: The row is one tab stop. Arrow keys move along it, Home and End jump to the ends, and the photo follows. - **Screen readers**: Each thumbnail is a button named after its photo, and the chosen one is marked current. - **Autoplay**: Off by default. Pass autoPlay in milliseconds; it pauses while hovered or focused. - **Narrow screens**: Thumbnails shrink so the whole row always fits across the photo. - **Reduced motion**: Thumbnails change size at once, and autoplay stays off. Notes: - Thumbnails and the backdrop use the same image, so the backdrop is already loaded when it is chosen. Use photos large enough for the backdrop. - Works best with three to eight photos; with more, the thumbnails get small. ```tsx "use client"; // stillui.dev/components/carousel#backdrop import { motion, useReducedMotion } from "motion/react"; import { useCallback, useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent } from "react"; import { cn } from "@/lib/utils"; // Quick enough to keep up with a pointer sweeping across the row. const GROW = { type: "spring", stiffness: 520, damping: 38, mass: 0.6 } as const; // How much bigger the chosen thumbnail gets. const LIFT = 1.22; const GAP = 6; export type CarouselItem = { src: string; alt: string }; type CarouselBackdropProps = { items: CarouselItem[]; /** Largest thumbnail width, in pixels. Shrinks so the whole row fits. */ thumbWidth?: number; defaultIndex?: number; index?: number; onIndexChange?: (index: number) => void; /** Moves to the next photo every this many milliseconds. Pauses while hovered or focused. */ autoPlay?: number; label?: string; className?: string; }; /** * A row of thumbnails over a full-bleed photo. Sweep across the row and the photo behind cuts to each one; the chosen thumbnail grows and its neighbours make room. */ export function CarouselBackdrop({ items, thumbWidth = 96, defaultIndex = 0, index, onIndexChange, autoPlay, label = "Photos", className, }: CarouselBackdropProps) { const reduce = useReducedMotion() ?? false; const count = items.length; const stageRef = useRef(null); const thumbs = useRef<(HTMLButtonElement | null)[]>([]); const [width, setWidth] = useState(thumbWidth); const [internal, setInternal] = useState(defaultIndex); const current = index ?? internal; const [paused, setPaused] = useState(false); const choose = useCallback( (next: number) => { const wrapped = ((next % count) + count) % count; if (wrapped === current) return; if (index === undefined) setInternal(wrapped); onIndexChange?.(wrapped); }, [count, current, index, onIndexChange], ); // Thumbnails shrink until the whole row, chosen one included, fits across the photo. useLayoutEffect(() => { const stage = stageRef.current; if (!stage) return; const measure = () => { const room = stage.offsetWidth * 0.88 - GAP * (count - 1); setWidth(Math.min(thumbWidth, room / (count - 1 + LIFT))); }; measure(); const observer = new ResizeObserver(measure); observer.observe(stage); return () => observer.disconnect(); }, [thumbWidth, count]); useEffect(() => { if (!autoPlay || paused || reduce) return; const timer = window.setInterval(() => choose(current + 1), autoPlay); return () => window.clearInterval(timer); }, [autoPlay, paused, reduce, current, choose]); // One tab stop for the row; the arrow keys walk it and the photo follows. const onKeyDown = (event: KeyboardEvent) => { const by = event.key === "ArrowRight" || event.key === "ArrowDown" ? 1 : event.key === "ArrowLeft" || event.key === "ArrowUp" ? -1 : 0; const to = event.key === "Home" ? 0 : event.key === "End" ? count - 1 : (current + by + count) % count; if (!by && event.key !== "Home" && event.key !== "End") return; event.preventDefault(); choose(to); thumbs.current[to]?.focus(); }; return (
setPaused(true)} onPointerLeave={() => setPaused(false)} onFocus={() => setPaused(true)} onBlur={() => setPaused(false)} > {/* Every photo is already loaded as a thumbnail, so the cut is instant. */} {items.map((item, i) => ( // eslint-disable-next-line @next/next/no-img-element {i ))}
{items.map((item, i) => { const chosen = i === current; const w = chosen ? width * LIFT : width; return ( { thumbs.current[i] = node; }} type="button" tabIndex={chosen ? 0 : -1} aria-label={item.alt} aria-current={chosen} onPointerEnter={(event) => event.pointerType === "mouse" && choose(i)} onClick={() => choose(i)} initial={false} animate={{ width: w, height: w * 1.25 }} transition={reduce ? { duration: 0 } : GROW} className="shrink-0 overflow-hidden rounded-[3px] shadow-overlay outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-black/40" > {/* eslint-disable-next-line @next/next/no-img-element */} ); })}
); } ``` ## Carousel: Pager Photos with a pill-shaped pager under them. The active dot stretches into a bar that fills as it counts down, and the pager takes on each photo's colour. - Install: `@stillui/carousel-pager` - Import: `import { CarouselPager } from "@/components/ui/carousel-pager"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/carousel States it handles: - **Countdown**: The active dot stretches into a bar and fills from the left. When it is full, the next photo slides in; after the last, it goes back to the first. - **Hold**: Hovering or focusing anything in the carousel holds the countdown where it is. It carries on from there when you leave. - **Pause**: Press the active bar to stop autoplay, and again to start it. Screen readers hear which it will do. - **Colour**: Give a photo a color and the pager fades to it while that photo shows. Without one it uses the foreground colour. - **Ends**: Previous fades out on the first photo and next on the last, like a row of pages. - **Dots**: Every dot is a button with a 24px tall target, so the small dots are still easy to hit. - **Swipe**: Drag the photo sideways to change it. A short quick flick is enough. - **Announcements**: While autoplay runs, slide changes aren't announced; once it is paused, they are. - **Reduced motion**: Autoplay stays off and slides change without sliding. Notes: - autoPlay defaults to 5000ms. Pass 0 for a plain pager with no countdown. - Colours are mixed with color-mix, so any CSS colour works, including oklch and CSS variables. ```tsx "use client"; // stillui.dev/components/carousel#pager import { animate, motion, useMotionValue, useReducedMotion, useTransform, type AnimationPlaybackControls, type PanInfo } from "motion/react"; import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState, type CSSProperties } from "react"; import { cn } from "@/lib/utils"; // Settles on a slide without bouncing past it. const SETTLE = { type: "spring", stiffness: 260, damping: 34, mass: 0.9 } as const; // The active dot stretches to this width; the rest stay round. const DOT = 6; const BAR = 28; export type CarouselItem = { src: string; alt: string; /** Tints the pager while this photo shows. Any CSS colour; leave it out for the neutral foreground. */ color?: string; }; type CarouselPagerProps = { items: CarouselItem[]; defaultIndex?: number; index?: number; onIndexChange?: (index: number) => void; /** Milliseconds each photo stays before the next. The active dot fills as it counts down. Pass 0 to turn it off. */ autoPlay?: number; label?: string; className?: string; }; /** * Photos with a pill-shaped pager under them. The active dot stretches into a bar that fills as it counts down, and the pager takes on each photo's colour. */ export function CarouselPager({ items, defaultIndex = 0, index, onIndexChange, autoPlay = 5000, label = "Photos", className }: CarouselPagerProps) { const reduce = useReducedMotion() ?? false; const ids = useId(); const count = items.length; const viewRef = useRef(null); const [internal, setInternal] = useState(defaultIndex); const current = index ?? internal; const [hovered, setHovered] = useState(false); const [stopped, setStopped] = useState(false); const playing = autoPlay > 0 && !reduce && !stopped; const choose = useCallback( (next: number) => { const wrapped = ((next % count) + count) % count; if (index === undefined) setInternal(wrapped); onIndexChange?.(wrapped); }, [count, index, onIndexChange], ); // The track follows the index; a drag moves it by hand first. const x = useMotionValue(0); const [width, setWidth] = useState(0); useLayoutEffect(() => { const view = viewRef.current; if (!view) return; const measure = () => setWidth(view.offsetWidth); measure(); const observer = new ResizeObserver(measure); observer.observe(view); return () => observer.disconnect(); }, []); useEffect(() => { if (!width) return; if (reduce) x.set(-current * width); else { const run = animate(x, -current * width, SETTLE); return () => run.stop(); } }, [current, width, reduce, x]); // How far the countdown on the active dot has run, from 0 to 1. It holds while hovered or focused. const progress = useMotionValue(0); const fill = useTransform(progress, (p) => `${p * 100}%`); useEffect(() => { progress.set(0); }, [current, progress]); useEffect(() => { if (!playing || hovered) return; let run: AnimationPlaybackControls | undefined = animate(progress, 1, { duration: ((1 - progress.get()) * autoPlay) / 1000, ease: "linear", onComplete: () => { run = undefined; choose(current + 1); }, }); return () => run?.stop(); }, [playing, hovered, autoPlay, current, choose, progress]); const onPan = (_: PointerEvent, info: PanInfo) => x.set(-current * width + info.offset.x); const onPanEnd = (_: PointerEvent, info: PanInfo) => { const swipe = info.offset.x + info.velocity.x * 0.2; const next = Math.abs(swipe) > width * 0.2 ? current - Math.sign(swipe) : current; const clamped = Math.max(0, Math.min(count - 1, next)); if (clamped !== current) choose(clamped); else animate(x, -current * width, SETTLE); }; const tint = items[current]?.color ?? "var(--foreground)"; const vars = { "--tint": tint } as CSSProperties; return (
event.pointerType === "mouse" && setHovered(true)} onPointerLeave={() => setHovered(false)} onFocus={() => setHovered(true)} onBlur={(event) => !event.currentTarget.contains(event.relatedTarget) && setHovered(false)} >
{items.map((item, i) => (
{/* A plain img keeps the component free of Next.js; pass already-sized images. */} {/* eslint-disable-next-line @next/next/no-img-element */} {item.alt}
))}
choose(current - 1)} />
{items.map((item, i) => { const active = i === current; return ( ); })}
choose(current + 1)} /> {stopped ? "Autoplay is paused." : "Moves on by itself; hovering or focusing holds it."}
); } function Arrow({ direction, disabled, onClick }: { direction: 1 | -1; disabled: boolean; onClick: () => void }) { return ( ); } ``` ## Checkbox: Standard A choice that waits to be submitted. The check draws in, and a parent can show a partial selection. - Install: `@stillui/checkbox` - Import: `import { Checkbox } from "@/components/ui/checkbox"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/checkbox States it handles: - **Unchecked**: An outlined box on the card surface. - **Checked**: Fills with the primary color while the check draws in. - **Indeterminate**: A dash for “some selected”. Announced as mixed. Clicking selects all. - **Pressed**: Box shrinks slightly under the pointer. - **Focus**: Outline from the ring token. Space toggles. - **Disabled**: Box and label dim together. Notes: - Use a checkbox when the choice is applied later by a Save or Submit button. For settings that apply at once, use a switch. ```tsx "use client"; // stillui.dev/components/checkbox import { motion, useReducedMotion } from "motion/react"; import { useId, useState, type ReactNode } from "react"; import { cn } from "@/lib/utils"; const PRESS = { type: "spring", stiffness: 700, damping: 40, mass: 0.6 } as const; const DRAW = { duration: 0.2, ease: [0.16, 1, 0.3, 1] } as const; export type CheckedState = boolean | "indeterminate"; type CheckboxProps = { checked?: CheckedState; defaultChecked?: CheckedState; onCheckedChange?: (checked: boolean) => void; disabled?: boolean; label?: ReactNode; description?: ReactNode; className?: string; id?: string; }; export function Checkbox({ checked, defaultChecked = false, onCheckedChange, disabled, label, description, className, id, }: CheckboxProps) { const reduce = useReducedMotion(); const [internal, setInternal] = useState(defaultChecked); const controlled = checked !== undefined; const state = controlled ? checked : internal; const filled = state !== false; const autoId = useId(); const boxId = id ?? autoId; const descId = description ? `${boxId}-desc` : undefined; // Indeterminate moves to checked, like native checkboxes. const toggle = () => { if (disabled) return; const next = state !== true; if (!controlled) setInternal(next); onCheckedChange?.(next); }; return (
{state === "indeterminate" ? ( ) : ( )} {label || description ? (
{label ? ( ) : null} {description ? (

{description}

) : null}
) : null}
); } ``` ## Checkbox: Card A whole card that toggles, for choices that need an icon and a sentence of explanation. - Install: `@stillui/checkbox-card` - Import: `import { CheckboxCard } from "@/components/ui/checkbox-card"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/checkbox States it handles: - **Unchecked**: A raised card with an empty circle in the corner. - **Hover**: A thin outline shows the whole card is clickable. - **Checked**: A primary outline and a filled circle with a check that pops in. - **Press**: The card dips slightly so the tap feels received. - **Disabled**: Faded and not clickable. - **Keyboard**: One tab stop per card, toggled with Space, announced as a checkbox. Notes: - Group cards in a fieldset with a legend so screen readers hear what the choices are for. ```tsx "use client"; // stillui.dev/components/checkbox#card import { AnimatePresence, motion, useReducedMotion } from "motion/react"; import { useState, type ReactNode } from "react"; import { cn } from "@/lib/utils"; const PRESS = { type: "spring", stiffness: 600, damping: 38 } as const; type CheckboxCardProps = { title: ReactNode; description?: ReactNode; icon?: ReactNode; checked?: boolean; defaultChecked?: boolean; onCheckedChange?: (checked: boolean) => void; disabled?: boolean; className?: string; }; /** A whole card that toggles, for choices that need a sentence of explanation. */ export function CheckboxCard({ title, description, icon, checked, defaultChecked = false, onCheckedChange, disabled, className, }: CheckboxCardProps) { const reduce = useReducedMotion(); const [internal, setInternal] = useState(defaultChecked); const on = checked ?? internal; const toggle = () => { if (checked === undefined) setInternal(!on); onCheckedChange?.(!on); }; return ( {icon ? ( {icon} ) : null} {title} {description ? {description} : null} {on ? ( ) : null} ); } ``` ## Checkbox: Todo A round checkbox for task lists. Checking it draws a line through the text, which then steps back. - Install: `@stillui/checkbox-todo` - Import: `import { CheckboxTodo } from "@/components/ui/checkbox-todo"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/checkbox States it handles: - **Open**: An empty circle and the task in full color. - **Done**: The circle fills, a check draws in, and a line is drawn through the task from left to right. - **Undo**: Unchecking erases the line in reverse and brings the text back. - **Keyboard**: Tab to the circle and press Space. The task text is its label. - **Reduced motion**: The check and line appear without drawing. Notes: - The line runs through the middle of the label, so keep each task to a single line. ```tsx "use client"; // stillui.dev/components/checkbox#todo import { motion, useReducedMotion } from "motion/react"; import { useId, useState, type ReactNode } from "react"; import { cn } from "@/lib/utils"; const PRESS = { type: "spring", stiffness: 700, damping: 40, mass: 0.6 } as const; const STRIKE = { duration: 0.28, ease: [0.65, 0, 0.35, 1] } as const; type CheckboxTodoProps = { children: ReactNode; checked?: boolean; defaultChecked?: boolean; onCheckedChange?: (checked: boolean) => void; className?: string; }; /** A to-do item. Checking it draws a line through the text, which then steps back. */ export function CheckboxTodo({ children, checked, defaultChecked = false, onCheckedChange, className }: CheckboxTodoProps) { const reduce = useReducedMotion(); const [internal, setInternal] = useState(defaultChecked); const on = checked ?? internal; const id = useId(); const toggle = () => { if (checked === undefined) setInternal(!on); onCheckedChange?.(!on); }; return (
); } ``` ## Checkbox: Chips Several choices as compact chips, for filters and preferences. A check slides in on the ones that are on. - Install: `@stillui/checkbox-chips` - Import: `import { CheckboxChips } from "@/components/ui/checkbox-chips"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/checkbox States it handles: - **Off**: A quiet chip with only the label. - **On**: Fills with the primary color and a check slides in; neighbours shift to make room. - **Keyboard**: Each chip is its own tab stop with role checkbox, toggled with Space. - **Screen readers**: The chips sit in a labelled group, so the topic is announced once. - **Reduced motion**: The check appears without sliding and nothing shifts. Notes: - The check is there so the state doesn’t rely on color alone. ```tsx "use client"; // stillui.dev/components/checkbox#chips import { AnimatePresence, motion, useReducedMotion } from "motion/react"; import { useState } from "react"; import { cn } from "@/lib/utils"; const SPRING = { type: "spring", stiffness: 500, damping: 36 } as const; export type ChipOption = { value: string; label: string }; type CheckboxChipsProps = { /** Names the group for screen readers. */ label: string; options: ChipOption[]; value?: string[]; defaultValue?: string[]; onValueChange?: (value: string[]) => void; className?: string; }; /** Several choices as compact chips. A check slides in on the ones that are on. */ export function CheckboxChips({ label, options, value, defaultValue = [], onValueChange, className }: CheckboxChipsProps) { const reduce = useReducedMotion(); const [internal, setInternal] = useState(defaultValue); const selected = value ?? internal; const transition = reduce ? { duration: 0 } : SPRING; const toggle = (option: string) => { const next = selected.includes(option) ? selected.filter((v) => v !== option) : [...selected, option]; if (value === undefined) setInternal(next); onValueChange?.(next); }; return (
{options.map((option) => { const on = selected.includes(option.value); return ( toggle(option.value)} layout={!reduce} transition={transition} style={{ borderRadius: 999 }} className={cn( "inline-flex h-8 items-center px-3 text-[13px] font-medium transition-[color,background-color,box-shadow,scale] active:scale-[0.95] duration-200", on ? "bg-primary text-primary-foreground" : "bg-secondary text-secondary-foreground hover:bg-secondary/70", )} > {on ? ( ) : null} {option.label} ); })}
); } ``` ## Command (paid) A search palette over the page. Type to filter, move with the arrow keys or the pointer, and press Enter to choose. It is this site's search. - Install: `@stillui-pro/command` with an account token (see "Paid components" above) - Page: https://stillui.netlify.app/components/command ## Copy Field: Field A read-only value with a copy button that confirms in place and announces the result. - Install: `@stillui/copy-field` - Import: `import { CopyField } from "@/components/ui/copy-field"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/copy-field States it handles: - **Idle**: Long values truncate; the full value is still copied. - **Copied**: Icon swaps to a drawn check for 1.6s. Screen readers hear “Copied to clipboard”. - **Failed**: Clipboard blocked: the icon shows a cross and the failure is announced. ```tsx "use client"; // stillui.dev/components/copy-field import { AnimatePresence, motion, useReducedMotion } from "motion/react"; import { useEffect, useRef, useState } from "react"; import { cn } from "@/lib/utils"; const SWAP = { duration: 0.14, ease: [0.16, 1, 0.3, 1] } as const; type CopyFieldProps = { value: string; /** Shown before the value, e.g. "$" for a shell command. Not copied. */ prefix?: string; /** Accessible name for the copy button. */ label?: string; className?: string; onCopy?: (value: string) => void; }; export function CopyField({ value, prefix, label = "Copy", className, onCopy }: CopyFieldProps) { const reduce = useReducedMotion(); const [state, setState] = useState<"idle" | "copied" | "failed">("idle"); const timer = useRef(undefined); useEffect(() => () => window.clearTimeout(timer.current), []); const copy = async () => { try { await navigator.clipboard.writeText(value); setState("copied"); onCopy?.(value); } catch { setState("failed"); } window.clearTimeout(timer.current); timer.current = window.setTimeout(() => setState("idle"), 1600); }; const icon = { initial: { opacity: 0, scale: reduce ? 1 : 0.6, filter: reduce ? "none" : "blur(2px)" }, animate: { opacity: 1, scale: 1, filter: "blur(0px)" }, exit: { opacity: 0, scale: reduce ? 1 : 0.6, filter: reduce ? "none" : "blur(2px)" } }; return (
{prefix ? {prefix} : null} {value} {state === "copied" ? "Copied to clipboard" : state === "failed" ? "Copy failed" : ""}
); } ``` ## Copy Field: Button A labelled copy button for places where the value is already on screen. The label turns into “Copied” in place. - Install: `@stillui/copy-button` - Import: `import { CopyButton } from "@/components/ui/copy-button"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/copy-field States it handles: - **Idle**: A small secondary button with a copy icon and a label. - **Copied**: The label slides up to “Copied” with a green check, and the button resizes to fit. - **Failed**: Says it couldn’t copy, for browsers that block clipboard access. - **Reset**: Returns to the label after 1.6 seconds. - **Screen readers**: The result is announced through a live region. ```tsx "use client"; // stillui.dev/components/copy-field#button import { AnimatePresence, motion, useReducedMotion } from "motion/react"; import { useEffect, useRef, useState } from "react"; import { cn } from "@/lib/utils"; const SPRING = { type: "spring", stiffness: 520, damping: 38 } as const; type CopyButtonProps = { value: string; label?: string; copiedLabel?: string; className?: string; }; /** A labelled copy button. The label changes to “Copied” and the button reshapes around it. */ export function CopyButton({ value, label = "Copy", copiedLabel = "Copied", className }: CopyButtonProps) { const reduce = useReducedMotion(); const [state, setState] = useState<"idle" | "copied" | "failed">("idle"); const timer = useRef(undefined); const transition = reduce ? { duration: 0 } : SPRING; useEffect(() => () => window.clearTimeout(timer.current), []); const copy = async () => { try { await navigator.clipboard.writeText(value); setState("copied"); } catch { setState("failed"); } window.clearTimeout(timer.current); timer.current = window.setTimeout(() => setState("idle"), 1600); }; const text = state === "copied" ? copiedLabel : state === "failed" ? "Couldn’t copy" : label; return ( {state === "copied" ? ( ) : state === "failed" ? ( ) : ( <> )} {text} {state === "idle" ? "" : text} ); } ``` ## Copy Field: Command An install command with a switch for the package manager. Copies whichever command is showing. - Install: `@stillui/copy-command` - Import: `import { CopyCommand } from "@/components/ui/copy-command"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/copy-field States it handles: - **Switching**: A short underline glides to the chosen tool and the command slides into place. - **Copied**: The icon turns into a green check for 1.6 seconds. - **Keyboard**: The tools are a labelled group of toggle buttons; the copy button names the tool it copies. - **Screen readers**: A copy is announced through a live region. - **Reduced motion**: The underline jumps and the command swaps without sliding. Notes: - Remember the reader’s choice with localStorage if your docs show many commands. ```tsx "use client"; // stillui.dev/components/copy-field#command import { AnimatePresence, motion, useReducedMotion } from "motion/react"; import { useEffect, useId, useRef, useState } from "react"; import { cn } from "@/lib/utils"; const GLIDE = { type: "spring", stiffness: 500, damping: 40 } as const; type CopyCommandProps = { /** One command per tool, e.g. { npm: "npm i motion", pnpm: "pnpm add motion" }. */ commands: Record; /** The package manager showing. Leave it out and the component keeps its own. */ tool?: string; onToolChange?: (tool: string) => void; className?: string; }; /** An install command with a switch for the package manager. Copies whichever one is showing. */ export function CopyCommand({ commands, tool: controlled, onToolChange, className }: CopyCommandProps) { const reduce = useReducedMotion(); const tools = Object.keys(commands); const [internal, setInternal] = useState(tools[0]); const tool = controlled && commands[controlled] ? controlled : internal; const setTool = (next: string) => { if (controlled === undefined) setInternal(next); onToolChange?.(next); }; const [copied, setCopied] = useState(false); const timer = useRef(undefined); const indicatorId = useId(); useEffect(() => () => window.clearTimeout(timer.current), []); const copy = async () => { try { await navigator.clipboard.writeText(commands[tool]); setCopied(true); window.clearTimeout(timer.current); timer.current = window.setTimeout(() => setCopied(false), 1600); } catch {} }; return (
{tools.map((name) => ( ))}
$ {commands[tool]}
{copied ? "Copied to clipboard" : ""}
); } ``` ## Copy Field: Secret A hidden value such as an API key, with buttons to reveal it and copy it. Copying works without revealing. - Install: `@stillui/copy-secret` - Import: `import { CopySecret } from "@/components/ui/copy-secret"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/copy-field States it handles: - **Hidden**: Dots, plus the last four characters so people can tell keys apart. - **Revealed**: The value sharpens out of a blur and a slash draws across the eye icon. - **Copied**: The copy icon turns into a green check. The full value is copied even while hidden. - **Keyboard**: The reveal button is a toggle with aria-pressed; both buttons name the secret. - **Reduced motion**: No blur or drawing; the value swaps instantly. Notes: - Hiding on screen protects against people looking over a shoulder, not against anything else. Treat the value as secret on the server too. ```tsx "use client"; // stillui.dev/components/copy-field#secret import { AnimatePresence, motion, useReducedMotion } from "motion/react"; import { useEffect, useRef, useState } from "react"; import { cn } from "@/lib/utils"; type CopySecretProps = { value: string; /** Characters left visible at the end while hidden, so people can tell keys apart. */ visibleEnd?: number; label?: string; className?: string; }; function mask(value: string, visibleEnd: number) { return "•".repeat(Math.max(8, Math.min(24, value.length - visibleEnd))) + value.slice(-visibleEnd); } /** A hidden value, like an API key, with buttons to reveal it and copy it. Copying never needs revealing. */ export function CopySecret({ value, visibleEnd = 4, label = "Secret", className }: CopySecretProps) { const reduce = useReducedMotion(); const [revealed, setRevealed] = useState(false); const [copied, setCopied] = useState(false); const timer = useRef(undefined); useEffect(() => () => window.clearTimeout(timer.current), []); const copy = async () => { try { await navigator.clipboard.writeText(value); setCopied(true); window.clearTimeout(timer.current); timer.current = window.setTimeout(() => setCopied(false), 1600); } catch {} }; return (
{label} {revealed ? value : mask(value, visibleEnd)} {copied ? "Copied to clipboard" : ""}
); } ``` ## Segmented Control: Pill Pick one of two to five options. The selection glides between segments on a shared surface. - Install: `@stillui/segmented-control` - Import: `import { SegmentedControl } from "@/components/ui/segmented-control"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/segmented-control States it handles: - **Selected**: Raised surface and full-contrast text. - **Unselected**: Muted text; full contrast on hover. - **Keyboard**: One tab stop. Arrow keys move and select, like native radios. - **Reduced motion**: The selection jumps instead of gliding. Notes: - More than five options, or labels longer than a word or two, belong in a select or tabs. ```tsx "use client"; // stillui.dev/components/segmented-control import { motion, MotionConfig, useReducedMotion } from "motion/react"; import { useId, useRef, useState, type KeyboardEvent } from "react"; import { cn } from "@/lib/utils"; // The indicator moves within the same surface, so it uses an on-screen spring with no overshoot. const GLIDE = { type: "spring", stiffness: 420, damping: 40, mass: 0.8 } as const; type Option = { value: string; label: string }; type SegmentedControlProps = { options: Option[]; value?: string; defaultValue?: string; onValueChange?: (value: string) => void; /** Accessible name for the group, e.g. "Billing period". */ label: string; size?: "sm" | "md"; className?: string; }; export function SegmentedControl({ options, value, defaultValue, onValueChange, label, size = "md", className, }: SegmentedControlProps) { const reduce = useReducedMotion(); const layoutId = useId(); const [internal, setInternal] = useState(defaultValue ?? options[0]?.value); const current = value ?? internal; const refs = useRef<(HTMLButtonElement | null)[]>([]); const select = (next: string) => { if (value === undefined) setInternal(next); onValueChange?.(next); }; // Arrow keys move and select, matching native radio groups. const onKeyDown = (event: KeyboardEvent) => { const index = options.findIndex((o) => o.value === current); const step = event.key === "ArrowRight" || event.key === "ArrowDown" ? 1 : event.key === "ArrowLeft" || event.key === "ArrowUp" ? -1 : 0; if (!step) return; event.preventDefault(); const next = (index + step + options.length) % options.length; select(options[next].value); refs.current[next]?.focus(); }; return (
{options.map((option, i) => { const selected = option.value === current; return ( ); })}
); } ``` ## Segmented Control: Underline Text options with a short line that glides under the chosen one. Lighter than a filled control, with optional counts. - Install: `@stillui/segmented-underline` - Import: `import { SegmentedUnderline } from "@/components/ui/segmented-underline"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/segmented-control States it handles: - **Selected**: Full-color text with a line underneath. - **Others**: Muted text that brightens on hover. - **Switching**: The line glides across on a spring with no overshoot. - **Counts**: An optional number beside each label, in a quieter color. - **Keyboard**: One tab stop; arrow keys move and select, like a radio group. - **Reduced motion**: The line jumps instead of gliding. ```tsx "use client"; // stillui.dev/components/segmented-control#underline import { motion, useReducedMotion } from "motion/react"; import { useId, useRef, useState, type KeyboardEvent } from "react"; import { cn } from "@/lib/utils"; const GLIDE = { type: "spring", stiffness: 480, damping: 42 } as const; type Option = { value: string; label: string; count?: number }; type SegmentedUnderlineProps = { options: Option[]; value?: string; defaultValue?: string; onValueChange?: (value: string) => void; label: string; className?: string; }; /** Text options with a line that glides under the chosen one. Lighter than a filled control. */ export function SegmentedUnderline({ options, value, defaultValue, onValueChange, label, className }: SegmentedUnderlineProps) { const reduce = useReducedMotion(); const layoutId = useId(); const [internal, setInternal] = useState(defaultValue ?? options[0]?.value); const current = value ?? internal; const refs = useRef<(HTMLButtonElement | null)[]>([]); const select = (next: string) => { if (value === undefined) setInternal(next); onValueChange?.(next); }; const onKeyDown = (event: KeyboardEvent) => { const step = event.key === "ArrowRight" ? 1 : event.key === "ArrowLeft" ? -1 : 0; if (!step) return; event.preventDefault(); const index = options.findIndex((o) => o.value === current); const next = (index + step + options.length) % options.length; select(options[next].value); refs.current[next]?.focus(); }; return (
{options.map((option, i) => { const selected = option.value === current; return ( ); })}
); } ``` ## Segmented Control: Icons Icon-only options for view switches like grid, list and board. Each option keeps a text name for screen readers. - Install: `@stillui/segmented-icons` - Import: `import { SegmentedIcons } from "@/components/ui/segmented-icons"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/segmented-control States it handles: - **Selected**: The icon sits on a raised surface that glides between options. - **Others**: Muted icons that brighten on hover; the name shows as a native tooltip. - **Keyboard**: One tab stop; arrow keys move and select. - **Screen readers**: Every icon has a label, so the group reads as “Layout, Grid, selected”. - **Reduced motion**: The surface jumps instead of gliding. Notes: - Only use icons people already know. If you need a legend, use the labelled control instead. ```tsx "use client"; // stillui.dev/components/segmented-control#icons import { motion, useReducedMotion } from "motion/react"; import { useId, useRef, useState, type KeyboardEvent, type ReactNode } from "react"; import { cn } from "@/lib/utils"; const GLIDE = { type: "spring", stiffness: 420, damping: 40, mass: 0.8 } as const; type Option = { value: string; label: string; icon: ReactNode }; type SegmentedIconsProps = { options: Option[]; value?: string; defaultValue?: string; onValueChange?: (value: string) => void; label: string; className?: string; }; /** Icon-only options, for view switches like grid and list. Each option keeps a text name for screen readers. */ export function SegmentedIcons({ options, value, defaultValue, onValueChange, label, className }: SegmentedIconsProps) { const reduce = useReducedMotion(); const layoutId = useId(); const [internal, setInternal] = useState(defaultValue ?? options[0]?.value); const current = value ?? internal; const refs = useRef<(HTMLButtonElement | null)[]>([]); const select = (next: string) => { if (value === undefined) setInternal(next); onValueChange?.(next); }; const onKeyDown = (event: KeyboardEvent) => { const step = event.key === "ArrowRight" || event.key === "ArrowDown" ? 1 : event.key === "ArrowLeft" || event.key === "ArrowUp" ? -1 : 0; if (!step) return; event.preventDefault(); const index = options.findIndex((o) => o.value === current); const next = (index + step + options.length) % options.length; select(options[next].value); refs.current[next]?.focus(); }; return (
{options.map((option, i) => { const selected = option.value === current; return ( ); })}
); } ``` ## Segmented Control: Expanding Icons that make room for the chosen option’s label. Compact like an icon control, but never mysterious. - Install: `@stillui/segmented-expand` - Import: `import { SegmentedExpand } from "@/components/ui/segmented-expand"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/segmented-control States it handles: - **Selected**: Icon and label on a raised pill. - **Others**: Icons only, muted, brightening on hover. - **Switching**: The old label tucks away while the new one slides out, and the pill glides between them in one spring. - **Keyboard**: One tab stop; left and right arrows move and select. - **Screen readers**: Every option has its label as its name, shown or not. - **Reduced motion**: Labels swap and the pill jumps without sliding. ```tsx "use client"; // stillui.dev/components/segmented-control#expand import { AnimatePresence, motion, MotionConfig, useReducedMotion } from "motion/react"; import { useId, useRef, useState, type KeyboardEvent, type ReactNode } from "react"; import { cn } from "@/lib/utils"; const SPRING = { type: "spring", stiffness: 460, damping: 38 } as const; type Option = { value: string; label: string; icon: ReactNode }; type SegmentedExpandProps = { options: Option[]; value?: string; defaultValue?: string; onValueChange?: (value: string) => void; label: string; className?: string; }; /** Icons that make room for the chosen option’s label. The control stays compact but never mysterious. */ export function SegmentedExpand({ options, value, defaultValue, onValueChange, label, className }: SegmentedExpandProps) { const reduce = useReducedMotion(); const layoutId = useId(); const [internal, setInternal] = useState(defaultValue ?? options[0]?.value); const current = value ?? internal; const refs = useRef<(HTMLButtonElement | null)[]>([]); const select = (next: string) => { if (value === undefined) setInternal(next); onValueChange?.(next); }; const onKeyDown = (event: KeyboardEvent) => { const step = event.key === "ArrowRight" ? 1 : event.key === "ArrowLeft" ? -1 : 0; if (!step) return; event.preventDefault(); const index = options.findIndex((o) => o.value === current); const next = (index + step + options.length) % options.length; select(options[next].value); refs.current[next]?.focus(); }; return (
{options.map((option, i) => { const selected = option.value === current; return ( { refs.current[i] = el; }} layout={!reduce} type="button" role="radio" aria-checked={selected} aria-label={option.label} tabIndex={selected ? 0 : -1} onClick={() => select(option.value)} style={{ borderRadius: 999 }} className={cn( "relative flex h-8 items-center px-2 text-[13px] font-medium transition-[color,background-color,box-shadow,scale] active:scale-[0.95] duration-150 [&_svg]:relative [&_svg]:size-4 [&_svg]:shrink-0", selected ? "text-foreground" : "text-muted-foreground hover:text-foreground", )} > {selected ? ( ) : null} {option.icon} {selected ? ( {option.label} ) : null} ); })}
); } ``` ## Sidebar: Collapsible An app sidebar with sections that folds down to an icon rail. The active item’s surface glides between rows. - Install: `@stillui/sidebar` - Import: `import { Sidebar } from "@/components/ui/sidebar"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/sidebar States it handles: - **Expanded**: Logo and name, section titles, and items with icons and labels. - **Active**: A raised surface sits behind the current page and glides to the next one. - **Collapsing**: Width springs down to 60 px; labels fade first so text never squashes. - **Collapsed**: Icons only. Each link keeps its name for screen readers and as a native tooltip. - **Links**: Items are real links with aria-current="page", so they work with any router. - **Reduced motion**: Width and surface change instantly. Notes: - Pass href on items to navigate; leave it off to handle selection yourself, as the demo does. - On phones, show the expanded sidebar in a sheet instead of collapsing it. ```tsx "use client"; // stillui.dev/components/sidebar import { AnimatePresence, motion, MotionConfig, useReducedMotion, type Variants } from "motion/react"; import { useEffect, useId, useState, type ElementType, type MouseEvent, type ReactNode } from "react"; import { cn } from "@/lib/utils"; const OPEN_WIDTH = 240; const CLOSED_WIDTH = 60; const EASE_OUT = [0.16, 1, 0.3, 1] as const; // Damped just past critical: the width settles against the rail without overshooting it. const WIDTH_SPRING = { type: "spring", stiffness: 380, damping: 36, mass: 0.8 } as const; // The surfaces that follow the active page and the pointer. const GLIDE = { type: "spring", stiffness: 520, damping: 42 } as const; // Pages under a group unfold in height, so rows below glide down instead of jumping, // then arrive one after another. Closing runs the stagger in reverse, quicker. const SUBMENU: Variants = { closed: { height: 0, opacity: 0, transition: { duration: 0.18, ease: EASE_OUT, staggerChildren: 0.02, staggerDirection: -1 } }, open: { height: "auto", opacity: 1, transition: { duration: 0.26, ease: EASE_OUT, delayChildren: 0.03, staggerChildren: 0.04 } }, }; const SUBMENU_ROW: Variants = { closed: { opacity: 0, y: -4, filter: "blur(2px)" }, open: { opacity: 1, y: 0, filter: "blur(0px)", transition: { duration: 0.2, ease: EASE_OUT } }, }; export type SidebarPage = { value: string; label: string; href?: string }; export type SidebarItem = { value: string; label: string; icon: ReactNode; href?: string; /** Pages tucked under this item. The item becomes a group that unfolds. */ children?: SidebarPage[]; }; export type SidebarSection = { title?: string; items: SidebarItem[] }; type SidebarProps = { /** Name shown at the top, e.g. the workspace. */ title: ReactNode; /** A small mark shown at the top, which is all that remains when collapsed. */ logo: ReactNode; sections: SidebarSection[]; value?: string; defaultValue?: string; onValueChange?: (value: string) => void; defaultCollapsed?: boolean; /** Groups open at first. Defaults to the group holding the current page. */ defaultOpen?: string[]; /** Renders page links, e.g. Next.js Link, so navigation stays client-side. Defaults to . */ linkComponent?: ElementType; className?: string; }; /** * An app sidebar that folds down to an icon rail. Labels slide away and back, groups unfold * their pages one after another, and the active surface glides wherever the current page is. */ export function Sidebar({ title, logo, sections, value, defaultValue, onValueChange, defaultCollapsed = false, defaultOpen, linkComponent: Link = "a", className, }: SidebarProps) { const reduce = useReducedMotion() ?? false; const ids = useId(); const [internal, setInternal] = useState(defaultValue ?? sections[0]?.items[0]?.value); const [collapsed, setCollapsed] = useState(defaultCollapsed); const [hovered, setHovered] = useState(null); const current = value ?? internal; const items = sections.flatMap((s) => s.items); const [open, setOpen] = useState( () => defaultOpen ?? items.filter((i) => i.children?.some((c) => c.value === current)).map((i) => i.value), ); // Ctrl+B or ⌘B folds and unfolds the sidebar, except while writing rich text. useEffect(() => { const onKey = (event: KeyboardEvent) => { if (event.key.toLowerCase() !== "b" || !(event.metaKey || event.ctrlKey) || event.altKey || event.shiftKey) return; if (event.target instanceof Element && event.target.closest("[contenteditable='true']")) return; event.preventDefault(); setCollapsed((c) => !c); }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); }, []); const select = (page: SidebarPage) => (event: MouseEvent) => { if (!page.href) event.preventDefault(); if (value === undefined) setInternal(page.value); onValueChange?.(page.value); }; const toggleGroup = (group: string) => { // From the rail, a group can't show its pages: unfold the sidebar and open the group there. if (collapsed) { setCollapsed(false); setOpen((o) => (o.includes(group) ? o : [...o, group])); return; } setOpen((o) => (o.includes(group) ? o.filter((g) => g !== group) : [...o, group])); }; const surfaces = (row: string, active: boolean) => ( <> {hovered === row && !active ? ( ) : null} {active ? : null} ); const rowClass = (active: boolean) => cn( "relative flex h-9 w-full items-center gap-2.5 rounded-lg px-[11px] text-left text-sm transition-colors duration-150 [&_svg]:size-[18px] [&_svg]:shrink-0", active ? "font-medium text-foreground" : "text-muted-foreground hover:text-foreground", ); const press = reduce ? undefined : { scale: 0.98 }; return (
{logo}
setCollapsed((c) => !c)} aria-expanded={!collapsed} aria-label={collapsed ? "Expand sidebar" : "Collapse sidebar"} aria-keyshortcuts="Control+B Meta+B" title={collapsed ? "Expand (Ctrl or ⌘ B)" : "Collapse (Ctrl or ⌘ B)"} whileTap={press} className="flex h-9 shrink-0 items-center gap-2.5 rounded-lg px-[11px] text-sm text-muted-foreground transition-colors hover:bg-background/60 hover:text-foreground" >
); } /** * Text that slides away as the sidebar narrows and back once it has room. It stays mounted, * so nothing reflows mid-animation: leaving is quick, arriving waits for the width to open. */ function Label({ show, reduce, className, children }: { show: boolean; reduce: boolean; className?: string; children: ReactNode }) { return ( {children} ); } ``` ## Sidebar: Rail (paid) A narrow icon rail that opens into a full sidebar. Closed, names slide out beside each icon on hover or focus; open, they sit beside the icons. - Install: `@stillui-pro/sidebar-rail` with an account token (see "Paid components" above) - Page: https://stillui.netlify.app/components/sidebar ## Sidebar: Tree Grouped pages hanging from a thin guide line, for docs and settings. The active page lights up its stretch of the line. - Install: `@stillui/sidebar-tree` - Import: `import { SidebarTree } from "@/components/ui/sidebar-tree"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/sidebar States it handles: - **Group closed**: An icon, the group name and a small arrow. - **Group open**: Pages unfold under a thin guide line; the arrow turns down. - **Active page**: A darker segment on the guide line glides to the current page, even across groups. - **Active group**: The group holding the current page keeps a stronger title, even when closed. - **Keyboard**: Group titles are buttons with aria-expanded; pages are links with aria-current. - **Reduced motion**: Groups open and the marker moves without animating. Notes: - Pass linkComponent={Link} from your router so moving between pages doesn’t reload. - Two levels is the limit. If you need a third, the information wants a different structure, not a deeper tree. ```tsx "use client"; // stillui.dev/components/sidebar#tree import { AnimatePresence, motion, MotionConfig, useReducedMotion } from "motion/react"; import { useId, useState, type ElementType, type MouseEvent, type ReactNode } from "react"; import { cn } from "@/lib/utils"; const SPRING = { type: "spring", stiffness: 420, damping: 40 } as const; export type TreeLink = { value: string; label: string; href?: string }; export type TreeGroup = { value: string; label: string; icon: ReactNode; children: TreeLink[] }; type SidebarTreeProps = { groups: TreeGroup[]; value?: string; defaultValue?: string; onValueChange?: (value: string) => void; defaultOpen?: string[]; /** Renders page links, e.g. Next.js Link, so navigation stays client-side. Defaults to
. */ linkComponent?: ElementType; className?: string; }; /** Grouped pages hanging from a thin guide line. The active page lights up its stretch of the line. */ export function SidebarTree({ groups, value, defaultValue, onValueChange, defaultOpen, linkComponent: Link = "a", className }: SidebarTreeProps) { const reduce = useReducedMotion(); const markerId = useId(); const [internal, setInternal] = useState(defaultValue ?? groups[0]?.children[0]?.value); const [open, setOpen] = useState(defaultOpen ?? groups.slice(0, 1).map((g) => g.value)); const current = value ?? internal; const select = (link: TreeLink) => (event: MouseEvent) => { if (!link.href) event.preventDefault(); if (value === undefined) setInternal(link.value); onValueChange?.(link.value); }; const toggle = (group: string) => setOpen((o) => (o.includes(group) ? o.filter((g) => g !== group) : [...o, group])); return ( ); } ``` ## Sidebar: Dot A quiet text list where the current page steps aside for a dot. The dot runs between pages, stretching with its speed. - Install: `@stillui/sidebar-dot` - Import: `import { SidebarDot } from "@/components/ui/sidebar-dot"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/sidebar States it handles: - **Resting**: Group titles with a small icon, and plain page names underneath. No surfaces, no lines. - **Current page**: Its name slides right to make room, and a dot sits in the space it left. - **Moving**: The dot runs down or up the gutter and stretches into a droplet the faster it goes, then lands round. The old name slides back as it leaves. - **Across groups**: One dot for the whole list, so it travels past group titles too. - **Header**: An optional slot above the groups, for a logo, an action or a search field. - **Reduced motion**: The dot and the names jump to their places. Notes: - This site’s own sidebar is this component. Pass linkComponent={Link} from your router so moving between pages doesn’t reload. - Best for long lists of pages, like docs, where surfaces on every row would get heavy. ```tsx "use client"; // stillui.dev/components/sidebar#dot import { animate, motion, useMotionValue, useReducedMotion, useTransform, useVelocity } from "motion/react"; import { useLayoutEffect, useRef, useState, type ElementType, type MouseEvent, type ReactNode } from "react"; import { cn } from "@/lib/utils"; const DOT = 6; const TRAVEL = { type: "spring", stiffness: 520, damping: 38, mass: 0.6 } as const; export type DotLink = { value: string; label: string; href?: string }; export type DotGroup = { value: string; label: string; icon?: ReactNode; links: DotLink[] }; type SidebarDotProps = { groups: DotGroup[]; /** Shown above the groups: a logo and an action, or a search field. */ header?: ReactNode; value?: string; defaultValue?: string; onValueChange?: (value: string) => void; /** Renders page links, e.g. Next.js Link, so navigation stays client-side. Defaults to . */ linkComponent?: ElementType; className?: string; }; /** * A quiet text list where the current page steps aside for a dot. Moving to another page, * the dot runs down the gutter, stretching with its speed, and settles round when it lands. */ export function SidebarDot({ groups, header, value, defaultValue, onValueChange, linkComponent: Link = "a", className }: SidebarDotProps) { const reduce = useReducedMotion(); const [internal, setInternal] = useState(defaultValue ?? groups[0]?.links[0]?.value); const current = value ?? internal; const listRef = useRef(null); const rows = useRef(new Map()); const placed = useRef(false); // The dot stretches along its path the faster it moves, and thins to keep its volume. const y = useMotionValue(0); const speed = useVelocity(y); const scaleY = useTransform(speed, (v) => 1 + Math.min(Math.abs(v) / 900, 2.2)); const scaleX = useTransform(scaleY, (s) => 1 / Math.sqrt(s)); const opacity = useMotionValue(0); useLayoutEffect(() => { const list = listRef.current; if (!list) return; const targetFor = () => { const row = current ? rows.current.get(current) : undefined; if (!row) return null; return row.getBoundingClientRect().top - list.getBoundingClientRect().top + (row.offsetHeight - DOT) / 2; }; const target = targetFor(); if (target === null) { opacity.set(0); return; } opacity.set(1); // First placement and reduced motion jump; every later change travels. const controls = placed.current && !reduce ? animate(y, target, TRAVEL) : (y.set(target), undefined); placed.current = true; // Groups above can change height (fonts loading, a resize): keep the dot on its row. const observer = new ResizeObserver(() => { const next = targetFor(); if (next !== null && !y.isAnimating()) y.set(next); }); observer.observe(list); return () => { controls?.stop(); observer.disconnect(); }; }, [current, reduce, y, opacity]); const select = (link: DotLink) => (event: MouseEvent) => { if (!link.href) event.preventDefault(); if (value === undefined) setInternal(link.value); onValueChange?.(link.value); }; return ( ); } ``` ## Sidebar: Floating A compact menu card that floats off the edge, with counts for new items. A soft highlight follows the pointer row to row. - Install: `@stillui/sidebar-floating` - Import: `import { SidebarFloating } from "@/components/ui/sidebar-floating"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/sidebar States it handles: - **Active**: The current page sits on a solid surface with stronger text. - **Hover**: A lighter surface glides between rows under the pointer, and fades when it leaves the menu. - **Counts**: A small red count for new items, read as “3 new” by screen readers. - **Keyboard**: Focus moves the same highlight, so keyboard and pointer feel alike. - **Reduced motion**: The highlight jumps between rows. Notes: - Sized by its content, not the window height, so it suits small apps and tools with few destinations. ```tsx "use client"; // stillui.dev/components/sidebar#floating import { AnimatePresence, motion, MotionConfig, useReducedMotion } from "motion/react"; import { useId, useState, type ElementType, type MouseEvent, type ReactNode } from "react"; import { cn } from "@/lib/utils"; const GLIDE = { type: "spring", stiffness: 520, damping: 42 } as const; export type FloatingItem = { value: string; label: string; icon: ReactNode; href?: string; count?: number }; type SidebarFloatingProps = { /** Shown at the top: an avatar and a name, for example. */ header: ReactNode; items: FloatingItem[]; value?: string; defaultValue?: string; onValueChange?: (value: string) => void; /** Renders page links, e.g. Next.js Link, so navigation stays client-side. Defaults to . */ linkComponent?: ElementType; className?: string; }; /** A compact menu that floats off the edge. A soft highlight follows the pointer from row to row. */ export function SidebarFloating({ header, items, value, defaultValue, onValueChange, linkComponent: Link = "a", className }: SidebarFloatingProps) { const reduce = useReducedMotion(); const hoverId = useId(); const [internal, setInternal] = useState(defaultValue ?? items[0]?.value); const [hovered, setHovered] = useState(null); const current = value ?? internal; const select = (item: FloatingItem) => (event: MouseEvent) => { if (!item.href) event.preventDefault(); if (value === undefined) setInternal(item.value); onValueChange?.(item.value); }; return ( ); } ``` ## Sidebar: Two-level (paid) Two levels side by side: an icon rail picks the section and a panel lists its pages. Press the section again to fold the panel. - Install: `@stillui-pro/sidebar-panels` with an account token (see "Paid components" above) - Page: https://stillui.netlify.app/components/sidebar ## Sidebar: Stretch line A text-only list with a line on the left. Moving pages, the line stretches to cover both rows, then lets go of the old one. - Install: `@stillui/sidebar-stretch` - Import: `import { SidebarStretch } from "@/components/ui/sidebar-stretch"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/sidebar States it handles: - **Resting**: A short dark segment on the guide line beside the current page. - **Moving**: The segment reaches toward the new page until it spans both, then lets go of the old one. - **Long jumps**: The stretch covers every row in between, so the eye follows the distance travelled. - **Keyboard**: Plain links with aria-current; the line is decoration only. - **Reduced motion**: The segment jumps straight to the new page. Notes: - Made for settings pages and docs where labels carry the meaning and icons would be noise. ```tsx "use client"; // stillui.dev/components/sidebar#stretch import { motion, useReducedMotion } from "motion/react"; import { useState, type ElementType, type MouseEvent, type ReactNode } from "react"; import { cn } from "@/lib/utils"; const ROW = 36; const GAP = 2; export type StretchItem = { value: string; label: string; href?: string }; type SidebarStretchProps = { title?: ReactNode; items: StretchItem[]; value?: string; defaultValue?: string; onValueChange?: (value: string) => void; /** Renders page links, e.g. Next.js Link, so navigation stays client-side. Defaults to . */ linkComponent?: ElementType; className?: string; }; /** * A text-only list with a line on the left. Moving to another page, the line first stretches * to cover both rows, then lets go of the old one, like an inchworm. */ export function SidebarStretch({ title, items, value, defaultValue, onValueChange, linkComponent: Link = "a", className }: SidebarStretchProps) { const reduce = useReducedMotion(); const [internal, setInternal] = useState(defaultValue ?? items[0]?.value); const current = value ?? internal; const index = Math.max(0, items.findIndex((i) => i.value === current)); const [from, setFrom] = useState(index); const top = (i: number) => i * (ROW + GAP) + 8; const height = ROW - 16; const select = (item: StretchItem) => (event: MouseEvent) => { if (!item.href) event.preventDefault(); setFrom(index); if (value === undefined) setInternal(item.value); onValueChange?.(item.value); }; // Stretch from the old row to the new one, then shrink onto the new row. const span = Math.abs(index - from); const lead = Math.min(top(from), top(index)); const keyframes = reduce || span === 0 ? { top: top(index), height } : { top: [top(from), lead, top(index)], height: [height, span * (ROW + GAP) + height, height] }; return ( ); } ``` ## Sidebar: Menu (paid) Navigation tucked behind a menu button, with search that filters the pages in place. For sites where content should get the whole width. - Install: `@stillui-pro/sidebar-menu` with an account token (see "Paid components" above) - Page: https://stillui.netlify.app/components/sidebar ## Slider: Standard Pick a value in a range. Built on the native range input, with the value always visible beside the label. - Install: `@stillui/slider` - Import: `import { Slider } from "@/components/ui/slider"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/slider States it handles: - **Resting**: Formatted value sits next to the label in tabular numbers, so it doesn’t wobble. - **Dragging**: Thumb grows slightly and a bubble shows the value above your finger. - **Keyboard**: Arrow keys, Page Up/Down, Home and End all work natively. Focus ring around the track. - **Screen readers**: Announces the formatted value (e.g. “$1,200”), not the raw number. - **Disabled**: Dims and stops responding. Notes: - If people need an exact number, pair the slider with a text field. Sliders are for “roughly this much”. ```tsx "use client"; // stillui.dev/components/slider import { AnimatePresence, motion, useReducedMotion, useSpring, useTransform } from "motion/react"; import { useEffect, useId, useState, type ReactNode } from "react"; import { cn } from "@/lib/utils"; const PRESS = { type: "spring", stiffness: 600, damping: 32, mass: 0.6 } as const; // Damped past critical: the thumb glides to a clicked spot and tracks a drag without ever rebounding. const GLIDE = { stiffness: 700, damping: 50, mass: 0.5 }; type SliderProps = { label: ReactNode; value?: number; defaultValue?: number; onValueChange?: (value: number) => void; min?: number; max?: number; step?: number; /** Formats the number shown next to the label and in the bubble. */ format?: (value: number) => string; disabled?: boolean; className?: string; }; export function Slider({ label, value, defaultValue = 50, onValueChange, min = 0, max = 100, step = 1, format = String, disabled, className, }: SliderProps) { const reduce = useReducedMotion(); const id = useId(); const [internal, setInternal] = useState(defaultValue); const [active, setActive] = useState(false); const current = value ?? internal; const percent = ((current - min) / (max - min)) * 100; // Thumb and fill read a spring that follows the value, so a click far along the track glides there. const glide = useSpring(percent, GLIDE); useEffect(() => { if (reduce) glide.jump(percent); else glide.set(percent); }, [percent, reduce, glide]); const fillWidth = useTransform(glide, (p) => `${p}%`); const thumbLeft = useTransform(glide, (p) => `${p}%`); const change = (next: number) => { if (value === undefined) setInternal(next); onValueChange?.(next); }; return (
{format(current)}
{/* Visuals. The native range input on top handles pointer, keyboard and screen readers. */}
{active ? ( {format(current)} ) : null} change(Number(e.target.value))} onPointerDown={() => setActive(true)} onPointerUp={() => setActive(false)} onPointerCancel={() => setActive(false)} onBlur={() => setActive(false)} className="peer absolute inset-0 size-full cursor-pointer opacity-0 disabled:cursor-not-allowed" /> {/* Keyboard focus ring drawn around the track, since the input itself is invisible. */}
); } ``` ## Slider: Stepped A slider that snaps to named stops like Off, Weekly, Daily. Each stop has a dot and a label you can click. - Install: `@stillui/slider-stepped` - Import: `import { SliderStepped } from "@/components/ui/slider-stepped"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/slider States it handles: - **Resting**: Dots fill up to the current stop; its name is bold below and repeated beside the label. - **Snapping**: The thumb and fill settle on the next stop with a short spring. - **Description**: An optional line under the slider explains what the current stop means. - **Shortcuts**: Clicking a stop’s name jumps straight to it. - **Keyboard**: A native range input, so arrows, Home and End work. The stop name is read out, not its number. - **Reduced motion**: The thumb jumps between stops. Notes: - Use it for three to six ordered choices. For unordered choices use a segmented control. ```tsx "use client"; // stillui.dev/components/slider#stepped import { motion, useReducedMotion } from "motion/react"; import { useId, useState, type ReactNode } from "react"; import { cn } from "@/lib/utils"; const SETTLE = { type: "spring", stiffness: 520, damping: 34 } as const; type SliderSteppedProps = { label: ReactNode; /** The named stops, from lowest to highest. */ steps: string[]; value?: number; defaultValue?: number; onValueChange?: (index: number) => void; /** One line under the slider describing the current step. */ describe?: (index: number) => ReactNode; className?: string; }; /** A slider that snaps to named stops, like Off, Low, Medium, High. Each stop is labelled under its dot. */ export function SliderStepped({ label, steps, value, defaultValue = 0, onValueChange, describe, className }: SliderSteppedProps) { const reduce = useReducedMotion(); const id = useId(); const [internal, setInternal] = useState(defaultValue); const current = value ?? internal; const last = steps.length - 1; const percent = (current / last) * 100; const change = (next: number) => { if (value === undefined) setInternal(next); onValueChange?.(next); }; return (
{steps[current]}
{steps.map((step, i) => ( ))} change(Number(e.target.value))} className="peer absolute -inset-x-2.5 inset-y-0 h-full w-[calc(100%+1.25rem)] cursor-pointer opacity-0" />
{/* Stop names, each centered under its dot; the ends align to the edges so they never overflow. */}
{steps.map((step, i) => ( ))}
{describe ?

{describe(current)}

: null}
); } ``` ## Slider: Range Pick a band, such as a price range, with two thumbs on one track. Built on two native range inputs. - Install: `@stillui/slider-range` - Import: `import { SliderRange } from "@/components/ui/slider-range"` - Dependencies: none - Page: https://stillui.netlify.app/components/slider States it handles: - **Resting**: The fill spans between the thumbs; both ends are written beside the label. - **Dragging**: Each thumb can be grabbed on its own. They can’t cross, and stay minGap apart. - **Stacked at the top**: When the low thumb is pushed to the far end it moves on top, so it can still be grabbed. - **Keyboard**: Two tab stops, named Minimum and Maximum, each with arrows, Home and End. - **Focus**: The focused thumb gets the focus ring, since the inputs themselves are invisible. Notes: - No animation library needed. The thumbs follow the pointer directly, which feels best for precise picks. ```tsx "use client"; // stillui.dev/components/slider#range import { motion, useReducedMotion, useSpring, useTransform, type MotionValue } from "motion/react"; import { useEffect, useId, useState, type ReactNode } from "react"; import { cn } from "@/lib/utils"; type Range = [number, number]; // Damped past critical: positions glide to a clicked spot and track a drag without ever rebounding. const GLIDE = { stiffness: 700, damping: 50, mass: 0.5 }; const PRESS = { type: "spring", stiffness: 600, damping: 32, mass: 0.6 } as const; /** A spring that follows a percentage, or jumps to it when motion is reduced. */ function useGlide(percent: number, reduce: boolean): MotionValue { const glide = useSpring(percent, GLIDE); useEffect(() => { if (reduce) glide.jump(percent); else glide.set(percent); }, [percent, reduce, glide]); return glide; } type SliderRangeProps = { label: ReactNode; value?: Range; defaultValue?: Range; onValueChange?: (value: Range) => void; min?: number; max?: number; step?: number; /** The smallest gap allowed between the two ends. */ minGap?: number; format?: (value: number) => string; className?: string; }; // Native inputs stacked on one track. Only their thumbs catch the pointer, so each end can be grabbed. const input = cn( "pointer-events-none absolute inset-0 h-full w-full appearance-none bg-transparent opacity-0 focus-visible:opacity-0", "[&::-webkit-slider-thumb]:pointer-events-auto [&::-webkit-slider-thumb]:size-6 [&::-webkit-slider-thumb]:cursor-grab [&::-webkit-slider-thumb]:appearance-none", "[&::-moz-range-thumb]:pointer-events-auto [&::-moz-range-thumb]:size-6 [&::-moz-range-thumb]:cursor-grab [&::-moz-range-thumb]:border-0", ); /** Pick a range, such as a price band, with two thumbs on one track. */ export function SliderRange({ label, value, defaultValue = [20, 80], onValueChange, min = 0, max = 100, step = 1, minGap = 0, format = String, className, }: SliderRangeProps) { const id = useId(); const reduce = useReducedMotion() ?? false; const [internal, setInternal] = useState(defaultValue); const [held, setHeld] = useState<0 | 1 | null>(null); const [low, high] = value ?? internal; const [focused, setFocused] = useState<0 | 1 | null>(null); const percent = (n: number) => ((n - min) / (max - min)) * 100; // Both ends and the fill between them glide, so keyboard steps and quick drags move smoothly. const lowGlide = useGlide(percent(low), reduce); const highGlide = useGlide(percent(high), reduce); const fillLeft = useTransform(lowGlide, (p) => `${p}%`); const fillRight = useTransform(highGlide, (p) => `${100 - p}%`); const thumbLeft = [useTransform(lowGlide, (p) => `${p}%`), useTransform(highGlide, (p) => `${p}%`)]; const change = (next: Range) => { if (value === undefined) setInternal(next); onValueChange?.(next); }; return (
{label} {format(low)} – {format(high)}
{[0, 1].map((i) => ( ))}
change([Math.min(Number(e.target.value), high - minGap), high])} onFocus={(e) => e.currentTarget.matches(":focus-visible") && setFocused(0)} onBlur={() => setFocused(null)} onPointerDown={() => setHeld(0)} onPointerUp={() => setHeld(null)} onPointerCancel={() => setHeld(null)} className={cn(input, low > max - (max - min) / 10 && "z-10")} /> change([low, Math.max(Number(e.target.value), low + minGap)])} onFocus={(e) => e.currentTarget.matches(":focus-visible") && setFocused(1)} onBlur={() => setFocused(null)} onPointerDown={() => setHeld(1)} onPointerUp={() => setHeld(null)} onPointerCancel={() => setHeld(null)} className={input} />
); } ``` ## Slider: Ruler (paid) A ruler of ticks under a large readout. Ticks up to the value darken, so the amount reads at a glance. - Install: `@stillui-pro/slider-ruler` with an account token (see "Paid components" above) - Page: https://stillui.netlify.app/components/slider ## Switch: Standard An on/off setting with a label and a one-line description. The thumb travels without overshoot. - Install: `@stillui/switch` - Import: `import { Switch } from "@/components/ui/switch"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/switch States it handles: - **Off / On**: Track color carries the state; thumb position confirms it for color-blind users. - **Pressed**: Thumb stretches slightly toward where it is going. - **Focus**: Outline on the track. Space toggles. - **Disabled**: The whole row dims so the label reads as unavailable too. Notes: - Use a switch for settings that apply immediately. If the change waits for a Save button, use a checkbox. ```tsx "use client"; // stillui.dev/components/switch import { motion, useReducedMotion } from "motion/react"; import { useId, useState, type ReactNode } from "react"; import { cn } from "@/lib/utils"; // A short travel with no overshoot: switches get flipped often, so they stay quick. const THUMB = { type: "spring", stiffness: 600, damping: 38, mass: 0.7 } as const; type SwitchProps = { checked?: boolean; defaultChecked?: boolean; onCheckedChange?: (checked: boolean) => void; disabled?: boolean; /** Visible label. Clicking it toggles the switch. */ label?: ReactNode; /** One line under the label explaining the effect. */ description?: ReactNode; className?: string; id?: string; }; export function Switch({ checked, defaultChecked = false, onCheckedChange, disabled, label, description, className, id, }: SwitchProps) { const reduce = useReducedMotion(); const [internal, setInternal] = useState(defaultChecked); const controlled = checked !== undefined; const on = controlled ? checked : internal; const autoId = useId(); const switchId = id ?? autoId; const descId = description ? `${switchId}-desc` : undefined; const toggle = () => { if (disabled) return; if (!controlled) setInternal(!on); onCheckedChange?.(!on); }; return (
{label || description ? (
{label ? ( ) : null} {description ? (

{description}

) : null}
) : null}
); } ``` ## Switch: Stretch The thumb stretches toward the other side while you press, then slides there when you let go. - Install: `@stillui/switch-stretch` - Import: `import { SwitchStretch } from "@/components/ui/switch-stretch"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/switch States it handles: - **Off / on**: A round thumb on the left or the right; the track fills with the primary color when on. - **Pressed**: The thumb widens into a pill, like a finger pushing it. - **Released**: The thumb slides to the other side and returns to a circle in the same spring. - **Keyboard**: role switch with aria-checked; Space and Enter toggle it. - **Reduced motion**: No stretch or slide; the thumb jumps to its side. Notes: - Bigger than the standard switch, so it suits touch-first settings screens. ```tsx "use client"; // stillui.dev/components/switch#stretch import { motion, useReducedMotion } from "motion/react"; import { useId, useState, type ReactNode } from "react"; import { cn } from "@/lib/utils"; const SPRING = { type: "spring", stiffness: 520, damping: 34, mass: 0.7 } as const; type SwitchStretchProps = { checked?: boolean; defaultChecked?: boolean; onCheckedChange?: (checked: boolean) => void; label?: ReactNode; className?: string; }; /** A switch whose thumb stretches toward the other side while pressed, then slides there on release. */ export function SwitchStretch({ checked, defaultChecked = false, onCheckedChange, label, className }: SwitchStretchProps) { const reduce = useReducedMotion(); const id = useId(); const [internal, setInternal] = useState(defaultChecked); const [pressed, setPressed] = useState(false); const on = checked ?? internal; const toggle = () => { if (checked === undefined) setInternal(!on); onCheckedChange?.(!on); }; return (
{label ? ( ) : null}
); } ``` ## Switch: Labelled A switch that writes its state inside the track, so on and off never depend on color alone. - Install: `@stillui/switch-labelled` - Import: `import { SwitchLabelled } from "@/components/ui/switch-labelled"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/switch States it handles: - **Off**: “Off” on the right, thumb on the left, neutral track. - **On**: The thumb slides right; “On” fades in on the left over the primary track. - **Custom words**: Pass onText and offText, e.g. Yes and No. Keep them to three letters or so. - **Keyboard**: role switch with aria-checked. The words are hidden from screen readers, which announce the state already. - **Reduced motion**: Thumb and words swap without sliding. Notes: - Helpful for people who can’t tell the track colors apart, and in forms printed or screenshotted for review. ```tsx "use client"; // stillui.dev/components/switch#labelled import { AnimatePresence, motion, useReducedMotion } from "motion/react"; import { useId, useState, type ReactNode } from "react"; import { cn } from "@/lib/utils"; const THUMB = { type: "spring", stiffness: 560, damping: 38, mass: 0.7 } as const; type SwitchLabelledProps = { checked?: boolean; defaultChecked?: boolean; onCheckedChange?: (checked: boolean) => void; label?: ReactNode; onText?: string; offText?: string; className?: string; }; /** A switch that says its state inside the track, for places where color alone isn’t enough. */ export function SwitchLabelled({ checked, defaultChecked = false, onCheckedChange, label, onText = "On", offText = "Off", className, }: SwitchLabelledProps) { const reduce = useReducedMotion(); const id = useId(); const [internal, setInternal] = useState(defaultChecked); const on = checked ?? internal; const toggle = () => { if (checked === undefined) setInternal(!on); onCheckedChange?.(!on); }; return (
{label ? ( ) : null}
); } ``` ## Switch: Icon thumb A switch with a check or a cross inside the thumb. The icon turns as the thumb travels. - Install: `@stillui/switch-icon` - Import: `import { SwitchIcon } from "@/components/ui/switch-icon"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/switch States it handles: - **Off**: A cross in the thumb on the left. - **On**: The thumb rolls right and the cross becomes a check in the primary color. - **Description**: An optional line under the label, linked with aria-describedby. - **Keyboard**: role switch with aria-checked; Space and Enter toggle it. - **Reduced motion**: The thumb and icon change without rolling. Notes: - The icon gives a second cue besides color, which helps people with color vision deficiency. ```tsx "use client"; // stillui.dev/components/switch#icon import { AnimatePresence, motion, useReducedMotion } from "motion/react"; import { useId, useState, type ReactNode } from "react"; import { cn } from "@/lib/utils"; const THUMB = { type: "spring", stiffness: 600, damping: 38, mass: 0.7 } as const; type SwitchIconProps = { checked?: boolean; defaultChecked?: boolean; onCheckedChange?: (checked: boolean) => void; label?: ReactNode; description?: ReactNode; className?: string; }; /** A switch with a check or a cross inside the thumb. The icon turns as the thumb travels. */ export function SwitchIcon({ checked, defaultChecked = false, onCheckedChange, label, description, className }: SwitchIconProps) { const reduce = useReducedMotion(); const id = useId(); const [internal, setInternal] = useState(defaultChecked); const on = checked ?? internal; const descId = description ? `${id}-desc` : undefined; const toggle = () => { if (checked === undefined) setInternal(!on); onCheckedChange?.(!on); }; return (
{label || description ? (
{label ? ( ) : null} {description ? (

{description}

) : null}
) : null}
); } ``` ## Text Field: Standard Label, input and one message row for hints and errors. Errors shake once; confirmed values get a check. - Install: `@stillui/text-field` - Import: `import { TextField } from "@/components/ui/text-field"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/text-field States it handles: - **Empty**: Placeholder uses the faint text role and never replaces the label. - **Focus**: A soft ring appears around the field; no layout change. - **Invalid**: Red edge, one short shake, error replaces the hint and is announced. - **Valid**: A check draws in at the right edge. - **Disabled**: Label and field dim together. Notes: - The message row keeps its height, so errors never push the rest of the form down. - The label sits closer to its field than to the field above, so each pair reads as one unit. ```tsx "use client"; // stillui.dev/components/text-field import { AnimatePresence, motion, useAnimationControls, useReducedMotion } from "motion/react"; import { forwardRef, useEffect, useId, type ComponentProps, type ReactNode } from "react"; import { cn } from "@/lib/utils"; const REVEAL = { duration: 0.18, ease: [0.16, 1, 0.3, 1] } as const; type TextFieldProps = Omit, "size"> & { label: ReactNode; /** Help text under the field. Replaced by the error while one is shown. */ hint?: ReactNode; /** Error message. Setting it marks the field invalid and gives it a short shake. */ error?: ReactNode; /** Marks the value as confirmed (e.g. a username that is available). */ valid?: boolean; }; export const TextField = forwardRef(function TextField( { label, hint, error, valid, id, className, disabled, ...props }, ref, ) { const reduce = useReducedMotion(); const controls = useAnimationControls(); const autoId = useId(); const inputId = id ?? autoId; const messageId = `${inputId}-message`; const invalid = Boolean(error); const message = error ?? hint; // Shake once when an error appears. Reduced motion keeps the color change only. useEffect(() => { if (invalid && !reduce) controls.start({ x: [0, -5, 5, -3, 3, 0], transition: { duration: 0.32 } }); }, [invalid, error, reduce, controls]); return (
{valid && !invalid ? ( ) : null} {/* Fixed-height row so the layout below never jumps when a message appears. */}
{message ? ( {message} ) : null}
); }); ``` ## Text Field: Floating label The label sits inside the field, then floats up when you focus or type. Compact forms without losing the label. - Install: `@stillui/text-field-floating` - Import: `import { TextFieldFloating } from "@/components/ui/text-field-floating"` - Dependencies: none - Page: https://stillui.netlify.app/components/text-field States it handles: - **Empty**: The label fills the field like a placeholder, at full text size. - **Focused**: The label shrinks to the top-left and darkens; a soft ring surrounds the field. - **Filled**: The label stays small at the top so the value and its name are both visible. - **Hint**: Optional help text under the field, linked with aria-describedby. - **Reduced motion**: The label moves without a transition. Notes: - No JavaScript: it relies on the :placeholder-shown selector, so autofilled values float the label too. - Unlike a placeholder, the label never disappears, which matters for people who return to a form later. ```tsx "use client"; // stillui.dev/components/text-field#floating import { forwardRef, useId, type ComponentProps } from "react"; import { cn } from "@/lib/utils"; type TextFieldFloatingProps = Omit, "placeholder" | "size"> & { label: string; hint?: string; }; /** * The label sits inside the field like a placeholder, then floats up when you type. * Pure CSS: an empty placeholder lets the label know when the field is empty. */ export const TextFieldFloating = forwardRef(function TextFieldFloating( { label, hint, id, className, ...props }, ref, ) { const autoId = useId(); const inputId = id ?? autoId; return (
{hint ? (

{hint}

) : null}
); }); ``` ## Text Field: Password A password field with a show button and, for new passwords, a strength meter that says exactly what’s missing. - Install: `@stillui/text-field-password` - Import: `import { TextFieldPassword } from "@/components/ui/text-field-password"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/text-field States it handles: - **Hidden / shown**: The eye button toggles the text; a slash draws across it while the password is visible. - **Strength**: A bar fills in quarters and changes from red to amber to green, with a word beside it. - **Checklist**: Each rule turns from a dot into a green check as it is met. - **Sign-in mode**: Pass meter={false} for existing passwords; it also switches autocomplete to current-password. - **Screen readers**: The strength word is announced politely; each rule says done or missing. - **Reduced motion**: The bar and slash change without animating. Notes: - This meter only checks the shape of a password. Check it against breached-password lists on the server too. ```tsx "use client"; // stillui.dev/components/text-field#password import { motion, useReducedMotion } from "motion/react"; import { useId, useState } from "react"; import { cn } from "@/lib/utils"; const FILL = { type: "spring", stiffness: 260, damping: 30 } as const; const rules = [ { test: (v: string) => v.length >= 12, text: "12 or more characters" }, { test: (v: string) => /[a-z]/.test(v) && /[A-Z]/.test(v), text: "Upper and lower case" }, { test: (v: string) => /\d/.test(v), text: "A number" }, { test: (v: string) => /[^A-Za-z0-9]/.test(v), text: "A symbol" }, ]; const levels = [ { label: "Too short", color: "bg-destructive" }, { label: "Weak", color: "bg-destructive" }, { label: "Fair", color: "bg-[oklch(72%_0.15_70)]" }, { label: "Good", color: "bg-success" }, { label: "Strong", color: "bg-success" }, ]; type TextFieldPasswordProps = { label?: string; value?: string; onValueChange?: (value: string) => void; /** Show the strength meter and checklist, for new passwords. */ meter?: boolean; className?: string; }; /** A password field with a show button and, for new passwords, a strength meter that says what’s missing. */ export function TextFieldPassword({ label = "Password", value, onValueChange, meter = true, className }: TextFieldPasswordProps) { const reduce = useReducedMotion(); const id = useId(); const [internal, setInternal] = useState(""); const [visible, setVisible] = useState(false); const current = value ?? internal; const passed = rules.filter((rule) => rule.test(current)).length; const level = current.length === 0 ? null : levels[current.length < 8 ? 0 : passed]; const change = (next: string) => { if (value === undefined) setInternal(next); onValueChange?.(next); }; return (
change(e.target.value)} autoComplete={meter ? "new-password" : "current-password"} aria-describedby={meter ? `${id}-strength` : undefined} className={cn( "h-10 w-full rounded-md bg-card pl-3 pr-10 text-sm shadow-[inset_0_0_0_1px_var(--input)] transition-shadow duration-150", "focus-visible:outline-none focus-visible:shadow-[inset_0_0_0_1px_var(--ring),0_0_0_3px_oklch(from_var(--ring)_l_c_h/0.2)]", )} />
{meter ? (
{level?.label ?? ""}
    {rules.map((rule) => { const ok = rule.test(current); return (
  • {ok ? : } {rule.text} {ok ? "(done)" : "(missing)"}
  • ); })}
) : null}
); } ``` ## Text Field: Code (paid) A one-time code in separate boxes, backed by a single real input so typing, pasting and autofill all just work. - Install: `@stillui-pro/text-field-code` with an account token (see "Paid components" above) - Page: https://stillui.netlify.app/components/text-field ## Text Field: Search A rounded search field with a clear button, Escape to clear, and a shortcut key to jump to it from anywhere. - Install: `@stillui/text-field-search` - Import: `import { TextFieldSearch } from "@/components/ui/text-field-search"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/text-field States it handles: - **Resting**: A soft muted field with a search icon and the shortcut key shown on the right. - **Focused**: The field lifts to the card color with a ring; the shortcut hint steps aside. - **Has text**: A clear button pops in. Escape also clears, without leaving the field. - **Shortcut**: Pressing / anywhere focuses it, unless someone is typing in another field. - **Screen readers**: Wrapped in a search landmark, with a label even though there is no visible one. ```tsx "use client"; // stillui.dev/components/text-field#search import { AnimatePresence, motion, useReducedMotion } from "motion/react"; import { useEffect, useRef, useState } from "react"; import { cn } from "@/lib/utils"; type TextFieldSearchProps = { label?: string; placeholder?: string; value?: string; onValueChange?: (value: string) => void; /** A key that focuses the field from anywhere on the page. */ shortcut?: string; className?: string; }; /** A search field with a clear button, Escape to clear, and a shortcut key to jump to it. */ export function TextFieldSearch({ label = "Search", placeholder = "Search", value, onValueChange, shortcut = "/", className }: TextFieldSearchProps) { const reduce = useReducedMotion(); const ref = useRef(null); const [internal, setInternal] = useState(""); const [focused, setFocused] = useState(false); const current = value ?? internal; const change = (next: string) => { if (value === undefined) setInternal(next); onValueChange?.(next); }; // The shortcut is ignored while someone is typing in another field. useEffect(() => { const onKey = (event: KeyboardEvent) => { const target = event.target as HTMLElement; if (event.key !== shortcut || target.isContentEditable || ["INPUT", "TEXTAREA", "SELECT"].includes(target.tagName)) return; event.preventDefault(); ref.current?.focus(); }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); }, [shortcut]); const pop = { initial: { opacity: 0, scale: reduce ? 1 : 0.8 }, animate: { opacity: 1, scale: 1 }, exit: { opacity: 0, scale: reduce ? 1 : 0.8 } }; return (
change(e.target.value)} onFocus={() => setFocused(true)} onBlur={() => setFocused(false)} onKeyDown={(e) => { if (e.key === "Escape" && current) { e.preventDefault(); change(""); } }} className={cn( "h-10 w-full rounded-full bg-muted pl-9 pr-10 text-sm transition-[background-color,box-shadow] duration-150 placeholder:text-muted-foreground [&::-webkit-search-cancel-button]:appearance-none", "focus-visible:bg-card focus-visible:outline-none focus-visible:shadow-[inset_0_0_0_1px_var(--ring),0_0_0_3px_oklch(from_var(--ring)_l_c_h/0.2)]", )} />
{current ? ( { change(""); ref.current?.focus(); }} aria-label="Clear search" className="grid size-7 place-items-center rounded-full text-muted-foreground transition-[color,background-color,box-shadow,scale] active:scale-[0.9] hover:bg-secondary hover:text-foreground" transition={{ duration: 0.12 }} {...pop} > ) : !focused ? ( {shortcut} ) : null}
); } ``` ## Theme Toggle: Button Switches light and dark with one of four page transitions. The icon’s sun becomes a moon as a shadow slides over it. - Install: `@stillui/theme-toggle` - Import: `import { ThemeToggle } from "@/components/ui/theme-toggle"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/theme-toggle States it handles: - **Light / dark**: Reads the dark class on , so every toggle on the page stays in sync. - **Fade**: The browser’s crossfade. The calmest choice and the default. - **Circle**: The new theme spreads from where you clicked; from the button’s center when using a keyboard. - **Rise**: The new theme comes up from the bottom edge. - **Tide**: Light rises from the bottom like a sunrise; dark falls from the top like nightfall. - **Older browsers**: Without the View Transition API the theme switches instantly. - **Reduced motion**: Switches instantly; the icon changes without animating. Notes: - Saves the choice to localStorage under “theme”. Add a small inline script in that reads it before paint, or the page flashes the wrong theme on load. ```tsx "use client"; // stillui.dev/components/theme-toggle import { motion, useReducedMotion } from "motion/react"; import { useId, useSyncExternalStore, type MouseEvent } from "react"; import { cn } from "@/lib/utils"; export type ThemeTransition = "fade" | "circle" | "rise" | "tide"; const ICON = { type: "spring", stiffness: 300, damping: 26 } as const; const EASE = "cubic-bezier(0.65, 0, 0.35, 1)"; // Clip-based transitions replace the browser's default crossfade while they run. const css = ` html[data-theme-transition="clip"]::view-transition-old(root), html[data-theme-transition="clip"]::view-transition-new(root) { animation: none; mix-blend-mode: normal; }`; function subscribe(onChange: () => void) { const observer = new MutationObserver(onChange); observer.observe(document.documentElement, { attributes: true, attributeFilter: ["class"] }); return () => observer.disconnect(); } function isDark() { return document.documentElement.classList.contains("dark"); } function applyTheme(dark: boolean) { document.documentElement.classList.toggle("dark", dark); try { localStorage.setItem("theme", dark ? "dark" : "light"); } catch {} } const FROM_BOTTOM = ["inset(100% 0 0 0)", "inset(0 0 0 0)"]; const FROM_TOP = ["inset(0 0 100% 0)", "inset(0 0 0 0)"]; /** Light rises from the bottom like a sunrise; dark falls from the top like nightfall. */ function tide(dark: boolean) { return dark ? FROM_TOP : FROM_BOTTOM; } /** A circle that grows from the pointer (or the button's center for keyboard use) to cover the screen. */ function circleFrom(event: MouseEvent) { const rect = event.currentTarget.getBoundingClientRect(); const x = event.clientX || rect.left + rect.width / 2; const y = event.clientY || rect.top + rect.height / 2; const radius = Math.hypot(Math.max(x, innerWidth - x), Math.max(y, innerHeight - y)); return [`circle(0px at ${x}px ${y}px)`, `circle(${radius}px at ${x}px ${y}px)`]; } type ThemeToggleProps = { /** How the page changes: a crossfade, a circle from the click, a rise from the bottom edge, or a tide (light rises, dark falls). */ transition?: ThemeTransition; className?: string; }; export function ThemeToggle({ transition = "fade", className }: ThemeToggleProps) { const dark = useSyncExternalStore(subscribe, isDark, () => false); const reduce = useReducedMotion(); const maskId = `moon-${useId().replace(/[^\w-]/g, "")}`; const toggle = (event: MouseEvent) => { const next = !isDark(); if (!document.startViewTransition || reduce) { applyTheme(next); return; } const root = document.documentElement; const clip = transition === "circle" ? circleFrom(event) : transition === "rise" ? FROM_BOTTOM : transition === "tide" ? tide(next) : null; if (clip) root.dataset.themeTransition = "clip"; const change = document.startViewTransition(() => applyTheme(next)); change.ready.then(() => { if (!clip) return; root.animate( { clipPath: clip }, { duration: transition === "circle" ? 520 : 640, easing: EASE, pseudoElement: "::view-transition-new(root)" }, ); }); change.finished.finally(() => delete root.dataset.themeTransition); }; return ( <> ); } ``` ## Theme Toggle: Picker Light, dark, or follow the operating system. A three-way choice for settings menus, remembered between visits. - Install: `@stillui/theme-picker` - Import: `import { ThemePicker } from "@/components/ui/theme-picker"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/theme-toggle States it handles: - **Light / Dark**: Sets the theme and saves it under “theme” in localStorage. - **System**: Removes the saved value and follows the OS, including when it changes at sunset. - **Switching**: A raised pill glides to the chosen icon. - **In sync**: Every picker and toggle on the page updates together, and other tabs follow too. - **Keyboard**: A radio group: one tab stop, arrow keys to choose. Each icon has a name. - **Reduced motion**: The pill jumps instead of gliding. Notes: - Pair it with a pre-paint script that reads localStorage “theme” and falls back to prefers-color-scheme, so pages never flash. ```tsx "use client"; // stillui.dev/components/theme-toggle#picker import { motion, useReducedMotion } from "motion/react"; import { useEffect, useId, useRef, useSyncExternalStore, type KeyboardEvent } from "react"; import { cn } from "@/lib/utils"; const GLIDE = { type: "spring", stiffness: 420, damping: 40, mass: 0.8 } as const; const CHANGE = "still-theme-change"; type Choice = "light" | "dark" | "system"; const choices: { value: Choice; label: string; d: string }[] = [ { value: "light", label: "Light", d: "M8 5.5a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5zM8 1.5v1.25M8 13.25v1.25M1.5 8h1.25M13.25 8h1.25M3.4 3.4l.9.9M11.7 11.7l.9.9M3.4 12.6l.9-.9M11.7 4.3l.9-.9" }, { value: "dark", label: "Dark", d: "M13.5 9.5A5.5 5.5 0 0 1 6.5 2.5a5.5 5.5 0 1 0 7 7z" }, { value: "system", label: "System", d: "M2.5 3.5h11v7h-11zM6 13.5h4M8 10.5v3" }, ]; // "system" is stored as no value, so a pre-paint script can fall back to the OS setting. function read(): Choice { try { const saved = localStorage.getItem("theme"); return saved === "light" || saved === "dark" ? saved : "system"; } catch { return "system"; } } // Re-reads when this picker saves, another tab saves, or any other toggle flips the dark class. function subscribe(onChange: () => void) { const observer = new MutationObserver(onChange); observer.observe(document.documentElement, { attributes: true, attributeFilter: ["class"] }); window.addEventListener(CHANGE, onChange); window.addEventListener("storage", onChange); return () => { observer.disconnect(); window.removeEventListener(CHANGE, onChange); window.removeEventListener("storage", onChange); }; } function systemDark() { return matchMedia("(prefers-color-scheme: dark)").matches; } function save(choice: Choice) { try { if (choice === "system") localStorage.removeItem("theme"); else localStorage.setItem("theme", choice); } catch {} document.documentElement.classList.toggle("dark", choice === "dark" || (choice === "system" && systemDark())); window.dispatchEvent(new Event(CHANGE)); } /** Light, dark, or follow the operating system. The choice is remembered. */ export function ThemePicker({ className }: { className?: string }) { const reduce = useReducedMotion(); const layoutId = useId(); const choice = useSyncExternalStore(subscribe, read, () => "system" as Choice); const refs = useRef<(HTMLButtonElement | null)[]>([]); // While following the system, react when the OS switches (e.g. at sunset). useEffect(() => { if (choice !== "system") return; const query = matchMedia("(prefers-color-scheme: dark)"); const sync = () => document.documentElement.classList.toggle("dark", query.matches); query.addEventListener("change", sync); return () => query.removeEventListener("change", sync); }, [choice]); const onKeyDown = (event: KeyboardEvent) => { const step = event.key === "ArrowRight" ? 1 : event.key === "ArrowLeft" ? -1 : 0; if (!step) return; event.preventDefault(); const index = choices.findIndex((c) => c.value === choice); const next = (index + step + choices.length) % choices.length; save(choices[next].value); refs.current[next]?.focus(); }; return (
{choices.map((c, i) => { const selected = c.value === choice; return ( ); })}
); } ``` ## Toast: Stack Brief confirmations that stack neatly, fan out on hover and leave on their own. - Install: `@stillui/toast` - Import: `import { useToast, ToastProvider } from "@/components/ui/toast"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/toast States it handles: - **Enter**: Rises from below on a soft spring; the previous toast tucks behind it. - **Stacked**: Up to three stay visible, older ones smaller and further back. - **Hover**: The stack fans out into a list and every timer pauses so nothing disappears while you read. - **Dismiss**: Leaves faster than it arrived, after 4 seconds or on the close button. - **Tones**: Neutral, success and error. The icon carries the meaning too, not just its color. - **Screen readers**: Announced politely through a live region, without stealing focus. Notes: - Wrap your app once in ToastProvider, then call useToast() anywhere below it. - Use toasts only for things people need to know. Confirming every small action trains people to ignore them. - Never put the only way to undo something in a toast; it may be gone before someone reaches it. ```tsx "use client"; // stillui.dev/components/toast import { animate, AnimatePresence, motion, useMotionValue, useReducedMotion, useTransform, type PanInfo } from "motion/react"; import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from "react"; import { cn } from "@/lib/utils"; const DURATION = 4000; const VISIBLE = 3; const GAP = 8; const ENTER = { type: "spring", stiffness: 380, damping: 34, mass: 0.9, } as const; // A swipe this far, or a flick this fast, sends the toast away; anything less springs it back. const SWIPE_DISTANCE = 80; const SWIPE_VELOCITY = 500; type Tone = "neutral" | "success" | "error"; type Toast = { id: number; title: string; description?: string; tone: Tone; }; type ToastInput = Omit & { tone?: Tone }; const ToastContext = createContext<((toast: ToastInput) => void) | null>(null); /** Returns a function that shows a toast. Must be used inside . */ export function useToast() { const add = useContext(ToastContext); if (!add) throw new Error("useToast must be used inside "); return add; } export function ToastProvider({ children }: { children: ReactNode }) { const [toasts, setToasts] = useState([]); const nextId = useRef(0); const add = useCallback((toast: ToastInput) => { const id = nextId.current++; const next: Toast = { tone: "neutral", ...toast, id }; setToasts((list) => [next, ...list].slice(0, VISIBLE + 1)); }, []); const remove = useCallback((id: number) => setToasts((list) => list.filter((t) => t.id !== id)), []); return ( {children} ); } function Toaster({ toasts, onDismiss }: { toasts: Toast[]; onDismiss: (id: number) => void }) { const [expanded, setExpanded] = useState(false); const [heights, setHeights] = useState>({}); const measure = useCallback((id: number, height: number) => { setHeights((h) => (h[id] === height ? h : { ...h, [id]: height })); }, []); // Offset of each toast when the stack is fanned out on hover. const offsets = useMemo(() => { const result: number[] = []; let total = 0; for (const t of toasts) { result.push(total); total += (heights[t.id] ?? 64) + GAP; } return result; }, [toasts, heights]); return (
setExpanded(true)} onPointerLeave={() => setExpanded(false)} >
    {toasts.map((toast, index) => ( ))}
); } type ToastItemProps = { toast: Toast; index: number; offset: number; /** Collapsed cards take the front card's height so a taller one never sticks out behind it. */ height?: number; expanded: boolean; paused: boolean; onMeasure: (id: number, height: number) => void; onDismiss: (id: number) => void; }; function ToastItem({ toast, index, offset, height, expanded, paused, onMeasure, onDismiss }: ToastItemProps) { const reduce = useReducedMotion(); const ref = useRef(null); const hidden = index >= VISIBLE; const swipeable = !hidden && (expanded || index === 0); // Swiping right drags the card out; its content fades as it goes. const x = useMotionValue(0); const contentOpacity = useTransform(x, [0, 160], [1, 0.2]); const onDragEnd = (_: unknown, info: PanInfo) => { if (info.offset.x > SWIPE_DISTANCE || info.velocity.x > SWIPE_VELOCITY) { const width = ref.current?.offsetWidth ?? 360; animate(x, width + 48, { type: "spring", stiffness: 300, damping: 34, velocity: info.velocity.x, }); window.setTimeout(() => onDismiss(toast.id), 140); } }; useEffect(() => { if (ref.current) onMeasure(toast.id, ref.current.offsetHeight); }, [toast.id, toast.title, toast.description, onMeasure]); // Auto-dismiss, paused while the pointer is over the stack. useEffect(() => { if (paused) return; const timer = window.setTimeout(() => onDismiss(toast.id), DURATION); return () => window.clearTimeout(timer); }, [paused, toast.id, onDismiss]); // Collapsed: older toasts tuck behind the newest. Expanded: they fan out into a list. const y = expanded ? -offset : -index * 10; const scale = expanded || reduce ? 1 : 1 - index * 0.05; return ( ); } function ToneIcon({ tone }: { tone: Tone }) { if (tone === "neutral") return null; return ( {tone === "success" ? : } ); } ``` ## Toast: Pill One short message in a capsule at the top of the screen. A new message reshapes the same pill instead of stacking. - Install: `@stillui/toast-pill` - Import: `import { usePillToast, PillToastProvider } from "@/components/ui/toast-pill"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/toast States it handles: - **Enter**: Drops in from above and settles on a spring. - **Replace**: The old text slides out, the new text slides in, and the pill resizes around it. - **Leave**: Fades up and away after 2.4 seconds. Each new message restarts the timer. - **Tones**: Neutral, success and error, told apart by the icon’s shape since the pill is one color. - **Reduced motion**: Appears and changes without movement. - **Screen readers**: The text is announced through a polite live region. Notes: - Best for a word or two: Copied, Saved, Sent. Anything longer, or anything with an action, belongs in the stack or action variant. ```tsx "use client"; // stillui.dev/components/toast#pill import { AnimatePresence, motion, useReducedMotion } from "motion/react"; import { createContext, useCallback, useContext, useEffect, useRef, useState, type ReactNode } from "react"; const DURATION = 2400; const MORPH = { type: "spring", stiffness: 420, damping: 36 } as const; type Tone = "neutral" | "success" | "error"; type PillToast = { id: number; title: string; tone: Tone; }; type PillToastInput = { title: string; tone?: Tone }; const PillToastContext = createContext<((toast: PillToastInput) => void) | null>(null); /** Returns a function that shows a pill. Must be used inside . */ export function usePillToast() { const show = useContext(PillToastContext); if (!show) throw new Error("usePillToast must be used inside "); return show; } export function PillToastProvider({ children }: { children: ReactNode }) { const [toast, setToast] = useState(null); const nextId = useRef(0); // A new message replaces the current one; the pill reshapes around it. const show = useCallback((input: PillToastInput) => { setToast({ tone: "neutral", ...input, id: nextId.current++ }); }, []); useEffect(() => { if (!toast) return; const timer = window.setTimeout(() => setToast(null), DURATION); return () => window.clearTimeout(timer); }, [toast]); return ( {children} ); } function Pill({ toast }: { toast: PillToast | null }) { const reduce = useReducedMotion(); const spring = reduce ? { duration: 0 } : MORPH; return (
{toast?.title}
{toast ? ( {toast.title} ) : null}
); } // Icons use the pill's own color, so the shape carries the meaning on the inverted background. function ToneIcon({ tone }: { tone: Tone }) { if (tone === "neutral") return null; return ( {tone === "success" ? ( ) : ( <> )} ); } ``` ## Toast: Action One message at the bottom of the screen with a single action, like Undo. It waits while you hover or focus it. - Install: `@stillui/toast-action` - Import: `import { useActionToast, ActionToastProvider } from "@/components/ui/toast-action"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/toast States it handles: - **Enter**: Rises from the bottom edge. A new toast replaces the current one. - **Action**: Runs the action, then dismisses. There is only ever one action, so the choice is obvious. - **Waiting**: The 6 second timer pauses while the pointer or keyboard focus is on the toast. - **Dismiss**: The close button or Escape, while focus is inside. - **Reduced motion**: Appears and leaves without movement. - **Screen readers**: Announces the message and that an action is available, without moving focus. Notes: - Undo in a toast is a shortcut, not the only way back. Keep deleted items recoverable somewhere people can find later, such as a trash folder. ```tsx "use client"; // stillui.dev/components/toast#action import { AnimatePresence, motion, useReducedMotion, type PanInfo } from "motion/react"; import { createContext, useCallback, useContext, useEffect, useRef, useState, type ReactNode } from "react"; // Longer than a plain toast: people need time to read and decide. const DURATION = 6000; const ENTER = { type: "spring", stiffness: 380, damping: 34 } as const; type ActionToast = { id: number; title: string; action?: { label: string; onAction: () => void }; }; type ActionToastInput = Omit; const ActionToastContext = createContext<((toast: ActionToastInput) => void) | null>(null); /** Returns a function that shows a toast with one action. Must be used inside . */ export function useActionToast() { const show = useContext(ActionToastContext); if (!show) throw new Error("useActionToast must be used inside "); return show; } export function ActionToastProvider({ children }: { children: ReactNode }) { const [toast, setToast] = useState(null); const [paused, setPaused] = useState(false); const nextId = useRef(0); const show = useCallback((input: ActionToastInput) => setToast({ ...input, id: nextId.current++ }), []); const dismiss = useCallback(() => setToast(null), []); // Waits while the pointer or keyboard focus is on the toast. useEffect(() => { if (!toast || paused) return; const timer = window.setTimeout(dismiss, DURATION); return () => window.clearTimeout(timer); }, [toast, paused, dismiss]); return ( {children}
setPaused(true)} onPointerLeave={() => setPaused(false)} onFocus={() => setPaused(true)} onBlur={() => setPaused(false)} >
{toast ? `${toast.title}${toast.action ? `. ${toast.action.label} is available.` : ""}` : ""}
{toast ? : null}
); } function ActionCard({ toast, onDismiss }: { toast: ActionToast; onDismiss: () => void }) { const reduce = useReducedMotion(); return ( (info.offset.y > 48 || info.velocity.y > 400) && onDismiss()} onKeyDown={(event) => event.key === "Escape" && onDismiss()} >

{toast.title}

{toast.action ? ( ) : null}
); } ``` ## Toast: Promise (paid) Follows a request from start to finish in one toast. The spinner becomes a check or an error, and the text changes in place. - Install: `@stillui-pro/toast-promise` with an account token (see "Paid components" above) - Page: https://stillui.netlify.app/components/toast ## Toast: Anchored A short message that appears right next to the button that caused it, where the eye already is. No provider needed. - Install: `@stillui/toast-anchored` - Import: `import { ToastAnchor } from "@/components/ui/toast-anchored"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/toast States it handles: - **Enter**: Pops out of the trigger on a quick spring, above it by default or below with side="bottom". - **Repeat**: Pressing again restarts the message and its timer instead of piling up copies. - **Leave**: Gone after 1.8 seconds; the message is short enough to read at a glance. - **Tones**: Neutral, success and error, told apart by the icon’s shape. - **Reduced motion**: Appears and leaves without movement. - **Screen readers**: Each anchor has its own polite live region, so the message is announced. Notes: - Use it when the result belongs to one control, such as Copy link. For results that affect the whole page, use the stack or action variant. ```tsx "use client"; // stillui.dev/components/toast#anchored import { AnimatePresence, motion, useReducedMotion } from "motion/react"; import { useCallback, useEffect, useState, type ReactNode } from "react"; import { cn } from "@/lib/utils"; const DURATION = 1800; const POP = { type: "spring", stiffness: 520, damping: 32 } as const; // Each message gets a fresh key, so pressing twice replays the pop. let nextId = 0; type Tone = "neutral" | "success" | "error"; type AnchoredToast = { id: number; title: string; tone: Tone; }; type AnchoredToastInput = { title: string; tone?: Tone }; type ToastAnchorProps = { /** Render the trigger. Call show() from it to put a message next to it. */ children: (show: (toast: AnchoredToastInput) => void) => ReactNode; /** Where the message appears relative to the trigger. */ side?: "top" | "bottom"; className?: string; }; /** Shows a short message right where the action happened, so the eye doesn't have to travel. */ export function ToastAnchor({ children, side = "top", className }: ToastAnchorProps) { const reduce = useReducedMotion(); const [toast, setToast] = useState(null); const show = useCallback((input: AnchoredToastInput) => { setToast({ tone: "neutral", ...input, id: nextId++ }); }, []); useEffect(() => { if (!toast) return; const timer = window.setTimeout(() => setToast(null), DURATION); return () => window.clearTimeout(timer); }, [toast]); const offset = side === "top" ? 6 : -6; return ( {children(show)} {toast?.title} {toast ? ( {toast.title} ) : null} ); } function ToneIcon({ tone }: { tone: Tone }) { if (tone === "neutral") return null; return ( {tone === "success" ? ( ) : ( <> )} ); } ``` ## Tooltip: Standard A short label for icon buttons. Waits before the first one opens, then opens instantly while you scan neighbors. - Install: `@stillui/tooltip` - Import: `import { Tooltip } from "@/components/ui/tooltip"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/tooltip States it handles: - **Resting**: Hidden. Nothing in the layout reserves space for it. - **Hover**: Opens after 500ms, so passing over a toolbar doesn't flash labels. - **Warm**: Within 400ms of one closing, the next opens with no delay. - **Keyboard focus**: Opens at once on focus. Escape closes it. Linked to the trigger with aria-describedby. - **Touch**: Not shown: touch screens have no hover. The trigger keeps its own accessible label. Notes: - Tooltips are for names and shortcuts, never for information someone needs to finish a task. Touch users won’t see them. - Keep the text to a few words. If it needs a sentence, it belongs on the page. ```tsx "use client"; // stillui.dev/components/tooltip import { AnimatePresence, motion, useReducedMotion } from "motion/react"; import { useEffect, useId, useRef, useState, type ReactNode } from "react"; import { cn } from "@/lib/utils"; const OPEN_DELAY = 500; // Once one tooltip has opened, neighbors open at once for a short while, // so scanning a toolbar doesn't mean waiting at every icon. const WARM_WINDOW = 400; let lastClosedAt = 0; type TooltipProps = { content: ReactNode; side?: "top" | "bottom"; children: ReactNode; className?: string; }; export function Tooltip({ content, side = "top", children, className }: TooltipProps) { const reduce = useReducedMotion(); const [open, setOpen] = useState(false); const timer = useRef(undefined); const id = useId(); useEffect(() => () => window.clearTimeout(timer.current), []); const show = () => { window.clearTimeout(timer.current); const warm = Date.now() - lastClosedAt < WARM_WINDOW; timer.current = window.setTimeout(() => setOpen(true), warm ? 0 : OPEN_DELAY); }; const hide = () => { window.clearTimeout(timer.current); setOpen((wasOpen) => { if (wasOpen) lastClosedAt = Date.now(); return false; }); }; const offset = side === "top" ? 4 : -4; return ( e.pointerType === "mouse" && show()} onPointerLeave={hide} onFocus={() => setOpen(true)} onBlur={hide} onKeyDown={(e) => e.key === "Escape" && hide()} aria-describedby={open ? id : undefined} > {children} {open ? ( {content} ) : null} ); } ``` ## Tooltip: Follow cursor A tooltip that follows the pointer along a wide target, like a chart or timeline, and reads out what’s under it. - Install: `@stillui/tooltip-follow` - Import: `import { TooltipFollow } from "@/components/ui/tooltip-follow"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/tooltip States it handles: - **Enter**: Appears right at the pointer without sliding in from elsewhere. - **Moving**: Follows the pointer on a tight spring, so it keeps up without jitter. - **Content**: Your function gets the position from 0 to 1 and returns what to show there. - **Leave**: Fades out quickly when the pointer leaves the target. - **Reduced motion**: Sticks to the pointer exactly, with no spring. Notes: - Mouse only, and hidden from screen readers. Give the chart itself a text summary, as the demo does with its label. ```tsx "use client"; // stillui.dev/components/tooltip#follow import { AnimatePresence, motion, useMotionValue, useReducedMotion, useSpring } from "motion/react"; import { useState, type PointerEvent, type ReactNode } from "react"; import { cn } from "@/lib/utils"; const FOLLOW = { stiffness: 700, damping: 50, mass: 0.5 } as const; type TooltipFollowProps = { /** Gets the pointer’s position across the target, from 0 (left) to 1 (right). */ content: (ratio: number) => ReactNode; children: ReactNode; className?: string; }; /** A tooltip that follows the pointer along a wide target, like a chart or a timeline, and reads out what’s under it. */ export function TooltipFollow({ content, children, className }: TooltipFollowProps) { const reduce = useReducedMotion(); const [ratio, setRatio] = useState(null); const raw = useMotionValue(0); const x = useSpring(raw, reduce ? { stiffness: 10000, damping: 1000 } : FOLLOW); const move = (event: PointerEvent) => { const rect = event.currentTarget.getBoundingClientRect(); const next = Math.min(1, Math.max(0, (event.clientX - rect.left) / rect.width)); if (ratio === null) x.jump(event.clientX - rect.left); raw.set(event.clientX - rect.left); setRatio(next); }; return (
setRatio(null)}> {children} {ratio !== null ? (
{content(ratio)}
) : null}
); } ``` ## Tooltip: Shortcut A tooltip that teaches the keyboard shortcut along with the name, so people learn the faster way as they go. - Install: `@stillui/tooltip-shortcut` - Import: `import { TooltipShortcut } from "@/components/ui/tooltip-shortcut"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/tooltip States it handles: - **Waiting**: Opens after half a second, so passing over a toolbar doesn’t flash tooltips. - **Warm**: Right after one closes, neighbours open instantly while you scan. - **Keys**: Each key sits in its own soft cap beside the label. - **Keyboard focus**: Opens at once on focus; Escape closes it. - **Reduced motion**: Fades without moving. Notes: - Also set aria-keyshortcuts on the button, so screen readers announce the shortcut too. ```tsx "use client"; // stillui.dev/components/tooltip#shortcut import { AnimatePresence, motion, useReducedMotion } from "motion/react"; import { useEffect, useId, useRef, useState, type ReactNode } from "react"; import { cn } from "@/lib/utils"; const OPEN_DELAY = 500; const WARM_WINDOW = 400; let lastClosedAt = 0; type TooltipShortcutProps = { label: string; /** Keys to press, e.g. ["⌘", "B"]. */ keys: string[]; side?: "top" | "bottom"; children: ReactNode; }; /** A tooltip that teaches the keyboard shortcut along with the name. */ export function TooltipShortcut({ label, keys, side = "top", children }: TooltipShortcutProps) { const reduce = useReducedMotion(); const [open, setOpen] = useState(false); const timer = useRef(undefined); const id = useId(); useEffect(() => () => window.clearTimeout(timer.current), []); const show = () => { window.clearTimeout(timer.current); const warm = Date.now() - lastClosedAt < WARM_WINDOW; timer.current = window.setTimeout(() => setOpen(true), warm ? 0 : OPEN_DELAY); }; const hide = () => { window.clearTimeout(timer.current); setOpen((wasOpen) => { if (wasOpen) lastClosedAt = Date.now(); return false; }); }; return ( e.pointerType === "mouse" && show()} onPointerLeave={hide} onFocus={() => setOpen(true)} onBlur={hide} onKeyDown={(e) => e.key === "Escape" && hide()} aria-describedby={open ? id : undefined} > {children} {open ? ( {label} {keys.map((key) => ( {key} ))} ) : null} ); } ``` ## Tooltip: Hover card A larger preview, like a profile or link card, that opens on hover and stays open while you move into it. - Install: `@stillui/tooltip-card` - Import: `import { TooltipCard } from "@/components/ui/tooltip-card"` - Dependencies: `motion` - Page: https://stillui.netlify.app/components/tooltip States it handles: - **Waiting**: Opens after 600 ms, a little slower than a tooltip, since it covers more of the page. - **Open**: A card that grows from the trigger’s edge. - **Moving in**: A 150 ms grace period lets the pointer cross the gap, so links inside the card can be clicked. - **Keyboard**: Opens on focus and stays open while focus is inside the card. Escape closes it. - **Reduced motion**: Fades without growing. Notes: - Never put the only path to something in a hover card. Touch screens can’t hover, so the trigger should link to the full page. ```tsx "use client"; // stillui.dev/components/tooltip#card import { AnimatePresence, motion, useReducedMotion } from "motion/react"; import { useEffect, useId, useRef, useState, type ReactNode } from "react"; import { cn } from "@/lib/utils"; const OPEN_DELAY = 600; // A short grace period lets the pointer travel from the trigger into the card. const CLOSE_DELAY = 150; type TooltipCardProps = { /** Rich content: a profile, a link preview, a definition. */ content: ReactNode; side?: "top" | "bottom"; children: ReactNode; className?: string; }; /** A larger preview that opens on hover and stays open while the pointer moves into it, so links inside work. */ export function TooltipCard({ content, side = "bottom", children, className }: TooltipCardProps) { const reduce = useReducedMotion(); const [open, setOpen] = useState(false); const timer = useRef(undefined); const id = useId(); useEffect(() => () => window.clearTimeout(timer.current), []); const openSoon = () => { window.clearTimeout(timer.current); timer.current = window.setTimeout(() => setOpen(true), open ? 0 : OPEN_DELAY); }; const closeSoon = () => { window.clearTimeout(timer.current); timer.current = window.setTimeout(() => setOpen(false), CLOSE_DELAY); }; return ( e.pointerType === "mouse" && openSoon()} onPointerLeave={closeSoon} onFocus={() => { window.clearTimeout(timer.current); setOpen(true); }} onBlur={(e) => { if (!e.currentTarget.contains(e.relatedTarget)) closeSoon(); }} onKeyDown={(e) => { if (e.key === "Escape") setOpen(false); }} > {children} {open ? ( {content} ) : null} ); } ```