Pause-First Rotating Carousel
Single-slide carousel that advances every six seconds, with the pause control first in the tab order and a timed bar on the current slide marker. Use it for announcement or testimonial rotations.
How it differs. Timer-driven: the rotation toggle and a status sentence sit before a crossfading stage, and the slide markers below double as the countdown. Hover and focus hold it, choosing a slide stops it.
Install
pnpm dlx shadcn@latest add @hazine/carousel-auto-rotate-pause-firstAdds 1 file, 1 shadcn primitive (button), 1 Hazine item (@hazine/use-controllable-state), and 1 package (lucide-react).
First time? Add the registry to components.json
{
"registries": {
"@hazine": "https://api.hazine.dev/r/{name}.json"
}
}Needed once per project. Items resolve each other through the @hazine namespace.
components/hazine/carousel-auto-rotate-pause-first.tsx, 448 lines
"use client"
import * as React from "react"
import { ArrowRight, ChevronLeft, ChevronRight, Pause, Play } from "lucide-react"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { useControllableState } from "@/hooks/use-controllable-state"
const MIN_INTERVAL_MS = 1000
const MAX_FRAME_MS = 100
const REDUCED_MOTION_QUERY = "(prefers-reduced-motion: reduce)"
export interface CarouselSlide {
id: string
/** Short tag above the title: a release, a category, a source. */
kicker?: string
title: string
body?: string
/** Attribution or footnote under the body. */
meta?: string
href?: string
linkLabel?: string
}
/** "{current}", "{total}", "{title}" and "{interval}" are replaced where they appear. */
export interface CarouselAutoRotatePauseFirstLabels {
pause: string
play: string
previous: string
next: string
rotating: string
rotatingDetail: string
held: string
heldDetail: string
paused: string
pausedDetail: string
position: string
goTo: string
loading: string
emptyTitle: string
emptyDescription: string
}
const DEFAULT_LABELS: CarouselAutoRotatePauseFirstLabels = {
pause: "Pause rotation",
play: "Start rotation",
previous: "Previous slide",
next: "Next slide",
rotating: "Rotating",
rotatingDetail: "every {interval}",
held: "On hold",
heldDetail: "while you read",
paused: "Paused",
pausedDetail: "until you start it",
position: "{current} of {total}",
goTo: "Show slide {current} of {total}: {title}",
loading: "Loading slides",
emptyTitle: "Nothing to announce yet",
emptyDescription: "New posts rotate here as soon as they are published.",
}
const DEFAULT_SLIDES: CarouselSlide[] = [
{
id: "release-4-2",
kicker: "Release 4.2",
title: "Shift swaps now need one approval, not two",
body: "Managers approve a swap from the notification itself. The second sign-off is gone for swaps inside the same role.",
href: "#release-4-2",
linkLabel: "Read the release notes",
},
{
id: "maintenance",
kicker: "Maintenance",
title: "Payroll exports pause on Saturday, 02:00 to 02:30 UTC",
body: "Exports requested during the 30 minute window queue and run in order once it closes. Nothing needs to be sent again.",
},
{
id: "pricing",
kicker: "Pricing",
title: "Annual plans drop from $12 to $9 a seat on January 1",
body: "That is $3 less per seat, or 25% off. Teams already on an annual plan move to the new rate at renewal.",
href: "#plans",
linkLabel: "Compare plans",
},
{
id: "webinar",
kicker: "Webinar",
title: "Rota planning for seasonal peaks, December 3",
body: "45 minutes with the scheduling team: 30 of walkthrough, 15 of questions. Everyone who registers gets the recording.",
href: "#webinar",
linkLabel: "Save a seat",
},
]
const focusClass =
"focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-foreground"
const softDisabledClass = "aria-disabled:pointer-events-none aria-disabled:opacity-50"
const slideClass =
"col-start-1 row-start-1 flex min-w-0 flex-col items-start gap-2 p-6 motion-safe:transition-all motion-safe:duration-300 motion-safe:ease-in-out @2xl:p-8"
const skeletonClass = "rounded-md bg-muted motion-safe:animate-pulse"
function fillLabel(template: string, values: Record<string, string | number>) {
return template.replace(/\{(\w+)\}/g, (match, key: string) =>
key in values ? String(values[key]) : match
)
}
function subscribeReducedMotion(notify: () => void) {
const query = window.matchMedia(REDUCED_MOTION_QUERY)
query.addEventListener("change", notify)
return () => query.removeEventListener("change", notify)
}
const readReducedMotion = () => window.matchMedia(REDUCED_MOTION_QUERY).matches
export interface CarouselAutoRotatePauseFirstProps
extends Omit<React.ComponentProps<"section">, "children" | "ref"> {
slides?: CarouselSlide[]
/** Accessible name of the carousel, for example "Product news". */
label?: string
/** Milliseconds each slide stays up. One second at least. */
interval?: number
/** Wraps from the last slide to the first. When false, rotation stops on the last slide. */
loop?: boolean
rotating?: boolean
defaultRotating?: boolean
onRotatingChange?: (rotating: boolean) => void
index?: number
defaultIndex?: number
onIndexChange?: (index: number) => void
loading?: boolean
/** One action shown in the empty state. */
emptyAction?: React.ReactNode
labels?: Partial<CarouselAutoRotatePauseFirstLabels>
locale?: string
}
export function CarouselAutoRotatePauseFirst({
slides = DEFAULT_SLIDES,
label = "Announcements",
interval = 6000,
loop = true,
rotating: rotatingProp,
defaultRotating = true,
onRotatingChange,
index,
defaultIndex = 0,
onIndexChange,
loading = false,
emptyAction,
labels,
locale = "en-US",
className,
onPointerEnter,
onPointerLeave,
...props
}: CarouselAutoRotatePauseFirstProps) {
const text = { ...DEFAULT_LABELS, ...labels }
const count = slides.length
const duration = Math.max(interval, MIN_INTERVAL_MS)
const [rawIndex, setIndex] = useControllableState({
value: index,
defaultValue: defaultIndex,
onChange: onIndexChange,
})
const [intent, setIntent] = useControllableState({
value: rotatingProp,
defaultValue: defaultRotating,
onChange: onRotatingChange,
})
// Under reduced motion nothing rotates until the user asks for it.
const [confirmed, setConfirmed] = React.useState(false)
const [hovered, setHovered] = React.useState(false)
const [focused, setFocused] = React.useState(false)
const reducedMotion = React.useSyncExternalStore(subscribeReducedMotion, readReducedMotion, () => false)
const current = Math.min(Math.max(rawIndex, 0), Math.max(count - 1, 0))
const atStart = !loop && current === 0
const atEnd = !loop && current === count - 1
const rotating = count > 1 && !loading && intent && (!reducedMotion || confirmed)
const held = rotating && (hovered || focused)
const ticking = rotating && !held
const timed = rotating && !reducedMotion
const root = React.useRef<HTMLElement>(null)
const elapsed = React.useRef(0)
const fill = React.useRef<HTMLSpanElement>(null)
// A new slide or a stop starts the countdown again. A hold keeps it.
React.useEffect(() => {
elapsed.current = 0
if (fill.current) fill.current.style.inlineSize = ""
}, [current, rotating])
// Focus arriving on any control holds rotation until focus leaves the carousel.
React.useEffect(() => {
const node = root.current
if (!node) return
const focusIn = () => setFocused(true)
const focusOut = (event: FocusEvent) => {
if (!(event.relatedTarget instanceof Node && node.contains(event.relatedTarget))) setFocused(false)
}
node.addEventListener("focusin", focusIn)
node.addEventListener("focusout", focusOut)
return () => {
node.removeEventListener("focusin", focusIn)
node.removeEventListener("focusout", focusOut)
}
}, [])
// Animation frames stop in a background tab, so slides never pass unseen. The
// first frame back spans the whole absence, so one frame counts for 100ms at most.
React.useEffect(() => {
if (!ticking) return
let frame = 0
let last = performance.now()
const step = (now: number) => {
elapsed.current += Math.min(Math.max(now - last, 0), MAX_FRAME_MS)
last = now
if (elapsed.current >= duration) {
elapsed.current = 0
if (atEnd) setIntent(false)
else setIndex((current + 1) % count)
}
if (fill.current && !reducedMotion) {
fill.current.style.inlineSize = `${(elapsed.current / duration) * 100}%`
}
frame = requestAnimationFrame(step)
}
frame = requestAnimationFrame(step)
return () => cancelAnimationFrame(frame)
}, [ticking, duration, current, count, atEnd, reducedMotion, setIndex, setIntent])
function toggleRotation() {
if (rotating) {
setIntent(false)
return
}
// Pressing Start is a clear request: it overrides the hold from the pointer
// or the focus that pressed it. The next pointer entry or focus move holds again.
setConfirmed(true)
setHovered(false)
setFocused(false)
if (atEnd) setIndex(0)
setIntent(true)
}
// Choosing a slide is a decision to read it, so rotation stays off afterwards.
function show(next: number) {
setIntent(false)
setIndex((next + count) % count)
}
const seconds = new Intl.NumberFormat(locale, {
style: "unit",
unit: "second",
unitDisplay: "long",
maximumFractionDigits: 1,
}).format(duration / 1000)
const ordinal = new Intl.NumberFormat(locale, { minimumIntegerDigits: 2 })
const state = !rotating ? "paused" : held ? "held" : "rotating"
const status = {
paused: [text.paused, text.pausedDetail],
held: [text.held, text.heldDetail],
rotating: [text.rotating, fillLabel(text.rotatingDetail, { interval: seconds })],
}[state]
return (
<section
ref={root}
data-slot="carousel-auto-rotate-pause-first"
data-state={state}
aria-roledescription="carousel"
aria-label={label}
aria-busy={loading || undefined}
className={cn(
"@container divide-y divide-border overflow-hidden rounded-xl border border-border bg-background text-foreground",
!loading && count === 0 && "border-dashed",
className
)}
onPointerEnter={(event) => {
setHovered(true)
onPointerEnter?.(event)
}}
onPointerLeave={(event) => {
setHovered(false)
onPointerLeave?.(event)
}}
{...props}
>
{!loading && count > 1 ? (
<div
data-slot="carousel-auto-rotate-pause-first-controls"
className="flex items-center gap-3 px-6 py-2 @2xl:px-8"
>
<Button
type="button"
variant="outline"
size="icon"
aria-label={rotating ? text.pause : text.play}
onClick={toggleRotation}
>
{rotating ? <Pause aria-hidden="true" /> : <Play aria-hidden="true" />}
</Button>
<p className="min-w-0 flex-1 truncate text-sm text-muted-foreground">
<span className="font-medium text-foreground">{status[0]}</span>
<span className="@max-sm:sr-only"> {status[1]}</span>
</p>
<p aria-hidden="true" className="font-mono text-xs text-muted-foreground tabular-nums">
<span className="font-medium text-foreground">{ordinal.format(current + 1)}</span>
{" / "}
{ordinal.format(count)}
</p>
<div className="flex items-center gap-1">
<Button
type="button"
variant="ghost"
size="icon"
aria-label={text.previous}
aria-disabled={atStart || undefined}
className={softDisabledClass}
onClick={() => {
if (!atStart) show(current - 1)
}}
>
<ChevronLeft aria-hidden="true" className="rtl:rotate-180" />
</Button>
<Button
type="button"
variant="ghost"
size="icon"
aria-label={text.next}
aria-disabled={atEnd || undefined}
className={softDisabledClass}
onClick={() => {
if (!atEnd) show(current + 1)
}}
>
<ChevronRight aria-hidden="true" className="rtl:rotate-180" />
</Button>
</div>
</div>
) : null}
{loading ? (
<div className="flex flex-col gap-3 p-6 @2xl:p-8">
<p role="status" className="sr-only">
{text.loading}
</p>
<span aria-hidden="true" className={cn(skeletonClass, "size-8")} />
<span aria-hidden="true" className={cn(skeletonClass, "h-3 w-24")} />
<span aria-hidden="true" className={cn(skeletonClass, "h-6 w-3/4")} />
<span aria-hidden="true" className={cn(skeletonClass, "h-4 w-full")} />
<span aria-hidden="true" className={cn(skeletonClass, "h-4 w-2/3")} />
<span aria-hidden="true" className={cn(skeletonClass, "h-1.5 w-16")} />
</div>
) : count === 0 ? (
<div
data-slot="carousel-auto-rotate-pause-first-empty"
className="flex flex-col items-start gap-1 p-6 @2xl:p-8"
>
<p className="text-sm font-semibold">{text.emptyTitle}</p>
<p className="max-w-prose text-sm text-muted-foreground">{text.emptyDescription}</p>
{emptyAction ? <div className="mt-3">{emptyAction}</div> : null}
</div>
) : (
<div
data-slot="carousel-auto-rotate-pause-first-slides"
aria-live={ticking ? "off" : "polite"}
className="grid"
>
{slides.map((slide, position) => (
<div
key={slide.id}
role="group"
aria-roledescription="slide"
aria-label={fillLabel(text.position, { current: position + 1, total: count })}
data-state={position === current ? "active" : "inactive"}
// Hidden slides keep their box, so the frame is as tall as the
// longest slide and never jumps. Visibility also takes them out
// of the tab order and the accessibility tree.
className={cn(slideClass, position === current ? "visible opacity-100" : "invisible opacity-0")}
>
{slide.kicker ? (
<p className="font-mono text-xs font-medium tracking-wider text-muted-foreground uppercase">
{slide.kicker}
</p>
) : null}
<p className="text-xl font-semibold tracking-tight text-balance wrap-anywhere @2xl:text-2xl">
{slide.title}
</p>
{slide.body ? (
<p className="max-w-prose text-sm wrap-anywhere text-muted-foreground">{slide.body}</p>
) : null}
{slide.meta ? <p className="text-xs text-muted-foreground">{slide.meta}</p> : null}
{slide.href ? (
<a
href={slide.href}
className={cn(
"mt-2 inline-flex min-h-6 items-center gap-1.5 text-sm font-medium underline-offset-4 hover:underline",
focusClass
)}
>
{slide.linkLabel ?? slide.title}
<ArrowRight aria-hidden="true" className="size-3.5 shrink-0 rtl:rotate-180" />
</a>
) : null}
</div>
))}
</div>
)}
{!loading && count > 1 ? (
<div
data-slot="carousel-auto-rotate-pause-first-progress"
className="flex flex-wrap gap-1 px-6 py-2 @2xl:px-8"
>
{slides.map((slide, position) => (
<button
key={slide.id}
type="button"
aria-label={fillLabel(text.goTo, {
current: position + 1,
total: count,
title: slide.title,
})}
aria-current={position === current ? "true" : undefined}
onClick={() => show(position)}
className={cn("group flex h-6 max-w-16 min-w-6 flex-1 items-center rounded-sm active:bg-muted", focusClass)}
>
{position === current ? (
<span className="block h-1.5 w-full overflow-hidden rounded-full bg-foreground/50">
<span
ref={fill}
className={cn("block h-full rounded-full bg-primary", timed ? "w-0" : "w-full")}
/>
</span>
) : (
<span className="block h-0.5 w-full rounded-full bg-foreground/50 transition-colors duration-100 group-hover:bg-foreground" />
)}
</button>
))}
</div>
) : null}
</section>
)
}
The demo in the preview, 151 lines
import * as React from "react"
import { Plus } from "lucide-react"
import { Button } from "@/components/ui/button"
import {
CarouselAutoRotatePauseFirst,
type CarouselSlide,
} from "@/components/hazine/carousel-auto-rotate-pause-first"
// The measure sits one level inside the full-width root, so a canvas that sizes
// the root of a demo cannot stretch the carousel.
function Frame({ children }: { children: React.ReactNode }) {
return (
<div className="w-full">
<div className="mx-auto max-w-2xl">{children}</div>
</div>
)
}
export default function CarouselAutoRotatePauseFirstDemo() {
return (
<Frame>
<CarouselAutoRotatePauseFirst label="Rotaboard announcements" />
</Frame>
)
}
const CUSTOMER_QUOTES: CarouselSlide[] = [
{
id: "quote-harrowgate",
kicker: "Hospitality, 140 staff",
title: "We stopped printing the rota in March and nobody asked for it back.",
body: "Swap requests used to reach me as text messages at midnight. Now they arrive as one approval, with the cover already named.",
meta: "Oluwaseun Adebayo, operations lead at Harrowgate Kitchens",
},
{
id: "quote-tidewell",
kicker: "Retail, 9 stores",
title: "Payroll closes on Monday morning now, not Wednesday afternoon.",
body: "Hours go from the schedule to the export without anyone retyping them, which removed 2 days from every pay run.",
meta: "Katarzyna Wolak, finance manager at Tidewell Outdoor",
},
{
id: "quote-penmoor",
kicker: "Care, 3 homes",
title: "Agency cover fell from 31 shifts a month to 12.",
body: "Open shifts go to our own staff first. 19 fewer agency shifts a month paid for the subscription in the first quarter.",
meta: "Dhruv Malhotra, registered manager at Penmoor Care",
},
]
function Paused() {
return (
<Frame>
<CarouselAutoRotatePauseFirst
label="Customer stories"
slides={CUSTOMER_QUOTES}
defaultRotating={false}
defaultIndex={1}
/>
</Frame>
)
}
function Bounds() {
return (
<Frame>
<CarouselAutoRotatePauseFirst
label="Customer stories"
slides={CUSTOMER_QUOTES}
loop={false}
defaultRotating={false}
defaultIndex={2}
/>
</Frame>
)
}
const CHANGELOG: CarouselSlide[] = [
{
id: "change-01",
kicker: "Release 4.2, scheduling and approvals",
title:
"Shift swaps inside the same role now need a single manager approval, and the approving manager can act on it straight from the push notification without opening the schedule",
body: "The second sign-off is gone for swaps inside the same role. Swaps across roles, across locations or into overtime still go to the location manager and then to payroll, in that order, and each step keeps its own 24 hour reminder. Declined swaps return to both people with the reason attached.",
meta: "Applies to every workspace on the Team and Business plans from November 18",
href: "#release-4-2",
linkLabel: "Read the full release notes for scheduling and approvals in 4.2",
},
{
id: "change-02",
kicker: "Integrations",
title: "Exports to payroll_provider_timesheet_batch_2026_11_weekly_final.csv keep their column order",
body: "Columns no longer reorder when a custom pay code is added.",
},
{ id: "change-03", kicker: "Mobile", title: "Clock in works offline for up to 12 hours" },
{ id: "change-04", kicker: "Mobile", title: "Open shifts show travel time from your last location" },
{ id: "change-05", kicker: "Reports", title: "Labour cost report splits base pay and premiums" },
{ id: "change-06", kicker: "Reports", title: "Overtime forecast covers the next 6 weeks" },
{ id: "change-07", kicker: "Admin", title: "Roles can be archived without removing their history" },
{ id: "change-08", kicker: "Admin", title: "Single sign-on supports 2 identity providers per workspace" },
{ id: "change-09", kicker: "Billing", title: "Invoices list seats added and removed during the period" },
{ id: "change-10", kicker: "Billing", title: "Annual plans can add seats at a prorated rate" },
{ id: "change-11", kicker: "Security", title: "Sessions end after 30 days without activity" },
{ id: "change-12", kicker: "Security", title: "Audit log exports include the approving device" },
]
function Overflow() {
return (
<Frame>
<CarouselAutoRotatePauseFirst
label="Changelog, November"
slides={CHANGELOG}
defaultRotating={false}
/>
</Frame>
)
}
function Empty() {
return (
<Frame>
<CarouselAutoRotatePauseFirst
label="Rotaboard announcements"
slides={[]}
emptyAction={
<Button size="sm">
<Plus aria-hidden="true" />
Write an announcement
</Button>
}
/>
</Frame>
)
}
function Loading() {
return (
<Frame>
<CarouselAutoRotatePauseFirst label="Rotaboard announcements" loading />
</Frame>
)
}
export const scenarios = {
paused: Paused,
bounds: Bounds,
overflow: Overflow,
empty: Empty,
loading: Loading,
}
Props14
- slides
- CarouselSlide[] = DEFAULT_SLIDES
- label
- string = "Announcements"
- Accessible name of the carousel, for example "Product news".
- interval
- number = 6000
- Milliseconds each slide stays up. One second at least.
- loop
- boolean = true
- Wraps from the last slide to the first. When false, rotation stops on the last slide.
- rotating
- boolean
- defaultRotating
- boolean = true
- onRotatingChange
- (rotating: boolean) => void
- index
- number
- defaultIndex
- number = 0
- onIndexChange
- (index: number) => void
- loading
- boolean = false
- emptyAction
- React.ReactNode
- One action shown in the empty state.
- labels
- Partial<CarouselAutoRotatePauseFirstLabels>
- locale
- string = "en-US"
Also accepts every prop of Omit<React.ComponentProps<"section">, "children" | "ref">.
Accessibility
- Keyboard
Keyboard support for Pause-First Rotating Carousel Key Effect Tab Moves through the rotation button, Previous slide, Next slide, the link of the visible slide, then one marker per slide. Focus arriving on any of them holds rotation until focus leaves the carousel Enter or Space on the rotation button Pauses or starts rotation. Start overrides the current hold, so slides rotate while focus stays on the button Enter or Space on Previous slide or Next slide Shows the neighbouring slide and stops rotation Enter or Space on a slide marker Shows that slide and stops rotation - Screen reader
A labelled section with the carousel role description. Each slide is a group named by its position. The rotation button comes first and its name switches between pause and start. The slide region is aria-live off while the timer runs and polite when it is held or paused.
- Announces: {kicker} {title} {body} {meta} {linkLabel}, read politely when a slide changes while rotation is held or paused
- Announces: Loading slides
- Reduced motion
- Starts paused and rotates only after the user presses Start rotation. Slides swap with no crossfade, the timed bar stays full and skeleton lines stop pulsing.
- Checked
- Not checked yet. Automated results appear here once CI has run.
Dependencies3
- button
- @hazine/use-controllable-state
- lucide-react
Filled chips are registry items the CLI adds for you. Outlined chips are npm packages.
Tokens shipped0
None. The item is styled by the tokens your theme already has.