|
| 1 | +"use client" |
| 2 | + |
| 3 | +import { useEffect, useRef } from "react" |
| 4 | +import { ArrowRight } from "@react-zero-ui/icon-sprite" |
| 5 | + |
| 6 | +type Props = { |
| 7 | + total: number |
| 8 | + desktopVis: number |
| 9 | + autoPlayInterval?: number | undefined |
| 10 | + activeState: boolean |
| 11 | +} |
| 12 | + |
| 13 | +const btn = |
| 14 | + "bg-white/80 border-2 border-gray-300 animate-click absolute z-1 rounded-full p-1.5 backdrop-blur-sm transition-all duration-300 hover:scale-110 translate-y-20 bubble-hover active before:opacity-20 " |
| 15 | + |
| 16 | +export function CarouselButtons({ total, desktopVis, autoPlayInterval, activeState }: Props) { |
| 17 | + // ---------- refs & cached DOM ---------- |
| 18 | + const prevBtnRef = useRef<HTMLButtonElement>(null) |
| 19 | + const rootRef = useRef<HTMLElement | null>(null) |
| 20 | + const trackRef = useRef<HTMLElement | null>(null) |
| 21 | + const itemsRef = useRef<HTMLElement[]>([]) |
| 22 | + const currentActiveElRef = useRef<HTMLElement | null>(null) |
| 23 | + |
| 24 | + // autoplay lifecycle |
| 25 | + const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null) |
| 26 | + const pausedRef = useRef(false) |
| 27 | + |
| 28 | + // IO for offscreen pause |
| 29 | + const ioRef = useRef<IntersectionObserver | null>(null) |
| 30 | + // RO for layout/viewport changes |
| 31 | + |
| 32 | + // ---------- helpers (no DOM queries; only use cached refs) ---------- |
| 33 | + const readState = () => { |
| 34 | + const t = trackRef.current |
| 35 | + if (!t) { |
| 36 | + return { vis: desktopVis, start: 0, active: 1 } |
| 37 | + } |
| 38 | + const cs = getComputedStyle(t) |
| 39 | + const vis = Number(cs.getPropertyValue("--vis")) || desktopVis |
| 40 | + const start = Number(cs.getPropertyValue("--carousel-idx").trim() || "0") || 0 // 0-based |
| 41 | + const active = Number(cs.getPropertyValue("--active").trim() || t.dataset.active || "1") || 1 // 1-based |
| 42 | + return { vis, start, active } |
| 43 | + } |
| 44 | + |
| 45 | + const writeStart = (s: number) => { |
| 46 | + const t = trackRef.current |
| 47 | + if (!t) return |
| 48 | + const { vis } = readState() |
| 49 | + const max = Math.max(0, total - vis) |
| 50 | + const clamped = Math.max(0, Math.min(s, max)) |
| 51 | + // dedup |
| 52 | + const current = Number(getComputedStyle(t).getPropertyValue("--carousel-idx").trim() || "0") || 0 |
| 53 | + if (clamped !== current) t.style.setProperty("--carousel-idx", String(clamped)) |
| 54 | + } |
| 55 | + |
| 56 | + const setActive = (target: number) => { |
| 57 | + const t = trackRef.current |
| 58 | + if (!t) return |
| 59 | + |
| 60 | + // dedup: skip if already active |
| 61 | + const cur = Number(t.dataset.active || "1") |
| 62 | + if (cur === target) return |
| 63 | + |
| 64 | + // toggle DOM data-active using cached nodes |
| 65 | + const prevEl = currentActiveElRef.current || t.querySelector<HTMLElement>('[data-active="true"]') |
| 66 | + if (prevEl) prevEl.setAttribute("data-active", "false") |
| 67 | + |
| 68 | + const idx = target - 1 // data-i is 1-based in your markup |
| 69 | + const nextEl = itemsRef.current[idx] || t.querySelector<HTMLElement>(`[data-i="${target}"]`) |
| 70 | + if (nextEl) { |
| 71 | + nextEl.setAttribute("data-active", "true") |
| 72 | + currentActiveElRef.current = nextEl |
| 73 | + } |
| 74 | + |
| 75 | + // reflect track-level state |
| 76 | + t.dataset.active = String(target) |
| 77 | + t.style.setProperty("--active", String(target)) |
| 78 | + |
| 79 | + // keep active in view using current vis/start snapshot (reads once) |
| 80 | + const { vis, start } = readState() |
| 81 | + const first = start + 1 |
| 82 | + const last = start + vis |
| 83 | + if (target > last) writeStart(target - vis) |
| 84 | + else if (target < first) writeStart(target - 1) |
| 85 | + } |
| 86 | + |
| 87 | + const next = () => { |
| 88 | + if (activeState) { |
| 89 | + // Active state mode: change active state, slide only if needed |
| 90 | + const current = readState().active |
| 91 | + const nextSlide = current >= total ? 1 : current + 1 |
| 92 | + setActive(nextSlide) |
| 93 | + } else { |
| 94 | + // Normal mode: always slide the carousel |
| 95 | + const { start, vis } = readState() |
| 96 | + const maxStart = Math.max(0, total - vis) |
| 97 | + const nextStart = start >= maxStart ? 0 : start + 1 |
| 98 | + writeStart(nextStart) |
| 99 | + } |
| 100 | + } |
| 101 | + const prev = () => { |
| 102 | + if (activeState) { |
| 103 | + // Active state mode: change active state, slide only if needed |
| 104 | + const current = readState().active |
| 105 | + const prevSlide = current <= 1 ? total : current - 1 |
| 106 | + setActive(prevSlide) |
| 107 | + } else { |
| 108 | + // Normal mode: always slide the carousel |
| 109 | + const { start, vis } = readState() |
| 110 | + const maxStart = Math.max(0, total - vis) |
| 111 | + const prevStart = start <= 0 ? maxStart : start - 1 |
| 112 | + writeStart(prevStart) |
| 113 | + } |
| 114 | + } |
| 115 | + |
| 116 | + // ---------- autoplay ---------- |
| 117 | + const startAutoplay = () => { |
| 118 | + if (!autoPlayInterval || pausedRef.current || intervalRef.current) return |
| 119 | + intervalRef.current = setInterval(() => { |
| 120 | + if (!pausedRef.current) next() |
| 121 | + }, autoPlayInterval) |
| 122 | + } |
| 123 | + const stopAutoplay = () => { |
| 124 | + if (intervalRef.current) { |
| 125 | + clearInterval(intervalRef.current) |
| 126 | + intervalRef.current = null |
| 127 | + } |
| 128 | + } |
| 129 | + const resetAutoplay = () => { |
| 130 | + stopAutoplay() |
| 131 | + startAutoplay() |
| 132 | + } |
| 133 | + |
| 134 | + // ---------- mount: cache DOM once ---------- |
| 135 | + useEffect(() => { |
| 136 | + const root = prevBtnRef.current?.closest<HTMLElement>("[data-carousel-root]") || null |
| 137 | + const track = root?.querySelector<HTMLElement>("[data-carousel-track]") || null |
| 138 | + rootRef.current = root |
| 139 | + trackRef.current = track || null |
| 140 | + |
| 141 | + if (track) { |
| 142 | + // cache item nodes once |
| 143 | + itemsRef.current = Array.from(track.querySelectorAll<HTMLElement>("[data-i]")) |
| 144 | + // seed current active |
| 145 | + const activeIdx = Number(track.dataset.active || "1") - 1 |
| 146 | + currentActiveElRef.current = itemsRef.current[activeIdx] || null |
| 147 | + } |
| 148 | + |
| 149 | + // initial clamp (if CSS vis/start mismatch) |
| 150 | + const { vis, start, active } = readState() |
| 151 | + const max = Math.max(0, total - vis) |
| 152 | + if (start > max) writeStart(max) |
| 153 | + setActive(active) // also ensures correct data-active node |
| 154 | + |
| 155 | + return () => { |
| 156 | + itemsRef.current = [] |
| 157 | + currentActiveElRef.current = null |
| 158 | + rootRef.current = null |
| 159 | + trackRef.current = null |
| 160 | + } |
| 161 | + // eslint-disable-next-line react-hooks/exhaustive-deps |
| 162 | + }, [total]) |
| 163 | + |
| 164 | + // ---------- autoplay lifecycle + pause conditions ---------- |
| 165 | + useEffect(() => { |
| 166 | + // respect reduced motion |
| 167 | + const prefersReduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches |
| 168 | + pausedRef.current = pausedRef.current || prefersReduced |
| 169 | + |
| 170 | + // pause when offscreen |
| 171 | + const track = trackRef.current |
| 172 | + if (track && !ioRef.current) { |
| 173 | + ioRef.current = new IntersectionObserver( |
| 174 | + ([e]) => { |
| 175 | + pausedRef.current = !e.isIntersecting |
| 176 | + if (!pausedRef.current) startAutoplay() |
| 177 | + }, |
| 178 | + { root: null, threshold: 0 } |
| 179 | + ) |
| 180 | + ioRef.current.observe(track) |
| 181 | + } |
| 182 | + |
| 183 | + // pause on tab hide/show |
| 184 | + const onVis = () => { |
| 185 | + pausedRef.current = document.visibilityState !== "visible" |
| 186 | + if (!pausedRef.current) startAutoplay() |
| 187 | + } |
| 188 | + document.addEventListener("visibilitychange", onVis, { passive: true }) |
| 189 | + |
| 190 | + // // pause on hover/focus within root |
| 191 | + const r = rootRef.current |
| 192 | + const onEnter = () => { |
| 193 | + pausedRef.current = true |
| 194 | + stopAutoplay() |
| 195 | + } |
| 196 | + const onLeave = () => { |
| 197 | + pausedRef.current = false |
| 198 | + startAutoplay() |
| 199 | + } |
| 200 | + r?.addEventListener("pointerenter", onEnter, { passive: true }) |
| 201 | + r?.addEventListener("pointerleave", onLeave, { passive: true }) |
| 202 | + r?.addEventListener("focusin", onEnter) |
| 203 | + r?.addEventListener("focusout", onLeave) |
| 204 | + |
| 205 | + // kick it off |
| 206 | + startAutoplay() |
| 207 | + |
| 208 | + return () => { |
| 209 | + stopAutoplay() |
| 210 | + document.removeEventListener("visibilitychange", onVis) |
| 211 | + r?.removeEventListener("pointerenter", onEnter) |
| 212 | + r?.removeEventListener("pointerleave", onLeave) |
| 213 | + r?.removeEventListener("focusin", onEnter) |
| 214 | + r?.removeEventListener("focusout", onLeave) |
| 215 | + ioRef.current?.disconnect() |
| 216 | + ioRef.current = null |
| 217 | + } |
| 218 | + // eslint-disable-next-line react-hooks/exhaustive-deps |
| 219 | + }, [autoPlayInterval]) |
| 220 | + |
| 221 | + // ---------- react to layout/viewport changes (vis may change) ---------- |
| 222 | + useEffect(() => { |
| 223 | + const onResize = () => { |
| 224 | + setActive(1) |
| 225 | + } |
| 226 | + const mediaQuery = window.matchMedia("(min-width: 576px) and (max-width: 1024px)") |
| 227 | + mediaQuery.addEventListener("change", onResize) |
| 228 | + return () => mediaQuery.removeEventListener("change", onResize) |
| 229 | + }, [total]) |
| 230 | + |
| 231 | + return ( |
| 232 | + <> |
| 233 | + <button |
| 234 | + ref={prevBtnRef} |
| 235 | + type="button" |
| 236 | + onClick={() => { |
| 237 | + prev() |
| 238 | + resetAutoplay() |
| 239 | + }} |
| 240 | + aria-label="Previous" |
| 241 | + className={btn + " bottom-8 left-4"} |
| 242 | + > |
| 243 | + <ArrowRight strokeWidth={2.5} size={24} className="rotate-180" /> |
| 244 | + </button> |
| 245 | + <button |
| 246 | + type="button" |
| 247 | + onClick={() => { |
| 248 | + next() |
| 249 | + resetAutoplay() |
| 250 | + }} |
| 251 | + aria-label="Next" |
| 252 | + className={btn + " right-4 bottom-8"} |
| 253 | + > |
| 254 | + <ArrowRight strokeWidth={2.5} size={24} /> |
| 255 | + </button> |
| 256 | + </> |
| 257 | + ) |
| 258 | +} |
0 commit comments