"use client"
import {
createContext,
use,
useEffect,
useState,
type ComponentProps,
type KeyboardEvent,
} from "react"
import { useRender } from "@base-ui/react/use-render"
import * as stylex from "@stylexjs/stylex"
import type { StyleXStyles } from "@stylexjs/stylex"
import { clsx } from "clsx"
import useEmblaCarousel, { type UseEmblaCarouselType } from "embla-carousel-react"
import { CaretDownIcon } from "@phosphor-icons/react/dist/csr/CaretDown"
import { CaretLeftIcon } from "@phosphor-icons/react/dist/csr/CaretLeft"
import { CaretRightIcon } from "@phosphor-icons/react/dist/csr/CaretRight"
import { CaretUpIcon } from "@phosphor-icons/react/dist/csr/CaretUp"
import { Button } from "@/components/ui/button"
import { radius, space } from "@/theme/tokens.stylex"
type CarouselApi = NonNullable<UseEmblaCarouselType[1]>
type CarouselOptions = Parameters<typeof useEmblaCarousel>[0]
type CarouselPlugin = NonNullable<Parameters<typeof useEmblaCarousel>[1]>[number]
type CarouselOrientation = "horizontal" | "vertical"
type CarouselContextValue = {
viewportRef: UseEmblaCarouselType[0]
api: CarouselApi | undefined
orientation: CarouselOrientation
canScrollPrev: boolean
canScrollNext: boolean
scrollPrev: () => void
scrollNext: () => void
}
const CarouselContext = createContext<CarouselContextValue | null>(null)
function useCarousel() {
const context = use(CarouselContext)
if (!context) throw new Error("useCarousel must be used within a <Carousel />")
return context
}
const gap = "var(--arene-carousel-gap)"
const bleed = `min(${space.s1}, var(--arene-carousel-gap))`
const buttonOffset = `calc(-1 * (${space.s8} + ${space.s4}))`
const styles = stylex.create({
root: { position: "relative", "--arene-carousel-gap": space.s4 },
viewport: {
overflow: "hidden",
padding: bleed,
margin: `calc(-1 * ${bleed})`,
},
content: { display: "flex" },
item: { minWidth: 0, flexShrink: 0, flexGrow: 0, flexBasis: "100%" },
button: { position: "absolute", "--arene-button-radius": radius.full },
})
const orientations = stylex.create({
horizontal: { flexDirection: "row", marginInlineStart: `calc(-1 * ${gap})` },
vertical: { flexDirection: "column", marginBlockStart: `calc(-1 * ${gap})` },
})
const itemOrientations = stylex.create({
horizontal: { paddingInlineStart: gap },
vertical: { paddingBlockStart: gap },
})
const buttonPlacements = stylex.create({
horizontalPrevious: {
insetBlockStart: "50%",
insetInlineStart: buttonOffset,
transform: "translateY(-50%)",
},
horizontalNext: {
insetBlockStart: "50%",
insetInlineEnd: buttonOffset,
transform: "translateY(-50%)",
},
verticalPrevious: {
insetBlockStart: buttonOffset,
insetInlineStart: "50%",
transform: "translateX(-50%)",
},
verticalNext: {
insetBlockEnd: buttonOffset,
insetInlineStart: "50%",
transform: "translateX(-50%)",
},
})
const carouselStyles = {
root: styles.root,
viewport: styles.viewport,
content: styles.content,
item: styles.item,
button: styles.button,
orientations,
itemOrientations,
buttonPlacements,
}
const reducedMotion = () => window.matchMedia("(prefers-reduced-motion: reduce)").matches
type Overrides = { xstyle?: StyleXStyles; className?: string }
type CarouselProps = useRender.ComponentProps<"div"> &
Overrides & {
orientation?: CarouselOrientation
opts?: CarouselOptions
plugins?: ReadonlyArray<CarouselPlugin>
setApi?: (api: CarouselApi) => void
}
function Carousel({
orientation = "horizontal",
opts,
plugins,
setApi,
onKeyDownCapture,
render,
ref,
style,
xstyle,
className,
...props
}: CarouselProps) {
const [viewportRef, api] = useEmblaCarousel(
{ ...opts, axis: orientation === "horizontal" ? "x" : "y" },
plugins ? [...plugins] : undefined,
)
const [canScrollPrev, setCanScrollPrev] = useState(false)
const [canScrollNext, setCanScrollNext] = useState(false)
useEffect(() => {
if (!api) return
const update = () => {
setCanScrollPrev(api.canScrollPrev())
setCanScrollNext(api.canScrollNext())
}
update()
api.on("reInit", update).on("select", update)
return () => {
api.off("reInit", update).off("select", update)
}
}, [api])
useEffect(() => {
if (api) setApi?.(api)
}, [api, setApi])
const scrollPrev = () => api?.scrollPrev(reducedMotion())
const scrollNext = () => api?.scrollNext(reducedMotion())
const previousKey = orientation === "horizontal" ? "ArrowLeft" : "ArrowUp"
const nextKey = orientation === "horizontal" ? "ArrowRight" : "ArrowDown"
const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
onKeyDownCapture?.(event)
if (event.defaultPrevented) return
if (event.key === previousKey) {
event.preventDefault()
scrollPrev()
} else if (event.key === nextKey) {
event.preventDefault()
scrollNext()
}
}
const sx = stylex.props(styles.root, xstyle)
const element = useRender({
defaultTagName: "div",
render,
ref,
props: {
role: "region",
"aria-roledescription": "carousel",
"data-slot": "carousel",
"data-orientation": orientation,
...sx,
...props,
onKeyDownCapture: handleKeyDown,
className: clsx(sx.className, className),
style: { ...sx.style, ...style },
},
})
return (
<CarouselContext
value={{
viewportRef,
api,
orientation,
canScrollPrev,
canScrollNext,
scrollPrev,
scrollNext,
}}
>
{element}
</CarouselContext>
)
}
type CarouselContentProps = useRender.ComponentProps<"div"> &
Overrides & {
viewportProps?: useRender.ComponentProps<"div"> & Overrides
}
function CarouselContent({
render,
ref,
style,
xstyle,
className,
viewportProps,
...props
}: CarouselContentProps) {
const { viewportRef, orientation } = useCarousel()
const {
xstyle: viewportXstyle,
className: viewportClassName,
style: viewportStyle,
...viewportRest
} = viewportProps ?? {}
const viewportSx = stylex.props(styles.viewport, viewportXstyle)
const sx = stylex.props(styles.content, orientations[orientation], xstyle)
const content = useRender({
defaultTagName: "div",
render,
ref,
props: {
"data-slot": "carousel-content",
...sx,
...props,
className: clsx(sx.className, className),
style: { ...sx.style, ...style },
},
})
return (
<div
ref={viewportRef}
data-slot="carousel-viewport"
{...viewportSx}
{...viewportRest}
className={clsx(viewportSx.className, viewportClassName)}
style={{ ...viewportSx.style, ...viewportStyle }}
>
{content}
</div>
)
}
function CarouselItem({
render,
ref,
style,
xstyle,
className,
...props
}: useRender.ComponentProps<"div"> & Overrides) {
const { orientation } = useCarousel()
const sx = stylex.props(styles.item, itemOrientations[orientation], xstyle)
return useRender({
defaultTagName: "div",
render,
ref,
props: {
role: "group",
"aria-roledescription": "slide",
"data-slot": "carousel-item",
...sx,
...props,
className: clsx(sx.className, className),
style: { ...sx.style, ...style },
},
})
}
type CarouselButtonProps = Omit<ComponentProps<typeof Button>, "disabled">
function CarouselPrevious({
variant = "outline",
size = "icon-sm",
xstyle,
onClick,
children,
...props
}: CarouselButtonProps) {
const { orientation, canScrollPrev, scrollPrev } = useCarousel()
const Icon = orientation === "horizontal" ? CaretLeftIcon : CaretUpIcon
return (
<Button
data-slot="carousel-previous"
variant={variant}
size={size}
aria-label="Previous slide"
disabled={!canScrollPrev}
xstyle={[styles.button, buttonPlacements[`${orientation}Previous`], xstyle]}
onClick={(event) => {
onClick?.(event)
scrollPrev()
}}
{...props}
>
{children ?? <Icon aria-hidden="true" />}
</Button>
)
}
function CarouselNext({
variant = "outline",
size = "icon-sm",
xstyle,
onClick,
children,
...props
}: CarouselButtonProps) {
const { orientation, canScrollNext, scrollNext } = useCarousel()
const Icon = orientation === "horizontal" ? CaretRightIcon : CaretDownIcon
return (
<Button
data-slot="carousel-next"
variant={variant}
size={size}
aria-label="Next slide"
disabled={!canScrollNext}
xstyle={[styles.button, buttonPlacements[`${orientation}Next`], xstyle]}
onClick={(event) => {
onClick?.(event)
scrollNext()
}}
{...props}
>
{children ?? <Icon aria-hidden="true" />}
</Button>
)
}
export {
Carousel,
CarouselContent,
CarouselItem,
CarouselNext,
CarouselPrevious,
carouselStyles,
useCarousel,
type CarouselApi,
type CarouselOptions,
type CarouselOrientation,
type CarouselPlugin,
}