Components

Carousel

Slides in a row on the Black ground, 16px apart, one to three in view, with ghost arrow buttons and the place in tabular figures. Native scroll snap: a swipe, a trackpad, the arrows and the arrow keys all move it. It never plays on its own. The track's edges fade while there are slides past them.

Install

React apps get the React files; every other stack gets the web component.

npx spyglass-ds add carousel
<script type="module" src="/spyglass-ds/elements/carousel.js"></script>
Saved creatives, three in view
1 / 5
One at a time
1 / 3

Usage

A row of saved creatives, quotes or offers that would crowd the page side by side. One slide in view on phones.

Never

  • Autoplay
  • Icons that move when the arrows are hovered
  • Dots in spectrum colors: the place reads in figures
  • Hiding the only copy of something important on a later slide

Adds with it: button packages lucide-react

Props

The web component takes the same as attributes or properties (<spyglass-carousel>); title is heading there.

<Carousel>

PropTypeDefault
countnumber

How many slides.

labelstring

What it holds, for assistive tech.

perView1 | 2 | 3

How many show at 768px and up.

1
slide(slot: { index: number }) => ReactNode

Draws slide `index`.

Examples

The same example in React and as web components; both render identically.

react/examples/carousel/Creatives.tsx
'use client'
import { Carousel } from '@/react/components/ui/Carousel'
// Saved creatives, three in view on wide screens and one on phones. Placeholders stand in for the ads.
const creatives = [
  { title: 'Acme summer UGC', meta: 'Video, 41 days running' },
  { title: 'Acme serum launch', meta: 'Carousel, 18 days running' },
  { title: 'Acme founder story', meta: 'Video, 63 days running' },
  { title: 'Acme bundle offer', meta: 'Image, 9 days running' },
  { title: 'Acme before and after', meta: 'Video, 27 days running' },
]

export default function Creatives() {
  return (
    <div className="w-full max-w-238">
      <Carousel
        label="Saved creatives"
        count={creatives.length}
        perView={3}
        slide={({ index }) => (
          <div className="flex flex-col gap-3">
            <div className="flex aspect-[4/5] items-end rounded-container bg-surface-raised p-4">
              <span className="type-label text-fg-muted">{`Creative ${index + 1}`}</span>
            </div>
            <div className="flex flex-col gap-1">
              <p className="type-ui-strong">{creatives[index]!.title}</p>
              <p className="type-caption text-fg-muted">{creatives[index]!.meta}</p>
            </div>
          </div>
        )}
      />
    </div>
  )
}
elements/examples/carousel/Creatives.html
<!-- Saved creatives, three in view on wide screens and one on phones. Placeholders stand in for the ads. -->
<div class="w-full max-w-238">
  <spyglass-carousel label="Saved creatives" per-view="3">
    <div class="flex flex-col gap-3">
      <div class="flex aspect-[4/5] items-end rounded-container bg-surface-raised p-4">
        <span class="type-label text-fg-muted">Creative 1</span>
      </div>
      <div class="flex flex-col gap-1">
        <p class="type-ui-strong">Acme summer UGC</p>
        <p class="type-caption text-fg-muted">Video, 41 days running</p>
      </div>
    </div>
    <div class="flex flex-col gap-3">
      <div class="flex aspect-[4/5] items-end rounded-container bg-surface-raised p-4">
        <span class="type-label text-fg-muted">Creative 2</span>
      </div>
      <div class="flex flex-col gap-1">
        <p class="type-ui-strong">Acme serum launch</p>
        <p class="type-caption text-fg-muted">Carousel, 18 days running</p>
      </div>
    </div>
    <div class="flex flex-col gap-3">
      <div class="flex aspect-[4/5] items-end rounded-container bg-surface-raised p-4">
        <span class="type-label text-fg-muted">Creative 3</span>
      </div>
      <div class="flex flex-col gap-1">
        <p class="type-ui-strong">Acme founder story</p>
        <p class="type-caption text-fg-muted">Video, 63 days running</p>
      </div>
    </div>
    <div class="flex flex-col gap-3">
      <div class="flex aspect-[4/5] items-end rounded-container bg-surface-raised p-4">
        <span class="type-label text-fg-muted">Creative 4</span>
      </div>
      <div class="flex flex-col gap-1">
        <p class="type-ui-strong">Acme bundle offer</p>
        <p class="type-caption text-fg-muted">Image, 9 days running</p>
      </div>
    </div>
    <div class="flex flex-col gap-3">
      <div class="flex aspect-[4/5] items-end rounded-container bg-surface-raised p-4">
        <span class="type-label text-fg-muted">Creative 5</span>
      </div>
      <div class="flex flex-col gap-1">
        <p class="type-ui-strong">Acme before and after</p>
        <p class="type-caption text-fg-muted">Video, 27 days running</p>
      </div>
    </div>
  </spyglass-carousel>
</div>
react/examples/carousel/Quotes.tsx
'use client'
import { Carousel } from '@/react/components/ui/Carousel'
// One quote at a time from Acme's team, on the #262626 card.
const quotes = [
  'We found the hook our competitors ran for 90 days in one search.',
  'Every brief starts with a board now. The team agrees faster.',
  'Ten minutes in Spyglass replaced a week of screenshots.',
]

export default function Quotes() {
  return (
    <div className="w-full max-w-150">
      <Carousel
        label="Quotes"
        count={quotes.length}
        slide={({ index }) => (
          <figure className="flex h-full flex-col justify-between gap-8 rounded-container bg-surface-raised p-8 max-sm:p-6">
            <blockquote className="type-heading-3">{quotes[index]}</blockquote>
            <figcaption className="type-caption text-fg-muted">Acme growth team</figcaption>
          </figure>
        )}
      />
    </div>
  )
}
elements/examples/carousel/Quotes.html
<!-- One quote at a time from Acme's team, on the #262626 card. -->
<div class="w-full max-w-150">
  <spyglass-carousel label="Quotes">
    <figure class="flex h-full flex-col justify-between gap-8 rounded-container bg-surface-raised p-8 max-sm:p-6">
      <blockquote class="type-heading-3">We found the hook our competitors ran for 90 days in one search.</blockquote>
      <figcaption class="type-caption text-fg-muted">Acme growth team</figcaption>
    </figure>
    <figure class="flex h-full flex-col justify-between gap-8 rounded-container bg-surface-raised p-8 max-sm:p-6">
      <blockquote class="type-heading-3">Every brief starts with a board now. The team agrees faster.</blockquote>
      <figcaption class="type-caption text-fg-muted">Acme growth team</figcaption>
    </figure>
    <figure class="flex h-full flex-col justify-between gap-8 rounded-container bg-surface-raised p-8 max-sm:p-6">
      <blockquote class="type-heading-3">Ten minutes in Spyglass replaced a week of screenshots.</blockquote>
      <figcaption class="type-caption text-fg-muted">Acme growth team</figcaption>
    </figure>
  </spyglass-carousel>
</div>

Source

react/components/ui/Carousel.tsx
'use client'
import { useEffect, useRef, useState, type KeyboardEvent, type ReactNode } from 'react'
import { ChevronLeft, ChevronRight } from 'lucide-react'
import { Button } from '@/react/components/ui/Button'

// shadcn's carousel in the brand: slides in a row on the Black ground, 16px apart, one or more in view, with two ghost
// arrow buttons and the place in tabular figures between them. Native scroll snap, so a swipe or a trackpad moves it
// as the arrows do; the arrows and the arrow keys on the focused track glide it with the browser's smooth scroll, and
// jump with reduced motion. It never plays on its own. Pass `count` and draw each slide with `slide({ index })`;
// `perView` sets how many show at 768px and up (one on phones).
export interface CarouselProps {
  /** How many slides. */
  count: number
  /** What it holds, for assistive tech. */
  label: string
  /** How many show at 768px and up. */
  perView?: 1 | 2 | 3
  /** Draws slide `index`. */
  slide?: (slot: { index: number }) => ReactNode
}

export function Carousel({ count, label, perView = 1, slide }: CarouselProps) {
  const track = useRef<HTMLDivElement | null>(null)
  const [current, setCurrent] = useState(0)
  const [visible, setVisible] = useState(1)
  const last = Math.max(0, count - visible)
  const countRef = useRef(count)
  countRef.current = count

  // One step: a slide and the gap after it.
  function stride(el: HTMLElement) {
    const [a, b] = el.children as unknown as HTMLElement[]
    return a ? (b ? b.offsetLeft - a.offsetLeft : a.offsetWidth) : 0
  }
  function measure() {
    const el = track.current
    const step = el ? stride(el) : 0
    if (!el || !step) return
    const v = Math.max(1, Math.round((el.clientWidth + step - (el.firstElementChild as HTMLElement).offsetWidth) / step))
    setVisible(v)
    setCurrent(Math.min(Math.max(0, countRef.current - v), Math.round(el.scrollLeft / step)))
  }
  function go(i: number) {
    const el = track.current
    const step = el ? stride(el) : 0
    if (!el || !step) return
    const reduce = globalThis.matchMedia?.('(prefers-reduced-motion: reduce)').matches
    el.scrollTo({ left: Math.max(0, Math.min(last, i)) * step, behavior: reduce ? 'auto' : 'smooth' })
  }
  function onKey(e: KeyboardEvent) {
    if (e.key === 'ArrowRight') { e.preventDefault(); go(current + 1) }
    if (e.key === 'ArrowLeft') { e.preventDefault(); go(current - 1) }
  }
  useEffect(() => {
    measure()
    const ro = new ResizeObserver(measure)
    if (track.current) ro.observe(track.current)
    return () => ro.disconnect()
  }, []) // eslint-disable-line react-hooks/exhaustive-deps

  return (
    <section data-ds="carousel" className="flex min-w-0 flex-col gap-3" role="region" aria-roledescription="carousel" aria-label={label}>
      <div
        ref={track}
        className="ds-carousel flex snap-x snap-mandatory gap-4 overflow-x-auto overscroll-x-contain rounded-container -outline-offset-2 fade-x"
        data-per-view={perView}
        tabIndex={0}
        aria-label={`${label}, use the arrow keys to move`}
        onScroll={measure}
        onKeyDown={onKey}
      >
        {Array.from({ length: count }, (_, k) => (
          <div key={k + 1} className="ds-carousel-slide min-w-0 shrink-0 snap-start" role="group" aria-roledescription="slide" aria-label={`${k + 1} of ${count}`}>
            {slide?.({ index: k })}
          </div>
        ))}
      </div>
      <div className="flex items-center justify-end gap-1">
        <Button variant="ghost" size="sm" icon disabled={current <= 0} aria-label={`Previous ${label}`} onClick={() => go(current - 1)}><ChevronLeft size={16} strokeWidth={1.5} aria-hidden="true" /></Button>
        <span className="min-w-12 text-center type-caption text-fg-muted tabular-nums" aria-live="polite">{`${current + 1} / ${last + 1}`}</span>
        <Button variant="ghost" size="sm" icon disabled={current >= last} aria-label={`Next ${label}`} onClick={() => go(current + 1)}><ChevronRight size={16} strokeWidth={1.5} aria-hidden="true" /></Button>
      </div>
      <style href="ds-carousel" precedence="ds">{css}</style>
    </section>
  )
}

export default Carousel

const css = `
.ds-carousel { scrollbar-width: none; }
.ds-carousel::-webkit-scrollbar { display: none; }
.ds-carousel-slide { width: 100%; }
@media (min-width: 768px) {
  .ds-carousel[data-per-view="2"] .ds-carousel-slide { width: calc((100% - var(--ds-space-lg)) / 2); }
  .ds-carousel[data-per-view="3"] .ds-carousel-slide { width: calc((100% - 2 * var(--ds-space-lg)) / 3); }
}
`
elements/components/ui/carousel.ts
import { html, LitElement, type PropertyValues } from 'lit'
import { html as staticHtml } from 'lit/static-html.js'
import { DsElement, define, tag } from '@/elements/lib/element'
import { icon } from '@/elements/lib/icon'
import { ChevronLeft, ChevronRight } from 'lucide'
import '@/elements/components/ui/button'
import styles from 'virtual:tw'

// Carousel.tsx as <spyglass-carousel>: slides in a row on the Black ground, 16px apart, one or more in view, with two
// ghost arrow buttons and the place in tabular figures between them. Native scroll snap, so a swipe or a trackpad
// moves it as the arrows do; the arrows and the arrow keys on the focused track glide it with the browser's smooth
// scroll, and jump with reduced motion. It never plays on its own. Each child element is a slide (React's `count` and
// `slide`): the element puts each in its own slide box. `per-view` sets how many show at 768px and up (one on phones).

/**
 * @summary Slides in a row with arrows and the place between them.
 * @slot - The slides: each child element is one.
 */
export class Carousel extends DsElement {
	static styles = [DsElement.styles, styles]
	// Each child goes into its own slide's slot, assigned by the element.
	static shadowRootOptions = { ...LitElement.shadowRootOptions, slotAssignment: 'manual' as const }
	static properties = { label: {}, perView: { type: Number, attribute: 'per-view' }, current: { state: true }, visible: { state: true }, slides: { state: true } }

	/** What it holds, for assistive tech. */
	label = ''
	/** How many show at 768px and up. */
	perView: 1 | 2 | 3 = 1
	private current = 0
	private visible = 1
	private slides: Element[] = []
	private ro?: ResizeObserver
	private mo?: MutationObserver

	private get count() {
		return this.slides.length
	}
	private get last() {
		return Math.max(0, this.count - this.visible)
	}
	private get track() {
		return this.renderRoot.querySelector<HTMLElement>('.ds-carousel')
	}
	// One step: a slide and the gap after it.
	private stride(el: HTMLElement) {
		const [a, b] = el.children as unknown as HTMLElement[]
		return a ? (b ? b.offsetLeft - a.offsetLeft : a.offsetWidth) : 0
	}

	private measure = () => {
		const el = this.track
		const step = el ? this.stride(el) : 0
		if (!el || !step) return
		this.visible = Math.max(1, Math.round((el.clientWidth + step - (el.firstElementChild as HTMLElement).offsetWidth) / step))
		this.current = Math.min(this.last, Math.round(el.scrollLeft / step))
	}
	private go(i: number) {
		const el = this.track
		const step = el ? this.stride(el) : 0
		if (!el || !step) return
		const reduce = globalThis.matchMedia?.('(prefers-reduced-motion: reduce)').matches
		el.scrollTo({ left: Math.max(0, Math.min(this.last, i)) * step, behavior: reduce ? 'auto' : 'smooth' })
	}
	private onKey = (e: KeyboardEvent) => {
		if (e.key === 'ArrowRight') {
			e.preventDefault()
			this.go(this.current + 1)
		}
		if (e.key === 'ArrowLeft') {
			e.preventDefault()
			this.go(this.current - 1)
		}
	}

	connectedCallback() {
		super.connectedCallback()
		this.slides = [...this.children]
		this.mo = new MutationObserver(() => { this.slides = [...this.children] })
		this.mo.observe(this, { childList: true })
	}
	disconnectedCallback() {
		super.disconnectedCallback()
		this.mo?.disconnect()
		this.ro?.disconnect()
	}

	protected firstUpdated(changed: PropertyValues) {
		super.firstUpdated(changed)
		this.measure()
		this.ro = new ResizeObserver(this.measure)
		if (this.track) this.ro.observe(this.track)
	}

	protected updated(changed: PropertyValues) {
		super.updated(changed)
		const slots = this.renderRoot.querySelectorAll<HTMLSlotElement>('slot')
		this.slides.forEach((s, k) => slots[k]?.assign(s))
	}

	render() {
		const count = this.count
		const last = this.last
		const button = tag('button')
		return html`<section data-ds="carousel" class="flex min-w-0 flex-col gap-3" role="region" aria-roledescription="carousel" aria-label=${this.label}><div class="ds-carousel flex snap-x snap-mandatory gap-4 overflow-x-auto overscroll-x-contain rounded-container -outline-offset-2 fade-x" data-per-view=${this.perView} tabindex="0" aria-label=${`${this.label}, use the arrow keys to move`} @scroll=${this.measure} @keydown=${this.onKey}>${this.slides.map((_, k) => html`<div class="ds-carousel-slide min-w-0 shrink-0 snap-start" role="group" aria-roledescription="slide" aria-label=${`${k + 1} of ${count}`}><slot></slot></div>`)}</div><div class="flex items-center justify-end gap-1">${staticHtml`<${button} variant="ghost" size="sm" icon ?disabled=${this.current <= 0} aria-label=${`Previous ${this.label}`} @click=${() => this.go(this.current - 1)}>${icon(ChevronLeft, 'chevron-left', { size: 16, strokeWidth: 1.5, attrs: { 'aria-hidden': 'true' } })}</${button}>`}<span class="min-w-12 text-center type-caption text-fg-muted tabular-nums" aria-live="polite">${`${this.current + 1} / ${last + 1}`}</span>${staticHtml`<${button} variant="ghost" size="sm" icon ?disabled=${this.current >= last} aria-label=${`Next ${this.label}`} @click=${() => this.go(this.current + 1)}>${icon(ChevronRight, 'chevron-right', { size: 16, strokeWidth: 1.5, attrs: { 'aria-hidden': 'true' } })}</${button}>`}</div></section>`
	}
}

define('carousel', Carousel)
elements/components/ui/carousel.css
/* Carousel.tsx's styles. */
.ds-carousel { scrollbar-width: none; }
.ds-carousel::-webkit-scrollbar { display: none; }
.ds-carousel-slide { width: 100%; }
@media (min-width: 768px) {
  .ds-carousel[data-per-view="2"] .ds-carousel-slide { width: calc((100% - var(--ds-space-lg)) / 2); }
  .ds-carousel[data-per-view="3"] .ds-carousel-slide { width: calc((100% - 2 * var(--ds-space-lg)) / 3); }
}

Reference: Derived from the guidelines: creatives on Black with the #262626 card fill, the 10px canvas corner (8px here), DM Sans figures. shadcn's carousel (a region with slide groups and previous and next) for anatomy and ARIA..