UNPKG

dbl-components

Version:

Framework based on bootstrap 5

70 lines 19.5 kB
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _react=_interopRequireWildcard(require("react"));var _propTypes=_interopRequireDefault(require("prop-types"));var _dblUtils=require("dbl-utils");var _propTypes2=require("../prop-types");var _useEventHandler=_interopRequireDefault(require("../hooks/use-event-handler"));var _container=_interopRequireDefault(require("./container"));function _interopRequireDefault(e){return e&&e.__esModule?e:{"default":e}}function _interopRequireWildcard(e,t){if("function"==typeof WeakMap)var r=new WeakMap,n=new WeakMap;return(_interopRequireWildcard=function _interopRequireWildcard(e,t){if(!t&&e&&e.__esModule)return e;var o,i,f={__proto__:null,"default":e};if(null===e||"object"!=_typeof(e)&&"function"!=typeof e)return f;if(o=t?n:r){if(o.has(e))return o.get(e);o.set(e,f)}for(var _t in e)"default"!==_t&&{}.hasOwnProperty.call(e,_t)&&((i=(o=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,_t))&&(i.get||i.set)?o(f,_t,i):f[_t]=e[_t]);return f})(e,t)}function _typeof(o){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o},_typeof(o)}function _classCallCheck(a,n){if(!(a instanceof n))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,r){for(var t=0;t<r.length;t++){var o=r[t];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,_toPropertyKey(o.key),o)}}function _createClass(e,r,t){return r&&_defineProperties(e.prototype,r),t&&_defineProperties(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function _callSuper(t,o,e){return o=_getPrototypeOf(o),_possibleConstructorReturn(t,_isNativeReflectConstruct()?Reflect.construct(o,e||[],_getPrototypeOf(t).constructor):o.apply(t,e))}function _possibleConstructorReturn(t,e){if(e&&("object"==_typeof(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return _assertThisInitialized(t)}function _assertThisInitialized(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function _isNativeReflectConstruct(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(_isNativeReflectConstruct=function _isNativeReflectConstruct(){return!!t})()}function _getPrototypeOf(t){return _getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},_getPrototypeOf(t)}function _inherits(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&_setPrototypeOf(t,e)}function _setPrototypeOf(t,e){return _setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},_setPrototypeOf(t,e)}function ownKeys(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);r&&(o=o.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),t.push.apply(t,o)}return t}function _objectSpread(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?ownKeys(Object(t),!0).forEach(function(r){_defineProperty(e,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):ownKeys(Object(t)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r))})}return e}function _slicedToArray(r,e){return _arrayWithHoles(r)||_iterableToArrayLimit(r,e)||_unsupportedIterableToArray(r,e)||_nonIterableRest()}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0}}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n}function _iterableToArrayLimit(r,l){var t=null==r?null:"undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(null!=t){var e,n,i,u,a=[],f=!0,o=!1;try{if(i=(t=t.call(r)).next,0===l){if(Object(t)!==t)return;f=!1}else for(;!(f=(e=i.call(t)).done)&&(a.push(e.value),a.length!==l);f=!0);}catch(r){o=!0,n=r}finally{try{if(!f&&null!=t["return"]&&(u=t["return"](),Object(u)!==u))return}finally{if(o)throw n}}return a}}function _arrayWithHoles(r){if(Array.isArray(r))return r}function _defineProperty(e,r,t){return(r=_toPropertyKey(r))in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}function _toPropertyKey(t){var i=_toPrimitive(t,"string");return"symbol"==_typeof(i)?i:i+""}function _toPrimitive(t,r){if("object"!=_typeof(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,r||"default");if("object"!=_typeof(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(t)}var timeoutDispatchPosition;/** * Custom horizontal scroll component with a custom scrollbar. * @param {Object} props - Component properties. * @param {string} props.breakpoint - The breakpoint value for responsive design. * @param {string} props.orientation - The orientation of the scroll (horizontal/vertical). * @param {number} props.width - The width of the scroll container. * @param {number} props.height - The height of the scroll container. * @param {Array<string>} props.scrollTrackClasses - Array of CSS classes for the scroll track. * @param {Array<string>} props.scrollBarClasses - Array of CSS classes for the scroll bar. * @param {Object} props.scrollTrackStyle - Inline styles for the scroll track. * @param {Object} props.scrollBarStyle - Inline styles for the scroll bar. * @param {React.ReactNode} props.children - Child elements to be rendered inside the scroll container. * @returns {React.Component} - The ScrollX component with a custom scrollbar. */function ScrollXNode(_ref){var name=_ref.name,_ref$scrollTrackClass=_ref.scrollTrackClasses,scrollTrackClasses=_ref$scrollTrackClass===void 0?[]:_ref$scrollTrackClass,_ref$scrollBarClasses=_ref.scrollBarClasses,scrollBarClasses=_ref$scrollBarClasses===void 0?[]:_ref$scrollBarClasses,_ref$scrollTrackStyle=_ref.scrollTrackStyle,scrollTrackStyle=_ref$scrollTrackStyle===void 0?{}:_ref$scrollTrackStyle,_ref$scrollBarStyle=_ref.scrollBarStyle,scrollBarStyle=_ref$scrollBarStyle===void 0?{}:_ref$scrollBarStyle,breakpoint=_ref.breakpoint,orientation=_ref.orientation,width=_ref.width,height=_ref.height,children=_ref.children;var scrollBarPosition=(0,_react.useCallback)(function(percentagePosition){if(!(scrollTrackRef.current&&scrollBarRef.current))return;var scrollBarrPercentage=percentagePosition*(scrollTrackRef.current.clientWidth-scrollBarRef.current.clientWidth);setScrollBarLeft(scrollBarrPercentage/scrollTrackRef.current.clientWidth)});var containerPosition=(0,_react.useCallback)(function(step){var newTranslate=Math.min(Math.max(initialTranslate.current+step,-diffContentWidth),0);initialTranslate.current=newTranslate;var newPercentage=Math.abs(newTranslate/diffContentWidth);setPercentage(newPercentage);setTranslate(newTranslate);scrollBarPosition(newPercentage);clearTimeout(timeoutDispatchPosition);timeoutDispatchPosition=setTimeout(function(){_dblUtils.eventHandler.dispatch(name,_defineProperty({},name,{position:Math.abs(newTranslate),percentage:newPercentage,size:diffContentWidth}))},660)});var updateScroll=(0,_react.useCallback)(function(update){if(update.position!==undefined){initialTranslate.current=0;containerPosition(update.position)}if(update.percentage!==undefined){initialTranslate.current=0;var position=-update.percentage*diffContentWidth;containerPosition(position)}if(update.resize){var container=containerRef.current;var newContentWidth=container.scrollWidth;var newDiffContentWidth=container.scrollWidth-container.clientWidth;setContentWidth(newContentWidth);setDiffContentWidth(newDiffContentWidth);initialTranslate.current=0;var _position=-percentage*newDiffContentWidth;containerPosition(_position)}});/** * Handles the scroll event on the container. */var handleScroll=(0,_react.useCallback)(function(){if(!scrollTrackRef.current)return;var container=containerRef.current;var scrollLeft=container.scrollLeft;var scrollBarPosition=scrollLeft/diffContentWidth*(scrollTrackRef.current.clientWidth-scrollBarRef.current.clientWidth);setScrollBarLeft(scrollBarPosition/scrollTrackRef.current.clientWidth)});/** * Handles the wheel event for scrolling. * @param {Event} event - The wheel event. */var handleWheel=(0,_react.useCallback)(function(event){var speed=event.deltaX;if(speed===0&&event.shiftKey){event.preventDefault();speed=-event.deltaY/Math.abs(event.deltaY)}speed*=10;var container=containerRef.current;if(!container)return;var containerRatio=container.scrollWidth/container.clientWidth;containerPosition(speed*containerRatio)});/** * Handles the start of a drag event. * @param {Event} e - The drag event. */var handleDragStart=(0,_react.useCallback)(function(e){e.preventDefault();e.stopPropagation();var initialPosValue=e.clientX||(e.touches?e.touches[0].clientX:0);containerRef.current.removeEventListener("scroll",handleScroll);document.addEventListener("mousemove",handleDrag);document.addEventListener("touchmove",handleDrag);document.addEventListener("mouseup",handleDragEnd);document.addEventListener("touchend",handleDragEnd);initialMouseX.current=initialPosValue;initialScrollLeft.current=scrollBarLeft});/** * Handles the scrollBar drag event. * @param {Event} e - The drag event. */var handleDrag=(0,_react.useCallback)(function(e){e.preventDefault();e.stopPropagation();var posValue=e.clientX||(e.touches?e.touches[0].clientX:0);var initialValue=initialMouseX.current;if(!containerRef.current||posValue===0)return;if(Math.abs(posValue-initialValue)<40)return;var barPercent=scrollBarRef.current.clientWidth/scrollTrackRef.current.clientWidth;var deltaX=(posValue-initialValue)*barPercent;containerPosition(-deltaX)});/** * Handles the end of a drag event. * @param {Event} e - The drag event. */var handleDragEnd=(0,_react.useCallback)(function(e){e.preventDefault();e.stopPropagation();containerRef.current.addEventListener("scroll",handleScroll);document.removeEventListener("mousemove",handleDrag);document.removeEventListener("touchmove",handleDrag);document.removeEventListener("mouseup",handleDragEnd);document.removeEventListener("touchend",handleDragEnd);initialMouseX.current=0;initialScrollLeft.current=0});/** * Handles the touch start event for touch devices. * @param {Event} e - The touch event. */var handleTouchStart=(0,_react.useCallback)(function(e){initialTouchX.current=e.touches[0].clientX;setIsTouching(true)});/** * Handles the touch move event for touch devices. * @param {Event} e - The touch event. */var handleTouchMove=(0,_react.useCallback)(function(event){var vector=event.touches[0].clientX-initialTouchX.current;initialTouchX.current=event.touches[0].clientX;containerPosition(vector)});/** * Handles the touch end event for touch devices. * @param {Event} e - The touch event. */var handleTouchEnd=(0,_react.useCallback)(function(e){setIsTouching(false)});var containerRef=(0,_react.useRef)(null);// Reference to the scroll container. var scrollTrackRef=(0,_react.useRef)(null);// Reference to the scroll track. var scrollBarRef=(0,_react.useRef)(null);// Reference to the scroll bar. var initialMouseX=(0,_react.useRef)(null);// Initial mouse X position for drag events. var initialScrollLeft=(0,_react.useRef)(null);// Left position of the scroll bar. var initialTouchX=(0,_react.useRef)(null);// Initial touch X position for touch events. var initialTranslate=(0,_react.useRef)(0);// Initial transform. // State variables. var _useState=(0,_react.useState)(false),_useState2=_slicedToArray(_useState,2),isTouchDevice=_useState2[0],setIsTouchDevice=_useState2[1];// Flag for touch device detection. var _useState3=(0,_react.useState)(false),_useState4=_slicedToArray(_useState3,2),isTouching=_useState4[0],setIsTouching=_useState4[1];// Flag for touch device detection. var _useState5=(0,_react.useState)(0),_useState6=_slicedToArray(_useState5,2),scrollBarLeft=_useState6[0],setScrollBarLeft=_useState6[1];// Left position of the scroll bar. var _useState7=(0,_react.useState)(0),_useState8=_slicedToArray(_useState7,2),wScrollBar=_useState8[0],setWScrollBar=_useState8[1];// Width of the scroll bar. var _useState9=(0,_react.useState)(false),_useState0=_slicedToArray(_useState9,2),showBar=_useState0[0],setShowBar=_useState0[1];// Flag to show or hide the scroll bar. var _useState1=(0,_react.useState)(0),_useState10=_slicedToArray(_useState1,2),contentWidth=_useState10[0],setContentWidth=_useState10[1];// Width of the scrollable content. var _useState11=(0,_react.useState)(0),_useState12=_slicedToArray(_useState11,2),diffContentWidth=_useState12[0],setDiffContentWidth=_useState12[1];// difference Width of the scrollable content. var _useState13=(0,_react.useState)(initialTranslate.current),_useState14=_slicedToArray(_useState13,2),translate=_useState14[0],setTranslate=_useState14[1];// Transform value for the scroll bar. var _useState15=(0,_react.useState)(initialTranslate.current),_useState16=_slicedToArray(_useState15,2),percentage=_useState16[0],setPercentage=_useState16[1];// percentage value for the scroll bar. // Custom hook to handle events (0,_useEventHandler["default"])([["update.".concat(name),updateScroll]],[name,ScrollContainer.jsClass].join("-"));// Effect to detect if the device supports touch events. (0,_react.useLayoutEffect)(function(){setIsTouchDevice("ontouchstart"in window);setScrollBarLeft(0);setTranslate(0)},[]);// Effect to update container and scroll bar properties. (0,_react.useEffect)(function(){if(containerRef.current){var container=containerRef.current;var _contentWidth=container.scrollWidth;var containerWidth=container.clientWidth;var _diffContentWidth=container.scrollWidth-container.clientWidth;var isContentOverflowing=_contentWidth>containerWidth;setShowBar(isContentOverflowing&&(!isTouchDevice||isTouching));setContentWidth(_contentWidth);setDiffContentWidth(_diffContentWidth);var wp=containerWidth/_contentWidth*100;setWScrollBar(Math.max(Math.min(wp,90),20));// Ensure scrollbar is not too small _dblUtils.eventHandler.dispatch(name,_defineProperty({},name,{position:Math.abs(initialTranslate.current),percentage:Math.abs(initialTranslate.current/_diffContentWidth),size:_diffContentWidth}))}},[contentWidth,breakpoint,orientation,width,height,isTouchDevice,isTouching]);// useEffect to add/remove event listeners (0,_react.useEffect)(function(){var container=containerRef.current;container.addEventListener("wheel",handleWheel,{passive:false});container.addEventListener("touchstart",handleTouchStart);container.addEventListener("touchmove",handleTouchMove);container.addEventListener("touchend",handleTouchEnd);return function(){container.removeEventListener("wheel",handleWheel);container.removeEventListener("touchstart",handleTouchStart);container.removeEventListener("touchmove",handleTouchMove);container.removeEventListener("touchend",handleTouchEnd)}},[contentWidth]);// Effect to handle scroll events. (0,_react.useEffect)(function(){var container=containerRef.current;container.addEventListener("scroll",handleScroll);return function(){return container.removeEventListener("scroll",handleScroll)}},[wScrollBar,contentWidth]);var stc=[scrollTrackClasses];// Scroll track classes. var sbc=["cursor-pointer",scrollBarClasses];// Scroll bar classes. var fc=function fc(input){return[input].flat().filter(Boolean).join(" ")};// Function to flatten and filter class names. var styleSbc=_objectSpread(_objectSpread({height:"100%",backgroundColor:"#888"},scrollBarStyle),{},{width:"".concat(wScrollBar,"%"),marginLeft:"".concat(scrollBarLeft*100,"%")});return/*#__PURE__*/_react["default"].createElement(_react["default"].Fragment,null,/*#__PURE__*/_react["default"].createElement("div",{style:{overflowX:"clip"}},/*#__PURE__*/_react["default"].createElement("div",{ref:containerRef,id:"".concat(name,"-container"),style:{paddingBottom:"2rem",marginBottom:"-2rem",transform:"translate(".concat(translate,"px)"),"--dbl-scroll-x-position":"".concat(Math.abs(translate),"px")}},children)),showBar&&/*#__PURE__*/_react["default"].createElement("div",{className:fc(stc),ref:scrollTrackRef,style:_objectSpread(_objectSpread({bottom:0,left:0,right:0,height:"20px",backgroundColor:"#ccc"},scrollTrackStyle),{},{position:"sticky"})},/*#__PURE__*/_react["default"].createElement("div",{ref:scrollBarRef,className:fc(sbc),style:styleSbc,onMouseDown:handleDragStart,onTouchStart:handleDragStart,role:"scrollbar","aria-controls":"".concat(name,"-container"),"aria-valuemin":"0","aria-valuemax":"100","aria-valuenow":percentage*100,tabIndex:"0"})))}ScrollXNode.propTypes={name:_propTypes["default"].string,breakpoint:_propTypes["default"].oneOfType([_propTypes["default"].string,_propTypes["default"].bool]),orientation:_propTypes["default"].oneOfType([_propTypes["default"].string,_propTypes["default"].bool]),width:_propTypes["default"].number,height:_propTypes["default"].number,scrollTrackClasses:_propTypes2.ptClasses,scrollBarClasses:_propTypes2.ptClasses,scrollTrackStyle:_propTypes["default"].object,scrollBarStyle:_propTypes["default"].object,children:_propTypes["default"].node};/** * Container class for the ScrollContainer component. */var ScrollContainer=exports["default"]=/*#__PURE__*/function(_Container){function ScrollContainer(){_classCallCheck(this,ScrollContainer);return _callSuper(this,ScrollContainer,arguments)}_inherits(ScrollContainer,_Container);return _createClass(ScrollContainer,[{key:"content",value:/** * Renders the ScrollXNode component with the provided properties. * @param {React.ReactNode} children - Child elements to be rendered inside the scroll container. * @returns {React.ReactElement} - The rendered ScrollXNode component. */function content(){var children=arguments.length>0&&arguments[0]!==undefined?arguments[0]:this.props.children;var _this$props=this.props,scrollTrackClasses=_this$props.scrollTrackClasses,scrollBarClasses=_this$props.scrollBarClasses,scrollTrackStyle=_this$props.scrollTrackStyle,scrollBarStyle=_this$props.scrollBarStyle;return/*#__PURE__*/_react["default"].createElement(ScrollXNode,{name:this.props.name,breakpoint:this.breakpoint,orientation:this.orientation,width:this.width,height:this.height,scrollTrackClasses:scrollTrackClasses,scrollBarClasses:scrollBarClasses,scrollTrackStyle:scrollTrackStyle,scrollBarStyle:scrollBarStyle,children:children})}}])}(_container["default"]);_defineProperty(ScrollContainer,"jsClass","ScrollContainer"); //# sourceMappingURL=scroll-container.js.map