Shimmering Text
A status line with light sweeping across it, meaning the work it names is happening now.
Installation
$
npx shadcn@latest add https://ui.mattdowney.com/r/shimmering-text.jsonUsage
import { ShimmeringText } from "@/components/ui/shimmering-text"Examples
Default
Say what is happening, not that something is. The line ends in a still ellipsis while it runs, and holds still under reduced motion.
Thinking…
Steps
Feed it each real step as it happens; the old words sink out as the new ones rise in. active={false} settles the finished line to plain text. Never rotate made-up steps on a timer.
Searching your documents…
API Reference
| Prop | Type | Default | Description |
|---|---|---|---|
| text* | string | None | What is happening, in a few words. |
| active | boolean | true | false settles to plain muted text with no sweep and no ellipsis, for a status that has finished. |
| ellipsis | boolean | true | Ends the line in a still ellipsis while active. An ellipsis already on the text is never doubled. |
| elapsed | boolean | false | Shows a quiet seconds count after the words once the wait passes 5 seconds. It does not reset when the words change. |
| align | "start" | "center" | "start" | Where the line sits in its parent, so changing words leave from the same place. Use center under a centred element. |
| duration | number | the ambient role (2s) | Length of one sweep, in seconds. Leave it unset so the sweep keeps the same clock as every other working loop. |
| delay | number | 0 | Delay before the first sweep, in seconds. |
| repeat | boolean | true | Whether the sweep loops. |
| repeatDelay | number | 0 | Pause between sweeps, in seconds. |
| startOnView | boolean | true | Starts the sweep only once the line is on screen. Set false to start at once. |
| once | boolean | false | When true, on-screen detection fires only the first time. |
| inViewMargin | string | None | Margin (rootMargin) for on-screen detection, e.g. "-100px". |
| spread | number | 2 | Band width per character, in pixels, so short and long lines sweep at the same softness. |
| color | string | None | Resting text color. Defaults to --muted-foreground. |
| shimmerColor | string | string[] | var(--color-neutral-50) | Color of the light at the band's center. Several colors blend across the band. |
| text*stringWhat is happening, in a few words. |
activeboolean = truefalse settles to plain muted text with no sweep and no ellipsis, for a status that has finished. |
| ellipsisboolean = trueEnds the line in a still ellipsis while active. An ellipsis already on the text is never doubled. |
| elapsedboolean = falseShows a quiet seconds count after the words once the wait passes 5 seconds. It does not reset when the words change. |
align"start" | "center" = "start"Where the line sits in its parent, so changing words leave from the same place. Use center under a centred element. |
| durationnumber = the ambient role (2s)Length of one sweep, in seconds. Leave it unset so the sweep keeps the same clock as every other working loop. |
| delaynumber = 0Delay before the first sweep, in seconds. |
| repeatboolean = trueWhether the sweep loops. |
| repeatDelaynumber = 0Pause between sweeps, in seconds. |
startOnViewboolean = trueStarts the sweep only once the line is on screen. Set false to start at once. |
onceboolean = falseWhen true, on-screen detection fires only the first time. |
inViewMarginstringMargin (rootMargin) for on-screen detection, e.g. "-100px". |
| spreadnumber = 2Band width per character, in pixels, so short and long lines sweep at the same softness. |
colorstringResting text color. Defaults to --muted-foreground. |
| shimmerColorstring | string[] = var(--color-neutral-50)Color of the light at the band's center. Several colors blend across the band. |
"use client"
import React, { useEffect, useMemo, useRef, useState } from "react"
import { motion, useInView, useReducedMotion, UseInViewOptions } from "motion/react"
import { cn } from "@/registry/lib/utils"
interface ShimmeringTextProps {
/** Text to display with shimmer effect */
text: string
/**
* Whether the work is still running. `false` settles to plain muted text with
* no sweep and no ellipsis, for a status that has finished.
*/
active?: boolean
/** Ends the line in a still ellipsis while active ("Thinking…"). */
ellipsis?: boolean
/** Shows a quiet seconds count after the words once the wait passes 5s. */
elapsed?: boolean
/** How the line sits in its parent, so changing words leave from the right place. */
align?: "start" | "center"
/** One sweep, in seconds. Defaults to the kit's ambient role (2s). */
duration?: number
/** Delay before starting animation */
delay?: number
/** Whether to repeat the animation */
repeat?: boolean
/** Pause duration between repeats in seconds */
repeatDelay?: number
/** Custom className */
className?: string
/** Whether to start animation when component enters viewport */
startOnView?: boolean
/** Whether to animate only once */
once?: boolean
/** Margin for in-view detection (rootMargin) */
inViewMargin?: UseInViewOptions["margin"]
/** Shimmer spread multiplier */
spread?: number
/** Base text color */
color?: string
/**
* Shimmer (moving sweep) color. A single color, or several for a multi-hue
* sweep: the colors blend across the band's center so the light reads as a
* gradient. The resting text color is unaffected; this only paints the
* moving highlight.
*/
shimmerColor?: string | string[]
}
const ELAPSED_THRESHOLD_S = 5
// The ambient role, read off the page so a project that retunes
// `--transition-duration-ambient` or `--ease-ambient` in its `:root` retunes
// this sweep with every other "working" loop (Skeleton, indeterminate
// Progress). The fallbacks are the role's shipped values.
type Ease = [number, number, number, number]
const AMBIENT_FALLBACK = { duration: 2, ease: [0.4, 0, 0.6, 1] as Ease }
function readAmbientRole(el: Element) {
const cs = getComputedStyle(el)
const d = cs.getPropertyValue("--transition-duration-ambient").trim()
const seconds = d.endsWith("ms") ? parseFloat(d) / 1000 : parseFloat(d)
const nums = cs.getPropertyValue("--ease-ambient").match(/-?\d*\.?\d+/g)?.map(Number)
return {
duration: Number.isFinite(seconds) && seconds > 0 ? seconds : AMBIENT_FALLBACK.duration,
ease: nums && nums.length === 4 ? (nums as Ease) : AMBIENT_FALLBACK.ease,
}
}
// The moving band: graded all the way through, transparent to a half-strength
// tint to the light at its center and back, so it reads as light passing over
// the words rather than a bar scanning them. No flat core.
function buildShimmerBand(colors: string[]): string {
const mid = (c: string) => `color-mix(in oklab, ${c} 50%, transparent)`
if (colors.length === 1) {
const c = colors[0]
return `linear-gradient(90deg,transparent calc(50% - var(--spread)),${mid(c)} calc(50% - var(--spread) / 2),${c} 50%,${mid(c)} calc(50% + var(--spread) / 2),transparent calc(50% + var(--spread)))`
}
const stops = colors
.map((c, i) => `${c} calc(50% + var(--spread) * ${(-0.5 + i / (colors.length - 1)).toFixed(4)})`)
.join(",")
return `linear-gradient(90deg,transparent calc(50% - var(--spread)),${stops},transparent calc(50% + var(--spread)))`
}
// Any ellipsis already on the text is dropped first, so it is never doubled.
const withEllipsis = (text: string) => `${text.replace(/\s*(\.{3}|…)\s*$/, "")}…`
// @use-when a line that says what is happening right now while it happens ("Thinking", "Refunding $42"): a light sweeps across it until the work ends.
export function ShimmeringText({
text,
active = true,
ellipsis = true,
elapsed = false,
align = "start",
duration,
delay = 0,
repeat = true,
repeatDelay = 0,
className,
startOnView = true,
once = false,
inViewMargin,
spread = 2,
color,
shimmerColor,
}: ShimmeringTextProps) {
const ref = useRef<HTMLSpanElement>(null)
const isInView = useInView(ref, { once, margin: inViewMargin })
const shouldReduceMotion = useReducedMotion()
const label = active && ellipsis ? withEllipsis(text) : text
// Spread scales with length, so short and long lines sweep at the same softness.
const dynamicSpread = useMemo(() => text.length * spread, [text, spread])
const shouldAnimate = active && !shouldReduceMotion && (!startOnView || isInView)
const [role, setRole] = useState(AMBIENT_FALLBACK)
useEffect(() => {
if (ref.current) setRole(readAmbientRole(ref.current))
}, [])
// A new label crossfades in place: the old words leave out of flow, sinking,
// and the new ones rise in. Never on the first paint, so the line does not
// pop in for a reader who did not ask for that.
// Derived during render, so the new words mount already carrying their
// enter transition.
const [prevLabel, setPrevLabel] = useState(label)
const [leaving, setLeaving] = useState<string | null>(null)
const [hasChanged, setHasChanged] = useState(false)
if (label !== prevLabel) {
setLeaving(prevLabel)
setPrevLabel(label)
setHasChanged(true)
}
// Whole seconds since the wait began. It measures the whole wait, so it does
// not reset when the words change.
const [seconds, setSeconds] = useState(0)
useEffect(() => {
if (!elapsed || !active) return
const startedAt = Date.now()
const id = setInterval(() => setSeconds(Math.floor((Date.now() - startedAt) / 1000)), 1000)
// Reset on the way out, not on the way in: a setState at the top of an
// effect fails react-hooks/set-state-in-effect in a consumer's lint.
return () => {
clearInterval(id)
setSeconds(0)
}
}, [elapsed, active])
const showElapsed = elapsed && active && seconds >= ELAPSED_THRESHOLD_S
const band =
Array.isArray(shimmerColor) && shimmerColor.length > 0
? buildShimmerBand(shimmerColor)
: buildShimmerBand(["var(--shimmer-color)"])
return (
<span
ref={ref}
data-slot="shimmering-text"
className={cn(
"relative inline-flex items-baseline gap-1 text-(--base-color) [--base-color:var(--muted-foreground)]",
// The light: the palest neutral in both modes, so the sweep is brighter
// than the resting text on a light page and on a dark one.
"[--shimmer-color:var(--color-neutral-50)]",
className
)}
style={
{
"--spread": `${dynamicSpread}px`,
...(color && { "--base-color": color }),
...(typeof shimmerColor === "string" && { "--shimmer-color": shimmerColor }),
} as React.CSSProperties
}
>
<motion.span
key={label}
data-slot="shimmering-text-words"
className={cn(
active && !shouldReduceMotion && "bg-[length:250%_100%,auto] bg-clip-text text-transparent [background-repeat:no-repeat,padding-box]",
hasChanged &&
"transition-[opacity,translate] duration-large ease-large starting:translate-y-1 starting:opacity-0 motion-reduce:transition-none"
)}
style={
active && !shouldReduceMotion
? { backgroundImage: `${band}, linear-gradient(var(--base-color), var(--base-color))` }
: undefined
}
initial={{ backgroundPosition: "100% center" }}
animate={shouldAnimate ? { backgroundPosition: "0% center" } : {}}
transition={{
backgroundPosition: {
repeat: repeat ? Infinity : 0,
// The ambient role: the same clock as Skeleton's pulse.
duration: duration ?? role.duration,
delay,
repeatDelay,
ease: role.ease,
},
}}
>
{label}
</motion.span>
{leaving !== null && (
<span
aria-hidden
data-slot="shimmering-text-leaving"
onTransitionEnd={() => setLeaving(null)}
className={cn(
"pointer-events-none absolute top-0 whitespace-nowrap",
align === "center" ? "start-1/2 -translate-x-1/2" : "start-0",
"translate-y-1 opacity-0 transition-[opacity,translate] duration-small ease-small starting:translate-y-0 starting:opacity-100 motion-reduce:transition-none",
"motion-reduce:hidden"
)}
>
{leaving}
</span>
)}
{showElapsed && (
<span
data-slot="shimmering-text-elapsed"
className="text-subtle-foreground tabular-nums transition-opacity duration-large ease-large starting:opacity-0 motion-reduce:transition-none"
>
{seconds}s
</span>
)}
</span>
)
}