@dnb/eufemia
Version:
DNB Eufemia Design System UI Library
76 lines (75 loc) • 2.47 kB
JavaScript
"use client";
import _extends from "@babel/runtime-corejs3/helpers/esm/extends";
import React from 'react';
import classnames from 'classnames';
import { extendPropsWithContext, validateDOMAttributes } from "../../shared/component-helper.js";
import Context from "../../shared/Context.js";
import { createSpacingClasses } from "../../components/space/SpacingHelper.js";
import { useIsomorphicLayoutEffect as useLayoutEffect } from "../../shared/helpers/useIsomorphicLayoutEffect.js";
const defaultProps = {
children: null
};
function ScrollView(localProps) {
const context = React.useContext(Context);
const props = extendPropsWithContext(localProps, defaultProps, context.ScrollView);
const {
interactive,
children,
className = null,
innerRef,
...attributes
} = props;
const mainParams = {
className: classnames('dnb-scroll-view', createSpacingClasses(props), className),
...attributes
};
const ref = React.useRef();
mainParams.ref = innerRef ? innerRef : ref;
mainParams.tabIndex = useInteractive({
interactive,
children,
ref: mainParams.ref
});
validateDOMAttributes(props, mainParams);
return React.createElement("div", mainParams, children);
}
function useInteractive({
interactive,
children,
ref
}) {
const [isInteractive, setAsInteractive] = React.useState(Boolean(interactive));
useLayoutEffect(() => {
if (interactive === 'auto') {
setAsInteractive(hasScrollbar());
}
}, [interactive, children]);
useLayoutEffect(() => {
if (interactive === 'auto' && typeof ResizeObserver !== 'undefined') {
const observer = new ResizeObserver(() => {
setAsInteractive(hasScrollbar());
});
observer.observe(ref.current);
return () => observer === null || observer === void 0 ? void 0 : observer.disconnect();
}
}, [interactive, ref]);
if (isInteractive) {
return 0;
}
return undefined;
function hasScrollbar() {
if (!ref.current) {
return true;
}
return ref.current.scrollWidth - 1 > ref.current.offsetWidth || ref.current.scrollHeight - 1 > ref.current.offsetHeight;
}
}
const ScrollViewWithRef = React.forwardRef((props, ref) => {
return React.createElement(ScrollView, _extends({}, props, {
innerRef: props.innerRef || ref
}));
});
ScrollView._supportsSpacingProps = true;
ScrollViewWithRef['_supportsSpacingProps'] = true;
export default ScrollViewWithRef;
//# sourceMappingURL=ScrollView.js.map