{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"react-image-carousel-with-scroll-snap-autoplay-dots-thumbnails-and-swipe","type":"registry:block","title":"React Image Carousel with Scroll Snap, Autoplay, Dots, Thumbnails and Swipe","description":"Free React image carousel in Tailwind with no library: CSS scroll snap, swipe, arrows, dots, keyboard keys and autoplay that pauses on hover and focus.","dependencies":["framer-motion"],"files":[{"path":"components/we-inc/react-image-carousel-with-scroll-snap-autoplay-dots-thumbnails-and-swipe.tsx","type":"registry:component","content":"import { useCallback, useEffect, useRef, useState, type KeyboardEvent, type RefObject } from \"react\";\nimport { useReducedMotion } from \"framer-motion\";\n\n/* ---------- Content: edit the slides here ---------- */\n\n\nconst heroSlides = [\n  { src: \"https://images.pexels.com/photos/3067766/pexels-photo-3067766.jpeg?auto=compress&cs=tinysrgb&w=1600\", alt: \"Red sandstone cliffs and a sea stack with waves breaking below\", place: \"Cala Rossa\", line: \"Sea stacks and a cove you reach on foot\", tone: \"#7c3a22\" },\n  { src: \"https://images.pexels.com/photos/33992262/pexels-photo-33992262.jpeg?auto=compress&cs=tinysrgb&w=1600\", alt: \"Tall limestone cliffs dropping into a deep blue sea, seen from above\", place: \"Capo Bianco\", line: \"Two hundred metres of pale rock over open water\", tone: \"#2b4f6e\" },\n  { src: \"https://images.pexels.com/photos/37109411/pexels-photo-37109411.jpeg?auto=compress&cs=tinysrgb&w=1600\", alt: \"Misty alpine lake at sunrise with mountains reflected in still water\", place: \"Lake Hallen\", line: \"Mist lifts off the water by seven\", tone: \"#36505e\" },\n  { src: \"https://images.pexels.com/photos/35972428/pexels-photo-35972428.jpeg?auto=compress&cs=tinysrgb&w=1600\", alt: \"Golden sand dunes under a clear blue sky\", place: \"The Long Dunes\", line: \"Walk the ridge line before the heat\", tone: \"#a8743c\" },\n];\n\nconst cards = [\n  { src: \"https://images.pexels.com/photos/34902344/pexels-photo-34902344.jpeg?auto=compress&cs=tinysrgb&w=900\", alt: \"White ceramic vases and a cylinder on a deep teal cloth\", name: \"Column vase set\", price: \"$148\", tone: \"#1f3b3a\" },\n  { src: \"https://images.pexels.com/photos/5199152/pexels-photo-5199152.jpeg?auto=compress&cs=tinysrgb&w=900\", alt: \"White jug, striped pitcher and a pomegranate on blue linen\", name: \"Striped pitcher\", price: \"$64\", tone: \"#c98e5a\" },\n  { src: \"https://images.pexels.com/photos/40085654/pexels-photo-40085654.jpeg?auto=compress&cs=tinysrgb&w=900\", alt: \"White vases and paper rolls against a rich blue backdrop\", name: \"Bottle vase, tall\", price: \"$92\", tone: \"#1e3657\" },\n  { src: \"https://images.pexels.com/photos/37209161/pexels-photo-37209161.jpeg?auto=compress&cs=tinysrgb&w=900\", alt: \"Wooden lounge chair with a cane seat beside a round white stool\", name: \"Cane lounge chair\", price: \"$740\", tone: \"#8a6f58\" },\n  { src: \"https://images.pexels.com/photos/39418138/pexels-photo-39418138.jpeg?auto=compress&cs=tinysrgb&w=900\", alt: \"Beige linen cushion resting on a woven wicker chair\", name: \"Washed linen cushion\", price: \"$58\", tone: \"#d9c6b3\" },\n  { src: \"https://images.pexels.com/photos/35082703/pexels-photo-35082703.jpeg?auto=compress&cs=tinysrgb&w=900\", alt: \"Clay vases and jugs on rough wooden shelves in black and white\", name: \"Shelf jug trio\", price: \"$116\", tone: \"#5c5c5c\" },\n];\n\nconst rooms = [\n  { src: \"https://images.pexels.com/photos/9890644/pexels-photo-9890644.jpeg?auto=compress&cs=tinysrgb&w=1600\", alt: \"Sunlit timber living room with a fireplace and dark sofas\", label: \"Living room\", tone: \"#6b4325\" },\n  { src: \"https://images.pexels.com/photos/6947280/pexels-photo-6947280.jpeg?auto=compress&cs=tinysrgb&w=1600\", alt: \"Bright room with a grey tufted sofa, blue cushions and a sunburst mirror\", label: \"Sitting room\", tone: \"#9aa7b3\" },\n  { src: \"https://images.pexels.com/photos/1484981/pexels-photo-1484981.jpeg?auto=compress&cs=tinysrgb&w=1600\", alt: \"Daybed with floral cushions and a reading chair by a sunny window\", label: \"Reading corner\", tone: \"#b49a77\" },\n  { src: \"https://images.pexels.com/photos/19516616/pexels-photo-19516616.jpeg?auto=compress&cs=tinysrgb&w=1600\", alt: \"Red brick townhouse front with a trimmed hedge under blue sky\", label: \"Street front\", tone: \"#8c3b2c\" },\n  { src: \"https://images.pexels.com/photos/30580640/pexels-photo-30580640.jpeg?auto=compress&cs=tinysrgb&w=1600\", alt: \"Two matching white modern houses with dark roofs and a lawn\", label: \"Garden side\", tone: \"#7d8a6a\" },\n];\n\n/** Milliseconds each hero slide stays before moving on. Set AUTOPLAY_MS to 0 to switch autoplay off. */\nconst AUTOPLAY_MS = 5000;\n\n/* ---------- Shared carousel logic ---------- */\n\nfunction useCarousel(trackRef: RefObject<HTMLDivElement>, count: number) {\n  const [index, setIndex] = useState(0);\n  const reduce = useReducedMotion();\n\n  useEffect(() => {\n    const track = trackRef.current;\n    if (!track) return;\n    const items = Array.from(track.children) as HTMLElement[];\n    const io = new IntersectionObserver(\n      (entries) => {\n        entries.forEach((e) => {\n          if (e.isIntersecting && e.intersectionRatio >= 0.6) setIndex(items.indexOf(e.target as HTMLElement));\n        });\n      },\n      { root: track, threshold: [0.6] },\n    );\n    items.forEach((el) => io.observe(el));\n    return () => io.disconnect();\n  }, [trackRef, count]);\n\n  const goTo = useCallback(\n    (i: number) => {\n      const track = trackRef.current;\n      if (!track) return;\n      const n = ((i % count) + count) % count;\n      const el = track.children[n] as HTMLElement | undefined;\n      if (!el) return;\n      track.scrollTo({ left: el.offsetLeft - track.offsetLeft, behavior: reduce ? \"auto\" : \"smooth\" });\n      setIndex(n);\n    },\n    [trackRef, count, reduce],\n  );\n\n  const onKeyDown = (e: KeyboardEvent<HTMLElement>) => {\n    if (e.key === \"ArrowRight\") { e.preventDefault(); goTo(index + 1); }\n    else if (e.key === \"ArrowLeft\") { e.preventDefault(); goTo(index - 1); }\n    else if (e.key === \"Home\") { e.preventDefault(); goTo(0); }\n    else if (e.key === \"End\") { e.preventDefault(); goTo(count - 1); }\n  };\n\n  return { index, goTo, onKeyDown, reduce };\n}\n\nfunction Arrow({ dir }: { dir: \"left\" | \"right\" }) {\n  return (\n    <svg width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" fill=\"none\" aria-hidden=\"true\">\n      <path d={dir === \"left\" ? \"M12 4.5 6.5 10 12 15.5\" : \"M8 4.5 13.5 10 8 15.5\"} stroke=\"currentColor\" strokeWidth=\"1.8\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n    </svg>\n  );\n}\n\nconst ring = \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2\";\nconst track = \"flex snap-x snap-mandatory overflow-x-auto overscroll-x-contain [scrollbar-width:none] [&::-webkit-scrollbar]:hidden\";\n\n/* ---------- Variant 1: full-width image slider with autoplay ---------- */\n\nfunction HeroSlider() {\n  const ref = useRef<HTMLDivElement>(null);\n  const { index, goTo, onKeyDown, reduce } = useCarousel(ref, heroSlides.length);\n  const [hovered, setHovered] = useState(false);\n  const [focused, setFocused] = useState(false);\n  const [stopped, setStopped] = useState(false);\n  const playing = AUTOPLAY_MS > 0 && !reduce && !stopped && !hovered && !focused;\n\n  useEffect(() => {\n    if (!playing) return;\n    const t = window.setTimeout(() => goTo(index + 1), AUTOPLAY_MS);\n    return () => window.clearTimeout(t);\n  }, [playing, index, goTo]);\n\n  return (\n    <section\n      aria-roledescription=\"carousel\"\n      aria-label=\"Coastal and mountain walks\"\n      onKeyDown={onKeyDown}\n      onMouseEnter={() => setHovered(true)}\n      onMouseLeave={() => setHovered(false)}\n      onFocus={() => setFocused(true)}\n      onBlur={(e) => { if (!e.currentTarget.contains(e.relatedTarget as Node)) setFocused(false); }}\n      className=\"relative overflow-hidden rounded-2xl bg-stone-900\"\n    >\n      <div ref={ref} className={`${track} aspect-[4/5] sm:aspect-[16/8]`} aria-live={playing ? \"off\" : \"polite\"}>\n        {heroSlides.map((s, i) => (\n          <div\n            key={s.src}\n            role=\"group\"\n            aria-roledescription=\"slide\"\n            aria-label={`${i + 1} of ${heroSlides.length}: ${s.place}`}\n            aria-hidden={i !== index}\n            className=\"relative h-full w-full shrink-0 snap-start\"\n            style={{ backgroundColor: s.tone }}\n          >\n            <img src={s.src} alt={s.alt} loading={i === 0 ? \"eager\" : \"lazy\"} draggable={false} className=\"h-full w-full object-cover\" />\n            <div className=\"pointer-events-none absolute inset-x-0 bottom-0 h-2/3 bg-gradient-to-t from-black/70 via-black/25 to-transparent\" />\n            <div className=\"absolute bottom-16 left-5 right-5 text-white sm:bottom-20 sm:left-10\">\n              <p className=\"text-xs font-medium uppercase tracking-[0.18em] text-white/80\">Walk {String(i + 1).padStart(2, \"0\")}</p>\n              <h3 className=\"mt-2 s2c-display text-3xl font-semibold tracking-tight sm:text-5xl\">{s.place}</h3>\n              <p className=\"mt-2 max-w-md text-sm text-white/85 sm:text-base\">{s.line}</p>\n            </div>\n          </div>\n        ))}\n      </div>\n\n      <div className=\"absolute inset-x-5 bottom-5 flex items-center justify-between gap-3 sm:inset-x-10 sm:bottom-7\">\n        <div className=\"flex items-center gap-1.5\">\n          {heroSlides.map((s, i) => (\n            <button\n              key={s.place}\n              type=\"button\"\n              onClick={() => goTo(i)}\n              aria-label={`Show slide ${i + 1}: ${s.place}`}\n              aria-current={i === index ? \"true\" : undefined}\n              className={`group relative flex h-10 items-center ${ring} focus-visible:ring-white focus-visible:ring-offset-black/40 rounded-full`}\n            >\n              <span className={`relative block h-1 overflow-hidden rounded-full bg-white/45 transition-[width] duration-500 ${i === index ? \"w-10\" : \"w-4 group-hover:bg-white/60\"}`}>\n                {i === index && (\n                  <span\n                    key={`${index}-${playing}`}\n                    className={`absolute inset-y-0 left-0 rounded-full bg-white ${playing ? \"s2c-fill\" : \"w-full\"}`}\n                    style={playing ? { animationDuration: `${AUTOPLAY_MS}ms` } : undefined}\n                  />\n                )}\n              </span>\n            </button>\n          ))}\n        </div>\n        <div className=\"flex items-center gap-2\">\n          {AUTOPLAY_MS > 0 && !reduce && (\n            <button\n              type=\"button\"\n              onClick={() => setStopped((v) => !v)}\n              aria-label={stopped ? \"Start autoplay\" : \"Stop autoplay\"}\n              className={`grid h-10 w-10 place-items-center rounded-full bg-white/15 text-white backdrop-blur-sm transition hover:bg-white/25 ${ring} focus-visible:ring-white focus-visible:ring-offset-black/40`}\n            >\n              {stopped ? (\n                <svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" aria-hidden=\"true\"><path d=\"M5 3.5v9l7-4.5-7-4.5Z\" fill=\"currentColor\" /></svg>\n              ) : (\n                <svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" aria-hidden=\"true\"><path d=\"M5 3.5h2v9H5zM9 3.5h2v9H9z\" fill=\"currentColor\" /></svg>\n              )}\n            </button>\n          )}\n          {([\"left\", \"right\"] as const).map((d) => (\n            <button\n              key={d}\n              type=\"button\"\n              onClick={() => goTo(index + (d === \"left\" ? -1 : 1))}\n              aria-label={d === \"left\" ? \"Previous slide\" : \"Next slide\"}\n              className={`grid h-10 w-10 place-items-center rounded-full bg-white text-stone-900 shadow-sm transition hover:bg-stone-100 active:scale-95 ${ring} focus-visible:ring-white focus-visible:ring-offset-black/40`}\n            >\n              <Arrow dir={d} />\n            </button>\n          ))}\n        </div>\n      </div>\n    </section>\n  );\n}\n\n/* ---------- Variant 2: multi-card row ---------- */\n\nfunction CardRow() {\n  const ref = useRef<HTMLDivElement>(null);\n  const { index, goTo, onKeyDown } = useCarousel(ref, cards.length);\n  const [edges, setEdges] = useState({ start: true, end: false });\n\n  const onScroll = () => {\n    const t = ref.current;\n    if (!t) return;\n    setEdges({ start: t.scrollLeft < 4, end: t.scrollLeft + t.clientWidth > t.scrollWidth - 4 });\n  };\n\n  const step = (dir: 1 | -1) => {\n    const t = ref.current;\n    if (!t) return;\n    t.scrollBy({ left: dir * t.clientWidth * 0.8, behavior: \"smooth\" });\n  };\n\n  return (\n    <section aria-roledescription=\"carousel\" aria-label=\"New in the shop\" onKeyDown={onKeyDown} className=\"min-w-0\">\n      <div className=\"mb-5 flex items-end justify-between gap-4\">\n        <div>\n          <p className=\"text-xs font-semibold uppercase tracking-[0.16em] text-stone-500\">Multi-card row</p>\n          <h3 className=\"mt-1 s2c-display text-2xl font-semibold tracking-tight text-stone-900\">New in the shop</h3>\n        </div>\n        <div className=\"flex gap-2\">\n          {([-1, 1] as const).map((d) => (\n            <button\n              key={d}\n              type=\"button\"\n              onClick={() => step(d)}\n              disabled={d === -1 ? edges.start : edges.end}\n              aria-label={d === -1 ? \"Scroll products left\" : \"Scroll products right\"}\n              className={`grid h-10 w-10 place-items-center rounded-full border border-stone-300 bg-white text-stone-800 transition hover:border-stone-400 hover:bg-stone-50 disabled:cursor-not-allowed disabled:opacity-35 ${ring} focus-visible:ring-stone-900`}\n            >\n              <Arrow dir={d === -1 ? \"left\" : \"right\"} />\n            </button>\n          ))}\n        </div>\n      </div>\n      <div ref={ref} onScroll={onScroll} className={`${track} -mx-1 gap-4 scroll-px-1 px-1 pb-2`}>\n        {cards.map((c, i) => (\n          <a\n            key={c.name}\n            href=\"#\"\n            aria-label={`${c.name}, ${c.price}, product ${i + 1} of ${cards.length}`}\n            onFocus={() => goTo(i)}\n            className={`group w-[72%] shrink-0 snap-start rounded-xl sm:w-[calc((100%-1rem)/2)] ${ring} focus-visible:ring-stone-900`}\n          >\n            <div className=\"aspect-[4/5] overflow-hidden rounded-xl\" style={{ backgroundColor: c.tone }}>\n              <img src={c.src} alt={c.alt} loading=\"lazy\" draggable={false} className=\"h-full w-full object-cover transition-transform duration-700 ease-out group-hover:scale-[1.04] motion-reduce:transition-none motion-reduce:group-hover:scale-100\" />\n            </div>\n            <div className=\"mt-3 flex items-baseline justify-between gap-3 text-sm\">\n              <span className=\"font-medium text-stone-900\">{c.name}</span>\n              <span className=\"tabular-nums text-stone-600\">{c.price}</span>\n            </div>\n          </a>\n        ))}\n      </div>\n      <p className=\"sr-only\" aria-live=\"polite\">Showing product {index + 1} of {cards.length}</p>\n    </section>\n  );\n}\n\n/* ---------- Variant 3: carousel with thumbnails ---------- */\n\nfunction ThumbCarousel() {\n  const ref = useRef<HTMLDivElement>(null);\n  const { index, goTo, onKeyDown } = useCarousel(ref, rooms.length);\n  const tabs = useRef<(HTMLButtonElement | null)[]>([]);\n  // When a thumbnail has focus, keep focus on the one that matches the shown photo.\n  useEffect(() => {\n    const active = document.activeElement;\n    if (active && tabs.current.includes(active as HTMLButtonElement)) tabs.current[index]?.focus();\n  }, [index]);\n\n  return (\n    <section aria-roledescription=\"carousel\" aria-label=\"Listing photos, Alder Street\" onKeyDown={onKeyDown} className=\"rounded-2xl bg-white p-3 ring-1 ring-stone-200 sm:p-4\">\n      <div className=\"relative\">\n        <div ref={ref} className={`${track} aspect-[3/2] rounded-xl`}>\n          {rooms.map((r, i) => (\n            <div key={r.src} role=\"group\" aria-roledescription=\"slide\" aria-label={`${i + 1} of ${rooms.length}: ${r.label}`} aria-hidden={i !== index} className=\"h-full w-full shrink-0 snap-start\" style={{ backgroundColor: r.tone }}>\n              <img src={r.src} alt={r.alt} loading={i === 0 ? \"eager\" : \"lazy\"} draggable={false} className=\"h-full w-full object-cover\" />\n            </div>\n          ))}\n        </div>\n        <span className=\"absolute left-3 top-3 rounded-full bg-stone-900/75 px-2.5 py-1 text-xs font-medium tabular-nums text-white\">\n          {index + 1} / {rooms.length}\n        </span>\n      </div>\n      <div role=\"tablist\" aria-label=\"Choose a photo\" className=\"mt-3 grid grid-cols-5 gap-2\">\n        {rooms.map((r, i) => (\n          <button\n            key={r.label}\n            type=\"button\"\n            role=\"tab\"\n            aria-selected={i === index}\n            aria-label={r.label}\n            tabIndex={i === index ? 0 : -1}\n            ref={(el) => { tabs.current[i] = el; }}\n            onClick={() => goTo(i)}\n            className={`relative aspect-[4/3] overflow-hidden rounded-lg transition ${ring} focus-visible:ring-emerald-700 ${i === index ? \"opacity-100\" : \"opacity-55 hover:opacity-90\"}`}\n            style={{ backgroundColor: r.tone }}\n          >\n            <img src={r.src.replace(\"w=1600\", \"w=320\")} alt=\"\" loading=\"lazy\" draggable={false} className=\"h-full w-full object-cover\" />\n            <span className={`absolute inset-0 rounded-lg ring-2 ring-inset transition ${i === index ? \"ring-emerald-700\" : \"ring-transparent\"}`} />\n          </button>\n        ))}\n      </div>\n      <p className=\"mt-3 text-sm text-stone-600\">\n        <span className=\"font-medium text-stone-900\">{rooms[index].label}</span> &middot; 14 Alder Street, three bedrooms\n      </p>\n    </section>\n  );\n}\n\nexport default function ReactImageCarousel() {\n  return (\n    <div className=\"min-h-[600px] bg-stone-100 px-4 py-10 s2c-body sm:px-8 sm:py-14\">\n      <style>{`\n        @keyframes s2c-fill { from { width: 0% } to { width: 100% } }\n        .s2c-body { font-family: Inter, ui-sans-serif, system-ui, sans-serif; }\n        .s2c-display { font-family: 'Inter Tight', Inter, ui-sans-serif, system-ui, sans-serif; }\n        .s2c-fill { animation-name: s2c-fill; animation-timing-function: linear; animation-fill-mode: forwards; }\n        @media (prefers-reduced-motion: reduce) { .s2c-fill { animation: none; width: 100%; } }\n      `}</style>\n      <div className=\"mx-auto flex max-w-5xl flex-col gap-12\">\n        <HeroSlider />\n        <div className=\"grid gap-12 lg:grid-cols-[1.35fr_1fr] lg:items-start\">\n          <CardRow />\n          <div className=\"min-w-0\">\n            <p className=\"mb-1 text-xs font-semibold uppercase tracking-[0.16em] text-stone-500\">With thumbnails</p>\n            <h3 className=\"mb-5 s2c-display text-2xl font-semibold tracking-tight text-stone-900\">14 Alder Street</h3>\n            <ThumbCarousel />\n          </div>\n        </div>\n      </div>\n    </div>\n  );\n}\n"}]}
