UNPKG

@navikt/ds-react

Version:

React components from the Norwegian Labour and Welfare Administration.

60 lines 2.5 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useScrollButtons = useScrollButtons; const react_1 = require("react"); const util_1 = require("../../../util"); const owner_1 = require("../../../util/owner"); function useScrollButtons(listRef) { const [displayScroll, setDisplayScroll] = (0, react_1.useState)({ start: false, end: false, }); const updateScrollButtonState = (0, react_1.useMemo)(() => (0, util_1.debounce)(() => { if (!(listRef === null || listRef === void 0 ? void 0 : listRef.current)) return; const { scrollWidth, clientWidth } = listRef.current; const scrollLeft = listRef.current.scrollLeft; // use 1 for the potential rounding error with browser zooms. const showStartScroll = scrollLeft > 1; const showEndScroll = scrollLeft < scrollWidth - clientWidth - 1; setDisplayScroll((oldDisplayScroll) => showStartScroll === oldDisplayScroll.start && showEndScroll === oldDisplayScroll.end ? oldDisplayScroll : { start: showStartScroll, end: showEndScroll }); }), [listRef]); (0, react_1.useEffect)(() => { const handleResize = () => updateScrollButtonState(); const ownerDoc = (0, owner_1.ownerDocument)(listRef.current); ownerDoc.addEventListener("resize", handleResize); let resizeObserver; if (typeof ResizeObserver !== "undefined" && listRef.current) { resizeObserver = new ResizeObserver(handleResize); resizeObserver.observe(listRef.current); } return () => { ownerDoc.removeEventListener("resize", handleResize); resizeObserver === null || resizeObserver === void 0 ? void 0 : resizeObserver.disconnect(); updateScrollButtonState.clear(); }; }, [listRef, updateScrollButtonState]); (0, react_1.useEffect)(() => { updateScrollButtonState(); }); return { update: updateScrollButtonState, start: displayScroll.start, end: displayScroll.end, show: displayScroll.end || displayScroll.start, scrollLeft: () => { if (listRef.current) { listRef.current.scrollLeft -= 100; } }, scrollRight: () => { if (listRef.current) { listRef.current.scrollLeft += 100; } }, }; } //# sourceMappingURL=useScrollButtons.js.map