Communication
Pull to refresh
Pull the list down from the top: a blob stretches, detaches into a spinner, then pops into a check when your refresh finishes. A Refresh button does the same.
Examples and variants
Slingshot
Pull down with the mouse or a finger.
- Update 3New
- Update 2
- Update 1
- Pull down from the top
function SlingshotRefresh() {
const [count, setCount] = useState(3)
return (
<PullToRefresh
className="h-64 w-full max-w-xs"
onRefresh={() => new Promise((resolve) => window.setTimeout(() => { setCount((c) => c + 1); resolve() }, tokenMs("--duration-fill") * 2))}
>
<ul className="flex flex-col gap-2 rounded-(--shape-lg) bg-canvas p-3 shadow-1">
{Array.from({ length: count }, (_, i) => (
<li key={count - i} className="isotope-rise flex items-center justify-between text-sm">
Update {count - i}
{i === 0 ? <Badge tone="info">New</Badge> : null}
</li>
))}
<li className="pt-2 text-caption text-ink-subtle">Pull down from the top</li>
</ul>
</PullToRefresh>
)
}Spec drawing
Measured from the live component at default density. Each code maps to the token that sets it; change the token and the drawing follows.
Install
With the CLI
The shadcn CLI only delivers files: it copies our code from the Isotopi registry into your project and installs the packages it uses. Add the foundation once, then the component.
npx shadcn@latest add https://isotopi.com/r/minimal.json
npx shadcn@latest add https://isotopi.com/r/pull-to-refresh.jsonBy hand
No CLI needed. Add the foundation once (see Getting started), then follow these steps. They include every component this one builds on.
Install the packages it uses.
Terminalnpm install @base-ui/react class-variance-authority cn lucide-reactCopy these 3 files to the same paths in your project. Imports use the
@/alias for your project root.components/ui/button.tsxbutton
components/ui/button.tsx"use client" import { useRef, useState } from "react" import { Button as ButtonPrimitive } from "@base-ui/react/button" import { CheckIcon, XIcon } from "lucide-react" import { tokenMs } from "@/lib/motion/token-ms" import { cva, type VariantProps } from "class-variance-authority" import { cn } from "cn" // Minimal: no strokes on controls (DESIGN.md rule 11), token sizes, token focus ring, // liquid press squash instead of shadcn's translate-y nudge. // Every visual spec reads a component token (styles/tokens/components.css, --button-*). // Sizes: sm | md | lg (default = md). Variants: primary (default) | secondary | outline | ghost | link. const filled = { primary: "bg-(--button-primary-container) text-(--button-primary-label) hover:bg-(--button-primary-container-hover) active:bg-(--button-primary-container-pressed)", secondary: "bg-(--button-secondary-container) text-(--button-secondary-label) hover:bg-(--button-secondary-container-hover) active:bg-(--button-secondary-container-pressed) aria-expanded:bg-(--button-secondary-container-hover)", } const buttonVariants = cva( "liquid-press group/button relative inline-flex shrink-0 items-center justify-center overflow-hidden rounded-(--button-corner) border-solid border-(length:--button-stroke-width) border-(--stroke-color-default) bg-clip-padding text-(length:--button-label-size) [font-weight:var(--button-label-weight)] whitespace-nowrap outline-none select-none focus-visible:shadow-(--focus-ring) disabled:pointer-events-none disabled:bg-(--button-container-disabled) disabled:text-(--button-label-disabled) disabled:shadow-none aria-invalid:shadow-(--focus-ring-invalid) [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-(--button-icon-size)", { variants: { variant: { primary: filled.primary, default: filled.primary, secondary: filled.secondary, outline: "bg-(--button-outline-container) text-(--button-secondary-label) shadow-(--button-outline-elevation) hover:bg-(--button-outline-container-hover) active:bg-(--button-outline-container-pressed) aria-expanded:bg-(--button-outline-container-hover)", ghost: "text-(--button-secondary-label) hover:bg-(--button-ghost-container-hover) active:bg-(--button-ghost-container-pressed) aria-expanded:bg-(--button-ghost-container-hover) disabled:bg-transparent", destructive: "", link: "text-(--button-link-label) underline-offset-4 hover:underline disabled:bg-transparent", }, size: { xs: "active:not-disabled:rounded-(--button-corner-pressed) h-(--button-height-xs) gap-(--button-gap-sm) px-(--button-padding-x-xs) text-(length:--button-label-size-sm) [&_svg:not([class*='size-'])]:size-(--button-icon-size-sm)", sm: "active:not-disabled:rounded-(--button-corner-pressed) h-(--button-height-sm) gap-(--button-gap-sm) px-(--button-padding-x-sm) [&_svg:not([class*='size-'])]:size-(--button-icon-size-sm)", md: "active:not-disabled:rounded-(--button-corner-pressed) h-(--button-height-md) gap-(--button-gap) px-(--button-padding-x-md) has-data-[icon=inline-end]:pe-(--button-padding-x-sm) has-data-[icon=inline-start]:ps-(--button-padding-x-sm)", default: "active:not-disabled:rounded-(--button-corner-pressed) h-(--button-height-md) gap-(--button-gap) px-(--button-padding-x-md) has-data-[icon=inline-end]:pe-(--button-padding-x-sm) has-data-[icon=inline-start]:ps-(--button-padding-x-sm)", lg: "active:not-disabled:rounded-(--button-corner-pressed) h-(--button-height-lg) gap-(--button-gap) px-(--button-padding-x-lg) has-data-[icon=inline-end]:pe-(--button-padding-x-md) has-data-[icon=inline-start]:ps-(--button-padding-x-md) [&_svg:not([class*='size-'])]:size-(--button-icon-size-lg)", icon: "size-(--icon-button-size-md) rounded-(--icon-button-corner)", "icon-xs": "size-(--button-height-xs) rounded-(--icon-button-corner) [&_svg:not([class*='size-'])]:size-(--button-icon-size-sm)", "icon-sm": "size-(--icon-button-size-sm) rounded-(--icon-button-corner) [&_svg:not([class*='size-'])]:size-(--button-icon-size-sm)", "icon-md": "size-(--icon-button-size-md) rounded-(--icon-button-corner)", "icon-lg": "size-(--icon-button-size-lg) rounded-(--icon-button-corner) [&_svg:not([class*='size-'])]:size-(--button-icon-size-lg)", }, tone: { neutral: "", danger: "", success: "", }, }, // tone: colour intent on any variant (component-model.md §7). destructive = tone danger. compoundVariants: [ { tone: "danger", variant: ["primary", "default", "secondary", "outline", "destructive"], className: "bg-(--button-danger-container) text-(--button-danger-label) shadow-none hover:bg-(--button-danger-container-hover) active:bg-(--button-danger-container-pressed) [--focus-ring-color:var(--color-danger)]", }, { tone: "danger", variant: ["ghost", "link"], className: "text-(--button-danger-label) hover:bg-(--button-danger-container) active:bg-(--button-danger-container-hover) [--focus-ring-color:var(--color-danger)]", }, { tone: "success", variant: ["primary", "default", "secondary", "outline"], className: "bg-(--button-success-container) text-(--button-success-label) shadow-none hover:bg-(--button-success-container-hover) active:bg-(--button-success-container-pressed)", }, ], defaultVariants: { variant: "primary", size: "md", tone: "neutral", }, } ) type Wash = { id: number; x: number; y: number } type Status = "idle" | "loading" | "success" | "error" type ButtonProps = ButtonPrimitive.Props & VariantProps<typeof buttonVariants> & { /** * The button shows its own result inside a fixed width: spinner, then a * check or a cross. Prefer this to a toast (component-model.md §5). */ status?: Status /** "hold": the click only happens after holding for --duration-fill (pointer, Space or Enter). */ confirm?: "hold" /** Screen reader text for the success and error states. */ statusLabel?: { success?: string; error?: string } /** @deprecated use status="loading" */ loading?: boolean /** @deprecated use status="success" */ success?: boolean } function Button({ className, variant = "primary", size = "md", tone = "neutral", status: statusProp, confirm, statusLabel, loading = false, success = false, children, onClick, onPointerUp, onPointerDown, onPointerLeave, onKeyDown, onKeyUp, ...props }: ButtonProps) { const status: Status = statusProp ?? (loading ? "loading" : success ? "success" : "idle") const busy = status === "loading" const [wash, setWash] = useState<Wash | null>(null) const [held, setHeld] = useState(false) const holdTimer = useRef(0) const allowClick = useRef(false) const self = useRef<HTMLElement | null>(null) const resolvedTone = variant === "destructive" ? "danger" : tone function startHold(element: HTMLElement) { if (confirm !== "hold" || busy) return self.current = element setHeld(true) window.clearTimeout(holdTimer.current) holdTimer.current = window.setTimeout(() => { setHeld(false) allowClick.current = true self.current?.click() allowClick.current = false }, tokenMs("--duration-fill", element)) } function stopHold() { if (confirm !== "hold") return setHeld(false) window.clearTimeout(holdTimer.current) } function handleClick(event: Parameters<NonNullable<ButtonProps["onClick"]>>[0]) { if (busy || (confirm === "hold" && !allowClick.current)) { event.preventDefault() return } onClick?.(event) } function handlePointerUp(event: Parameters<NonNullable<ButtonProps["onPointerUp"]>>[0]) { onPointerUp?.(event) stopHold() if (event.defaultPrevented || busy || confirm === "hold") return if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return const motion = event.currentTarget.closest<HTMLElement>("[data-motion]")?.dataset.motion if (motion === "calm" || motion === "still") return const rect = event.currentTarget.getBoundingClientRect() setWash({ id: Date.now(), x: event.clientX - rect.left, y: event.clientY - rect.top, }) } const showResult = status === "success" || status === "error" return ( <ButtonPrimitive data-slot="button" data-icon={typeof size === "string" && size.startsWith("icon") ? "" : undefined} data-tone={resolvedTone} data-status={status} data-confirm={confirm} aria-busy={busy || undefined} aria-disabled={busy || undefined} {...props} className={cn( buttonVariants({ variant, size, tone: resolvedTone, className }), status === "error" && "animate-[isotope-nudge_var(--duration-fast)_var(--ease-out)]" )} onClick={handleClick} onPointerUp={handlePointerUp} onPointerDown={(event) => { onPointerDown?.(event) if (event.button === 0) startHold(event.currentTarget) }} onPointerLeave={(event) => { onPointerLeave?.(event) stopHold() }} onKeyDown={(event) => { onKeyDown?.(event) if (confirm === "hold" && (event.key === " " || event.key === "Enter") && !event.repeat) { startHold(event.currentTarget) } }} onKeyUp={(event) => { onKeyUp?.(event) if (event.key === " " || event.key === "Enter") stopHold() }} > {confirm === "hold" ? ( <span aria-hidden data-held={held ? "" : undefined} className="hold-fill pointer-events-none absolute inset-y-0 left-0 w-full bg-current opacity-20" /> ) : null} <span className={cn( "button-label relative inline-flex items-center justify-center gap-[inherit]", (busy || showResult) && "opacity-0 blur-(--motion-blur-enter) transition-[opacity,filter] duration-(--duration-fast) ease-(--ease-out)" )} > {children} {confirm === "hold" ? <span className="sr-only">(hold to confirm)</span> : null} </span> {showResult ? ( <span className="button-success absolute inset-0 inline-flex items-center justify-center" role="status"> <span className="sr-only"> {status === "success" ? statusLabel?.success ?? "Done" : statusLabel?.error ?? "Failed"} </span> {status === "success" ? <CheckIcon aria-hidden /> : <XIcon aria-hidden />} </span> ) : null} {busy ? ( <span className="absolute inset-0 inline-flex items-center justify-center gap-inline-xs"> <span className="sr-only">Loading</span> {[0, 1, 2].map((dot) => ( <span key={dot} aria-hidden className="size-inline-xs rounded-full bg-current animate-[isotope-pulse_var(--duration-pulse)_var(--ease-out)_infinite]" style={{ animationDelay: `calc(var(--duration-stagger) * ${dot})` }} /> ))} </span> ) : null} {wash ? ( <span key={wash.id} aria-hidden onAnimationEnd={() => setWash(null)} className="pointer-events-none absolute size-[calc(var(--size-control-lg)*4)] rounded-full bg-current animate-[isotope-wash_var(--duration-settle)_var(--ease-out)_both]" style={{ left: wash.x, top: wash.y }} /> ) : null} </ButtonPrimitive> ) } export { Button, buttonVariants } export type { ButtonProps }components/ui/spinner.tsxspinner
components/ui/spinner.tsximport * as React from "react" import { CheckIcon } from "lucide-react" import { cn } from "cn" /* Spinner: a short, unknown wait. Three buoyant dots (or a ring). When the work succeeds, set done: the dots gather into the centre and pop into a check. Sizes follow the icon tokens. */ const sizes = { sm: "h-icon-sm", md: "h-icon-md", lg: "h-icon-lg" } function Spinner({ className, size = "md", variant = "dots", done = false, label = "Loading", ...props }: React.ComponentProps<"span"> & { size?: keyof typeof sizes /** dots (default), ring, wave, orbit, morph, typing. All resolve into the same check. */ variant?: "dots" | "ring" | "wave" | "orbit" | "morph" | "typing" done?: boolean label?: string }) { return ( <span role="status" data-slot="spinner" data-done={done || undefined} className={cn("spinner relative inline-flex items-center justify-center", sizes[size], className)} {...props} > <span className="sr-only">{done ? "Done" : label}</span> {variant === "dots" || variant === "typing" ? ( <span aria-hidden data-variant={variant} className="spinner-dots inline-flex h-full items-center gap-[0.2em]"> {[0, 1, 2].map((dot) => ( <span key={dot} className="spinner-dot aspect-square h-[28%] rounded-full bg-current" style={{ "--dot": dot } as React.CSSProperties} /> ))} </span> ) : variant === "wave" ? ( <span aria-hidden className="spinner-dots inline-flex h-full items-center gap-[0.15em]"> {[0, 1, 2, 3].map((bar) => ( <span key={bar} className="spinner-bar h-full w-[0.18em] rounded-full bg-current" style={{ "--dot": bar } as React.CSSProperties} /> ))} </span> ) : variant === "orbit" ? ( <span aria-hidden className="spinner-dots spinner-orbit relative aspect-square h-full"> <span className="absolute top-0 left-1/2 aspect-square h-[30%] -translate-x-1/2 rounded-full bg-current" /> </span> ) : variant === "morph" ? ( <span aria-hidden className="spinner-dots spinner-morph aspect-square h-[70%] bg-current" /> ) : ( <span aria-hidden className="spinner-ring aspect-square h-full rounded-full" /> )} <CheckIcon aria-hidden className="spinner-check absolute aspect-square h-full w-auto" strokeWidth={2.5} /> </span> ) } export { Spinner }components/ui/pull-to-refresh.tsxpull-to-refresh
components/ui/pull-to-refresh.tsx"use client" import * as React from "react" import { RefreshCwIcon } from "lucide-react" import { cn } from "cn" import { Button } from "@/components/ui/button" import { Spinner } from "@/components/ui/spinner" import { tokenMs } from "@/lib/motion/token-ms" /* Pull to refresh (slingshot): pull the list down from the top and a blob stretches from the top edge. Past the threshold it detaches into a spinner; when onRefresh resolves, the spinner pops into a check and the content settles. A Refresh button does the same without pulling. */ function PullToRefresh({ onRefresh, children, threshold = 72, className, }: { onRefresh: () => Promise<void> children: React.ReactNode threshold?: number className?: string }) { const scrollRef = React.useRef<HTMLDivElement>(null) const start = React.useRef<number | null>(null) const [pull, setPull] = React.useState(0) const [state, setState] = React.useState<"idle" | "refreshing" | "done">("idle") async function refresh() { setState("refreshing") setPull(threshold) await onRefresh() setState("done") window.setTimeout(() => { setState("idle") setPull(0) }, tokenMs("--duration-signature")) } const ready = pull >= threshold return ( <div data-slot="pull-to-refresh" className={cn("relative flex flex-col gap-2", className)}> <div className="relative min-h-0 flex-1 overflow-hidden rounded-(--shape-lg)"> <span aria-hidden data-ready={ready || undefined} className="refresh-blob pointer-events-none absolute start-1/2 top-0 z-[1] flex -translate-x-1/2 items-end justify-center rounded-b-full bg-(--refresh-blob)" style={{ height: state === "idle" ? pull : threshold * 0.7, width: Math.max(24, 56 - pull / 4) }} > <span className="mb-1.5 inline-flex"> {state === "refreshing" ? <Spinner size="sm" label="Refreshing" /> : state === "done" ? <Spinner size="sm" done /> : <RefreshCwIcon className="size-(--size-icon-sm)" style={{ rotate: `${pull * 3}deg`, opacity: Math.min(1, pull / threshold) }} />} </span> </span> <div ref={scrollRef} className="refresh-content h-full touch-pan-x overflow-y-auto" style={{ translate: `0 ${state === "idle" ? pull * 0.5 : threshold * 0.5}px` }} onPointerDown={(event) => { if ((scrollRef.current?.scrollTop ?? 1) > 0 || state !== "idle") return event.currentTarget.setPointerCapture(event.pointerId) start.current = event.clientY }} onPointerMove={(event) => { if (start.current === null) return const dy = event.clientY - start.current setPull(Math.max(0, Math.min(threshold * 1.5, dy * 0.6))) }} onPointerUp={() => { start.current = null if (pull >= threshold) void refresh() else setPull(0) }} > {children} </div> </div> <Button size="sm" variant="ghost" className="self-center" status={state === "refreshing" ? "loading" : "idle"} onClick={() => void refresh()}> Refresh </Button> <p role="status" className="sr-only"> {state === "refreshing" ? "Refreshing" : state === "done" ? "Up to date" : ""} </p> </div> ) } export { PullToRefresh }
Imports
What the examples on this page import:
import { Badge } from "@/components/ui/badge"
import { PagePeel } from "@/components/ui/page-peel"
import { PullToRefresh } from "@/components/ui/pull-to-refresh"
import { SignaturePad } from "@/components/ui/signature-pad"
import { SortableList } from "@/components/ui/sortable-list"
import { SwipeDeck } from "@/components/ui/swipe-deck"
import { tokenMs } from "@/lib/motion/token-ms"Anatomy
- 1Blob · --refresh-blob; turns selected past the threshold.
- 2Content · Slides down with the pull.
- 3Refresh button · No-pull alternative.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
onRefresh | () => Promise<void> | — | Your refresh. |
threshold | number | 72 | Pull distance in px. |
Tokens
Every visual spec is a component token in styles/tokens/components.css, pointing at a semantic token. Change a token to restyle the component; themes change the semantic layer.
| Token | Points to | Light | Dark |
|---|---|---|---|
--refresh-blob | var(--surface-container-high) | oklch(0.94 0.007 95) | oklch(0.27 0 0) |
--refresh-threshold | var(--space-16) | 64px | same |
Motion
| Trigger | What happens | Tokens |
|---|---|---|
| Pull / release | Blob stretches on a bouncy spring; spinner; check pops. | --spring-bouncy |
Calm keeps the motion without overshoot. Still (and reduced motion) keeps a designed frame with no movement.
Accessibility
- A visible Refresh button; the status is announced.
Usage
Do
- Use on feeds and inboxes.
Don’t
- Don't make pulling the only way to refresh.
Code
"use client"
import * as React from "react"
import { RefreshCwIcon } from "lucide-react"
import { cn } from "cn"
import { Button } from "@/components/ui/button"
import { Spinner } from "@/components/ui/spinner"
import { tokenMs } from "@/lib/motion/token-ms"
/*
Pull to refresh (slingshot): pull the list down from the top and a blob
stretches from the top edge. Past the threshold it detaches into a
spinner; when onRefresh resolves, the spinner pops into a check and the
content settles. A Refresh button does the same without pulling.
*/
function PullToRefresh({
onRefresh,
children,
threshold = 72,
className,
}: {
onRefresh: () => Promise<void>
children: React.ReactNode
threshold?: number
className?: string
}) {
const scrollRef = React.useRef<HTMLDivElement>(null)
const start = React.useRef<number | null>(null)
const [pull, setPull] = React.useState(0)
const [state, setState] = React.useState<"idle" | "refreshing" | "done">("idle")
async function refresh() {
setState("refreshing")
setPull(threshold)
await onRefresh()
setState("done")
window.setTimeout(() => {
setState("idle")
setPull(0)
}, tokenMs("--duration-signature"))
}
const ready = pull >= threshold
return (
<div data-slot="pull-to-refresh" className={cn("relative flex flex-col gap-2", className)}>
<div className="relative min-h-0 flex-1 overflow-hidden rounded-(--shape-lg)">
<span
aria-hidden
data-ready={ready || undefined}
className="refresh-blob pointer-events-none absolute start-1/2 top-0 z-[1] flex -translate-x-1/2 items-end justify-center rounded-b-full bg-(--refresh-blob)"
style={{ height: state === "idle" ? pull : threshold * 0.7, width: Math.max(24, 56 - pull / 4) }}
>
<span className="mb-1.5 inline-flex">
{state === "refreshing" ? <Spinner size="sm" label="Refreshing" /> : state === "done" ? <Spinner size="sm" done /> : <RefreshCwIcon className="size-(--size-icon-sm)" style={{ rotate: `${pull * 3}deg`, opacity: Math.min(1, pull / threshold) }} />}
</span>
</span>
<div
ref={scrollRef}
className="refresh-content h-full touch-pan-x overflow-y-auto"
style={{ translate: `0 ${state === "idle" ? pull * 0.5 : threshold * 0.5}px` }}
onPointerDown={(event) => {
if ((scrollRef.current?.scrollTop ?? 1) > 0 || state !== "idle") return
event.currentTarget.setPointerCapture(event.pointerId)
start.current = event.clientY
}}
onPointerMove={(event) => {
if (start.current === null) return
const dy = event.clientY - start.current
setPull(Math.max(0, Math.min(threshold * 1.5, dy * 0.6)))
}}
onPointerUp={() => {
start.current = null
if (pull >= threshold) void refresh()
else setPull(0)
}}
>
{children}
</div>
</div>
<Button size="sm" variant="ghost" className="self-center" status={state === "refreshing" ? "loading" : "idle"} onClick={() => void refresh()}>
Refresh
</Button>
<p role="status" className="sr-only">
{state === "refreshing" ? "Refreshing" : state === "done" ? "Up to date" : ""}
</p>
</div>
)
}
export { PullToRefresh }