Skip to content

The Open Standard for Generative UI

Refactor carousel (#199)

subhamab8daadb2cfa
diff --git a/js/packages/react-ui/src/components/Carousel/Carousel.tsx b/js/packages/react-ui/src/components/Carousel/Carousel.tsx
index 9b1daf6e2..e0418e417 100644
--- a/js/packages/react-ui/src/components/Carousel/Carousel.tsx
+++ b/js/packages/react-ui/src/components/Carousel/Carousel.tsx
@@ -1,5 +1,15 @@
import clsx from "clsx";
-import { createContext, forwardRef, useContext, useEffect, useRef, useState } from "react";
+import {
+ createContext,
+ forwardRef,
+ useCallback,
+ useContext,
+ useEffect,
+ useImperativeHandle,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
import { IconButton } from "../IconButton";
interface CarouselContextType {
@@ -9,6 +19,8 @@ interface CarouselContextType {
noSnap?: boolean;
showButtons?: boolean;
variant?: "card" | "sunk";
+ isPrevVisible: boolean;
+ isNextVisible: boolean;
}
const CarouselContext = createContext<CarouselContextType | null>(null);
@@ -24,9 +36,16 @@ export interface CarouselProps extends React.HTMLAttributes<HTMLDivElement> {
noSnap?: boolean;
showButtons?: boolean;
variant?: "card" | "sunk";
+ onScrollLeftEnabled?: (enabled: boolean) => void;
+ onScrollRightEnabled?: (enabled: boolean) => void;
}
-export const Carousel = forwardRef<HTMLDivElement, CarouselProps>(
+export interface CarouselRef {
+ scroll: (direction: "left" | "right") => void;
+ scrollDivRef: React.RefObject<HTMLDivElement | null>;
+}
+
+export const Carousel = forwardRef<CarouselRef, CarouselProps>(
(
{
itemsToScroll = 1,
@@ -35,53 +54,127 @@ export const Carousel = forwardRef<HTMLDivElement, CarouselProps>(
variant = "card",
className,
children,
+ onScrollLeftEnabled,
+ onScrollRightEnabled,
...props
},
ref,
) => {
const scrollDivRef = useRef<HTMLDivElement>(null);
+ const [isPrevVisible, setIsPrevVisible] = useState(false);
+ const [isNextVisible, setIsNextVisible] = useState(false);
- const scroll = (direction: "left" | "right") => {
- if (scrollDivRef.current) {
- const container = scrollDivRef.current;
- let children = Array.from(container.children);
+ const scroll = useCallback((direction: "left" | "right") => {
+ if (!scrollDivRef.current) {
+ return;
+ }
- const spacingEl = children.splice(0, 1)[0] as HTMLElement;
+ const container = scrollDivRef.current;
+ const items = noSnap
+ ? Array.from(container.children[0]?.children ?? [])
+ : Array.from(container.children);
+
+ if (items.length === 0) {
+ return;
+ }
- if (noSnap) {
- children = Array.from(children[0]!.children);
- }
+ const containerRect = container.getBoundingClientRect();
+ const visibleIndex = items.findIndex((child) => {
+ const rect = child.getBoundingClientRect();
+ return rect.left >= containerRect.left;
+ });
- const visibleIndex = children.findIndex((child) => {
- const rect = child.getBoundingClientRect();
- return rect.left >= container.getBoundingClientRect().left;
- });
+ let currentIndex = visibleIndex;
+ if (visibleIndex === -1) {
+ // Scrolled to the far right, so the last item is the current one
+ currentIndex = items.length - 1;
+ }
+
+ const targetIndex =
+ direction === "left"
+ ? Math.max(0, currentIndex - itemsToScroll)
+ : Math.min(items.length - 1, currentIndex + itemsToScroll);
+
+ const targetElement = items[targetIndex] as HTMLElement;
- const targetIndex =
- direction === "left"
- ? Math.max(0, visibleIndex - itemsToScroll)
- : Math.min(children.length - 1, visibleIndex + itemsToScroll);
-
- const targetElement = (
- targetIndex === 0 ? spacingEl : children[targetIndex]
- ) as HTMLElement;
-
- if (targetElement) {
- container.scrollTo({
- left: targetElement.offsetLeft,
- behavior: "smooth",
- });
- }
+ if (targetElement) {
+ container.scrollTo({
+ left: targetElement.offsetLeft,
+ behavior: "smooth",
+ });
}
- };
+ }, []);
+
+ useEffect(() => {
+ if (!scrollDivRef.current) return;
+
+ const container = scrollDivRef.current;
+ const handleScroll = () => {
+ const canScrollLeft = container.scrollLeft > 0;
+ const canScrollRight =
+ Math.ceil(container.scrollLeft) + container.offsetWidth < container.scrollWidth;
+ setIsPrevVisible(canScrollLeft);
+ setIsNextVisible(canScrollRight);
+ };
+
+ handleScroll();
+
+ const resizeObserver = new ResizeObserver(handleScroll);
+ resizeObserver.observe(container);
+ const mutationObserver = new MutationObserver(handleScroll);
+ mutationObserver.observe(container, { childList: true, subtree: true });
+
+ container.addEventListener("scroll", handleScroll);
+
+ return () => {
+ container.removeEventListener("scroll", handleScroll);
+ resizeObserver.disconnect();
+ mutationObserver.disconnect();
+ };
+ }, [scrollDivRef]);
+
+ useEffect(() => {
+ onScrollLeftEnabled?.(isPrevVisible);
+ }, [isPrevVisible, onScrollLeftEnabled]);
+
+ useEffect(() => {
+ onScrollRightEnabled?.(isNextVisible);
+ }, [isNextVisible, onScrollRightEnabled]);
+
+ useImperativeHandle(ref, () => {
+ return {
+ scroll,
+ scrollDivRef,
+ };
+ }, []);
+
+ const contextValue = useMemo(
+ () => ({
+ scrollDivRef,
+ scroll,
+ itemsToScroll,
+ noSnap,
+ showButtons,
+ variant,
+ isPrevVisible,
+ isNextVisible,
+ }),
+ [
+ scrollDivRef,
+ scroll,
+ itemsToScroll,
+ noSnap,
+ showButtons,
+ variant,
+ isPrevVisible,
+ isNextVisible,
+ ],
+ );
return (
- <CarouselContext.Provider
- value={{ scrollDivRef, scroll, itemsToScroll, noSnap, showButtons, variant }}
- >
+ <CarouselContext.Provider value={contextValue}>
<div
className={clsx("crayon-carousel", `crayon-carousel--${variant}`, className)}
- ref={ref}
{...props}
>
{children}
@@ -93,7 +186,7 @@ export const Carousel = forwardRef<HTMLDivElement, CarouselProps>(
export const CarouselContent = forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, children, ...props }, _ref) => {
- const { scrollDivRef, noSnap } = useCarousel();
+ const { scrollDivRef, noSnap, isPrevVisible, isNextVisible } = useCarousel();
const content = noSnap ? (
<div className="crayon-carousel-content-wrapper">{children}</div>
@@ -102,7 +195,18 @@ export const CarouselContent = forwardRef<HTMLDivElement, React.HTMLAttributes<H
);
return (
- <div ref={scrollDivRef} className={clsx("crayon-carousel-content", className)} {...props}>
+ <div
+ ref={scrollDivRef}
+ className={clsx(
+ "crayon-carousel-content",
+ {
+ "crayon-carousel-content--mask-left": isPrevVisible,
+ "crayon-carousel-content--mask-right": isNextVisible,
+ },
+ className,
+ )}
+ {...props}
+ >
{content}
</div>
);
@@ -121,33 +225,9 @@ export const CarouselPrevious = forwardRef<
HTMLButtonElement,
React.ComponentProps<typeof IconButton>
>(({ className, style, ...props }, ref) => {
- const { scrollDivRef, scroll, showButtons } = useCarousel();
- const [show, setShow] = useState(true);
-
- useEffect(() => {
- if (!scrollDivRef.current) return;
+ const { scroll, showButtons, isPrevVisible } = useCarousel();
- const container = scrollDivRef.current;
- const shouldShow = () => container.scrollLeft > 0;
-
- setShow(shouldShow());
-
- const handleScroll = () => {
- setShow(shouldShow());
- };
-
- const resizeObserver = new ResizeObserver(handleScroll);
- resizeObserver.observe(container);
-
- container.addEventListener("scroll", handleScroll);
-
- return () => {
- container.removeEventListener("scroll", handleScroll);
- resizeObserver.disconnect();
- };
- }, [scrollDivRef]);
-
- if (!show || !showButtons) return null;
+ if (!isPrevVisible || !showButtons) return null;
return (
<div className={clsx("crayon-carousel-button crayon-carousel-button-left", className)}>
@@ -166,33 +246,9 @@ export const CarouselPrevious = forwardRef<
export const CarouselNext = forwardRef<HTMLButtonElement, React.ComponentProps<typeof IconButton>>(
({ className, style, ...props }, ref) => {
- const { scrollDivRef, scroll, showButtons } = useCarousel();
- const [show, setShow] = useState(true);
-
- useEffect(() => {
- if (!scrollDivRef.current) return;
-
- const container = scrollDivRef.current;
- const shouldShow = () => container.scrollLeft + container.offsetWidth < container.scrollWidth;
-
- setShow(shouldShow());
-
- const handleScroll = () => {
- setShow(shouldShow());
- };
-
- const resizeObserver = new ResizeObserver(handleScroll);
- resizeObserver.observe(container);
-
- container.addEventListener("scroll", handleScroll);
-
- return () => {
- container.removeEventListener("scroll", handleScroll);
- resizeObserver.disconnect();
- };
- }, [scrollDivRef]);
+ const { scroll, showButtons, isNextVisible } = useCarousel();
- if (!show || !showButtons) return null;
+ if (!isNextVisible || !showButtons) return null;
return (
<div className={clsx("crayon-carousel-button crayon-carousel-button-right", className)}>
diff --git a/js/packages/react-ui/src/components/Carousel/carousel.scss b/js/packages/react-ui/src/components/Carousel/carousel.scss
index e55d0ae47..f8c6de423 100644
--- a/js/packages/react-ui/src/components/Carousel/carousel.scss
+++ b/js/packages/react-ui/src/components/Carousel/carousel.scss
@@ -14,6 +14,33 @@
-ms-overflow-x: hidden;
scrollbar-width: none;
+ &.crayon-carousel-content--mask-left.crayon-carousel-content--mask-right {
+ mask-image: linear-gradient(
+ to right,
+ transparent,
+ black 40px,
+ black calc(100% - 40px),
+ transparent
+ );
+ -webkit-mask-image: linear-gradient(
+ to right,
+ transparent,
+ black 40px,
+ black calc(100% - 40px),
+ transparent
+ );
+ }
+
+ &.crayon-carousel-content--mask-left:not(.crayon-carousel-content--mask-right) {
+ mask-image: linear-gradient(to right, transparent, black 40px, black);
+ -webkit-mask-image: linear-gradient(to right, transparent, black 40px, black);
+ }
+
+ &.crayon-carousel-content--mask-right:not(.crayon-carousel-content--mask-left) {
+ mask-image: linear-gradient(to left, transparent, black 40px, black);
+ -webkit-mask-image: linear-gradient(to left, transparent, black 40px, black);
+ }
+
&-wrapper {
display: flex;
gap: cssUtils.$spacing-m;
@@ -61,6 +88,7 @@
right: -12px;
}
}
+
@media (max-width: 400px) {
.crayon-carousel-item {
width: 248px;
diff --git a/js/packages/react-ui/src/components/Carousel/stories/carousel.stories.tsx b/js/packages/react-ui/src/components/Carousel/stories/carousel.stories.tsx
index 38e922601..6a6164018 100644
--- a/js/packages/react-ui/src/components/Carousel/stories/carousel.stories.tsx
+++ b/js/packages/react-ui/src/components/Carousel/stories/carousel.stories.tsx
@@ -13,6 +13,7 @@ import {
Trophy,
UtensilsCrossed,
} from "lucide-react";
+import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { Card } from "../../Card";
import { CardHeader } from "../../CardHeader";
import { IconButton } from "../../IconButton";
@@ -23,6 +24,7 @@ import {
CarouselItem,
CarouselNext,
CarouselPrevious,
+ CarouselRef,
} from "../Carousel";
import "../carousel.scss";
@@ -40,7 +42,15 @@ const meta: Meta<typeof Carousel> = {
},
decorators: [
(Story) => (
- <div style={{ width: "100%", maxWidth: "28rem" }}>
+ <div
+ style={{
+ width: "100%",
+ height: "100%",
+ display: "flex",
+ justifyContent: "center",
+ alignItems: "center",
+ }}
+ >
<Story />
</div>
),
@@ -259,7 +269,118 @@ export const SunkVariant: Story = {
<Carousel
itemsToScroll={itemsToScroll}
noSnap={noSnap}
- showButtons={showButtons}
+ showButtons={false}
+ variant={variant}
+ >
+ <CarouselContent>
+ {repeatedItems.map((item) => (
+ <CarouselItem key={item.id}>
+ <CardHeader
+ title={item.title}
+ subtitle={item.subtitle}
+ actions={[<IconButton variant="tertiary" size="small" icon={item.icon} />]}
+ />
+ <Image src={item.imageUrl ?? ""} alt={`${item.title} image`} scale="fill" />
+ </CarouselItem>
+ ))}
+ </CarouselContent>
+ <CarouselPrevious icon={<ChevronLeft />} />
+ <CarouselNext icon={<ChevronRight />} />
+ </Carousel>
+ </Card>
+ );
+ },
+};
+
+export const WithRef: Story = {
+ args: {
+ ...Default.args,
+ variant: "card",
+ },
+ parameters: {
+ docs: {
+ description: {
+ story: "Carousel with the `sunk` variant.",
+ },
+ },
+ },
+ render: (args) => {
+ const { itemsToScroll, noSnap, variant } = args;
+ const repeatedItems = Array.from({ length: items.length }, (_, index) => ({
+ ...items[index % items.length],
+ id: `item-${index + 1}`,
+ }));
+
+ const ref = useRef<CarouselRef | null>(null);
+ const [canScroll, setCanScroll] = useState({ left: false, right: false });
+ const [scrollContainer, setScrollContainer] = useState<HTMLDivElement | null>(null);
+
+ useLayoutEffect(() => {
+ if (ref.current?.scrollDivRef.current) {
+ setScrollContainer(ref.current.scrollDivRef.current);
+ }
+ });
+
+ useEffect(() => {
+ if (!scrollContainer) {
+ return;
+ }
+ const handleScroll = () => {
+ const canScrollLeft = scrollContainer.scrollLeft > 0;
+ const canScrollRight =
+ Math.ceil(scrollContainer.scrollLeft) + scrollContainer.offsetWidth <
+ scrollContainer.scrollWidth;
+ setCanScroll({ left: canScrollLeft, right: canScrollRight });
+ };
+
+ handleScroll();
+
+ scrollContainer.addEventListener("scroll", handleScroll);
+ const resizeObserver = new ResizeObserver(handleScroll);
+ resizeObserver.observe(scrollContainer);
+ const mutationObserver = new MutationObserver(handleScroll);
+ mutationObserver.observe(scrollContainer, { childList: true, subtree: true });
+
+ return () => {
+ scrollContainer.removeEventListener("scroll", handleScroll);
+ resizeObserver.disconnect();
+ mutationObserver.disconnect();
+ };
+ }, [scrollContainer]);
+
+ return (
+ <Card style={{ width: "700px", display: "flex", flexDirection: "column", gap: "10px" }}>
+ <div
+ style={{
+ display: "flex",
+ flexDirection: "row",
+ gap: "10px",
+ justifyContent: "space-between",
+ }}
+ >
+ <span>Carousel Header</span>
+ <div style={{ display: "flex", flexDirection: "row", gap: "10px" }}>
+ <IconButton
+ variant="tertiary"
+ size="small"
+ onClick={() => ref.current?.scroll("left")}
+ disabled={!canScroll.left}
+ icon={<ChevronLeft />}
+ />
+ <IconButton
+ variant="tertiary"
+ size="small"
+ onClick={() => ref.current?.scroll("right")}
+ disabled={!canScroll.right}
+ icon={<ChevronRight />}
+ />
+ </div>
+ </div>
+ <Carousel
+ ref={ref}
+ itemsToScroll={itemsToScroll}
+ noSnap={noSnap}
+ showButtons={false}
variant={variant}
>
<CarouselContent>