@carbon/ibm-products
Version:
Carbon for IBM Products
279 lines (277 loc) • 11.5 kB
JavaScript
/**
* Copyright IBM Corp. 2020, 2026
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
const require_runtime = require("../../_virtual/_rolldown/runtime.js");
const require_index = require("../../node_modules/classnames/index.js");
const require_settings = require("../../settings.js");
const require_useIsomorphicEffect = require("../../global/js/hooks/useIsomorphicEffect.js");
const require_devtools = require("../../global/js/utils/devtools.js");
const require_CarouselItem = require("./CarouselItem.js");
let react = require("react");
react = require_runtime.__toESM(react);
let prop_types = require("prop-types");
prop_types = require_runtime.__toESM(prop_types);
let _carbon_react = require("@carbon/react");
//#region src/components/Carousel/Carousel.tsx
/**
* Copyright IBM Corp. 2023, 2023
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
var import_classnames = /* @__PURE__ */ require_runtime.__toESM(require_index.default);
const blockClass = `${require_settings.pkg.prefix}--carousel`;
const componentName = "Carousel";
const defaults = {
disableArrowScroll: false,
onScroll: () => {},
onChangeIsScrollable: () => {}
};
/**
* The Carousel acts as a scaffold for other Onboarding content.
*
* This component is not intended for general use.
*
* Expected scrolling behavior.
* 1. Scroll the maximum number of visible items at a time.
* 2. The left-most item should always be left-aligned in the viewport.
*
* Exception.
* 1. After scrolling to the last (right-most) item,
* if some of its content remains hidden,
* then nudge it to the right until it is right-aligned.
* 2. From the right-aligned position, when scrolling left,
* the left-most item should again be left-aligned.
*/
const Carousel = react.default.forwardRef((props, ref) => {
const { children, className, disableArrowScroll = defaults.disableArrowScroll, fadedEdgeColor, onChangeIsScrollable = defaults.onChangeIsScrollable, onScroll = defaults.onScroll, isScrollMode = false, disableResetOnResize = false, ...rest } = props;
const carouselRef = (0, react.useRef)(null);
const scrollRef = (0, react.useRef)(null);
const leftFadedEdgeRef = (0, react.useRef)(null);
const rightFadedEdgeRef = (0, react.useRef)(null);
const childElementsRef = (0, react.useRef)(Array(react.default.Children.count(children)).fill((0, react.useRef)(null)));
const leftFadedEdgeColor = typeof fadedEdgeColor === "object" ? fadedEdgeColor?.left : fadedEdgeColor;
const rightFadedEdgeColor = typeof fadedEdgeColor === "object" ? fadedEdgeColor?.right : fadedEdgeColor;
const carbonPrefix = (0, _carbon_react.usePrefix)();
const handleOnScroll = (0, react.useCallback)(() => {
if (!scrollRef.current) return;
const clientWidth = scrollRef.current?.clientWidth;
const scrollLeft = parseInt(`${scrollRef.current?.scrollLeft}`, 10);
const scrollWidth = scrollRef.current?.scrollWidth;
const scrollLeftMax = scrollWidth - clientWidth;
const scrollPercent = parseFloat((scrollLeft / scrollLeftMax).toFixed(2)) || 0;
onChangeIsScrollable(scrollWidth > clientWidth);
onScroll(scrollPercent);
}, [onChangeIsScrollable, onScroll]);
const getElementInView = (0, react.useCallback)((containerRect, elementRect) => {
const elementLeftIsRightOfContainerLeft = elementRect.left >= containerRect.left;
const elementRightIsLeftOfContainerRight = elementRect.right <= containerRect.right;
return elementLeftIsRightOfContainerLeft && elementRightIsLeftOfContainerRight;
}, []);
const getElementsInView = (0, react.useCallback)(() => {
const containerRect = scrollRef?.current?.getBoundingClientRect();
return childElementsRef.current.filter((el) => getElementInView(containerRect, el.getBoundingClientRect()));
}, [getElementInView]);
const getContainerAndChildRectData = (0, react.useCallback)(() => {
const containerRect = scrollRef?.current?.getBoundingClientRect();
const elementRectsInView = getElementsInView().map((el) => el.getBoundingClientRect());
return {
containerRect,
elementRectsInView,
visibleWidth: elementRectsInView.reduce((accumulator, currentValue) => accumulator + currentValue.width, 0)
};
}, [getElementsInView]);
const handleScrollNext = (0, react.useCallback)(() => {
if (!scrollRef.current) return;
const { containerRect, visibleWidth } = getContainerAndChildRectData();
const scrollValue = visibleWidth > 0 ? visibleWidth : containerRect?.width;
scrollRef.current.scrollLeft += scrollValue;
}, [getContainerAndChildRectData]);
const handleScrollPrev = (0, react.useCallback)(() => {
if (!scrollRef.current) return;
const { containerRect, elementRectsInView, visibleWidth } = getContainerAndChildRectData();
const scrollValue = visibleWidth > 0 ? visibleWidth - elementRectsInView[0].left : (containerRect?.width ?? 0) + (containerRect?.left ?? 0);
scrollRef.current.scrollLeft -= scrollValue;
}, [getContainerAndChildRectData]);
const handleScrollReset = (0, react.useCallback)(() => {
if (!scrollRef.current) return;
scrollRef.current.scrollLeft = 0;
handleOnScroll();
}, [handleOnScroll]);
const handleScrollToView = (0, react.useCallback)((itemNumber) => {
updateAriaHiddenTabIndex(itemNumber);
childElementsRef.current[itemNumber]?.scrollIntoView();
}, []);
const getFocusableElements = (container) => {
const notQuery = `:not(.${carbonPrefix}--visually-hidden,.${carbonPrefix}--btn--disabled,[aria-hidden="true"],[disabled])`;
const queryButton = `button${notQuery}`;
const queryInput = `input${notQuery}`;
const querySelect = `select${notQuery}`;
const queryTextarea = `textarea${notQuery}`;
const query = `${queryButton},${`[href]${notQuery}`},${`a${notQuery}`},${queryInput},${querySelect},${queryTextarea},${`[tabindex="0"]${notQuery}`}`;
return container?.querySelectorAll(`${query}`) ?? [];
};
const updateAriaHiddenTabIndex = (itemNumber) => {
!isScrollMode && childElementsRef.current?.forEach((item, idx) => {
const isActive = idx === itemNumber;
item?.setAttribute("aria-hidden", String(!isActive));
getFocusableElements(item).forEach((el) => {
el.tabIndex = isActive ? 0 : -1;
});
});
};
(0, react.useEffect)(() => {
setTimeout(() => {
updateAriaHiddenTabIndex(0);
handleOnScroll();
}, 0);
}, []);
(0, react.useEffect)(() => {
const handleWindowResize = () => {
if (!scrollRef.current) return;
if (!disableResetOnResize) {
scrollRef.current.scrollLeft = 0;
handleOnScroll();
}
};
window.addEventListener("resize", handleWindowResize);
return () => window.removeEventListener("resize", handleWindowResize);
}, [handleOnScroll]);
(0, react.useEffect)(() => {
const handleScrollend = () => {
handleOnScroll();
};
const scrollDiv = scrollRef.current;
scrollDiv?.addEventListener("scrollend", handleScrollend);
return () => scrollDiv?.removeEventListener("scrollend", handleScrollend);
}, [handleOnScroll]);
(0, react.useEffect)(() => {
function handleWheel(event) {
if (event.shiftKey) {
event.stopPropagation();
event.preventDefault();
event.cancelBubble = false;
}
}
const scrollDiv = scrollRef.current;
if (scrollDiv) {
scrollDiv.addEventListener("wheel", handleWheel, { passive: false });
return () => {
scrollDiv.removeEventListener("wheel", handleWheel);
};
}
}, []);
(0, react.useEffect)(() => {
function handleKeydown(event) {
const { key } = event;
if ((key === "ArrowLeft" || key === "ArrowRight") && disableArrowScroll) {
event.stopPropagation();
event.preventDefault();
event.cancelBubble = false;
}
}
const carouselDiv = carouselRef.current;
if (carouselDiv) {
carouselDiv.addEventListener("keydown", handleKeydown);
return () => carouselDiv.removeEventListener("keydown", handleKeydown);
}
}, [disableArrowScroll]);
(0, react.useImperativeHandle)(ref, () => ({
scrollNext() {
handleScrollNext();
},
scrollPrev() {
handleScrollPrev();
},
scrollReset() {
handleScrollReset();
},
scrollToView(itemNumber) {
handleScrollToView(itemNumber);
}
}), [
handleScrollNext,
handleScrollPrev,
handleScrollReset,
handleScrollToView
]);
require_useIsomorphicEffect.useIsomorphicEffect(() => {
if (leftFadedEdgeRef?.current && leftFadedEdgeRef.current.style) leftFadedEdgeRef.current.style.background = `linear-gradient(90deg, ${leftFadedEdgeColor}, transparent)`;
}, [leftFadedEdgeRef, leftFadedEdgeColor]);
require_useIsomorphicEffect.useIsomorphicEffect(() => {
if (rightFadedEdgeRef?.current && rightFadedEdgeRef.current.style) rightFadedEdgeRef.current.style.background = `linear-gradient(270deg, ${rightFadedEdgeColor}, transparent)`;
}, [rightFadedEdgeRef, rightFadedEdgeColor]);
return /* @__PURE__ */ react.default.createElement("div", {
...rest,
tabIndex: -1,
className: (0, import_classnames.default)(blockClass, className),
ref: carouselRef,
...require_devtools.getDevtoolsProps(componentName)
}, /* @__PURE__ */ react.default.createElement("div", { className: (0, import_classnames.default)(`${blockClass}__elements-container`) }, /* @__PURE__ */ react.default.createElement("div", {
className: `${blockClass}__elements`,
ref: scrollRef
}, react.default.Children.map(children, (child, index) => {
return /* @__PURE__ */ react.default.createElement(require_CarouselItem.CarouselItem, {
key: index,
ref: (element) => {
childElementsRef.current[index] = element;
}
}, child);
})), leftFadedEdgeColor && /* @__PURE__ */ react.default.createElement("div", {
ref: leftFadedEdgeRef,
className: `${blockClass}__elements-container--scrolled`
}), rightFadedEdgeColor && /* @__PURE__ */ react.default.createElement("div", {
ref: rightFadedEdgeRef,
className: `${blockClass}__elements-container--scroll-max`
})));
});
Carousel.displayName = componentName;
Carousel.propTypes = {
/**
* Provide the contents of the Carousel.
*/
children: prop_types.default.node.isRequired,
/**
* Provide an optional class to be applied to the containing node.
*/
className: prop_types.default.string,
/**
* Disables the ability of the Carousel to scroll
* use a keyboard's left and right arrow keys.
*/
disableArrowScroll: prop_types.default.bool,
/**
* Enables the edges of the component to have faded styling.
*
* Pass a single string (`$color`) to specify the same color for left and right.
*
* Or pass an object (`{ left: $color1, right: $color2 }`) to specify different colors.
*/
/**@ts-ignore*/
fadedEdgeColor: prop_types.default.oneOfType([prop_types.default.string, prop_types.default.shape({
left: prop_types.default.string,
right: prop_types.default.string
})]),
/**
* enable scroll mode when only scroll functionality is required, more than one items will be visible at a time
* when isScrollMode is false, component behaves like a carousal and on item will be active at a time
* and other items will be hidden and inactive.
*/
isScrollMode: prop_types.default.bool,
/**
* An optional callback function that returns `true`
* when the carousel has enough content to be scrollable,
* and `false` when there is not enough content.
*/
onChangeIsScrollable: prop_types.default.func,
/**
* An optional callback function that returns the scroll position as
* a value between 0 and 1.
*/
onScroll: prop_types.default.func
};
//#endregion
exports.Carousel = Carousel;