UNPKG

react-simple-horizontal-scroller

Version:

A wrapper for horizontally scorlling items, like tabs, that will manage adding and removing scroll controls

380 lines (363 loc) 20.7 kB
import * as React from 'react'; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; function styleInject(css, ref) { if ( ref === void 0 ) ref = {}; var insertAt = ref.insertAt; if (!css || typeof document === 'undefined') { return; } var head = document.head || document.getElementsByTagName('head')[0]; var style = document.createElement('style'); style.type = 'text/css'; if (insertAt === 'top') { if (head.firstChild) { head.insertBefore(style, head.firstChild); } else { head.appendChild(style); } } else { head.appendChild(style); } if (style.styleSheet) { style.styleSheet.cssText = css; } else { style.appendChild(document.createTextNode(css)); } } var css_248z = ".HorizontalScrollContainer_root {\r\n display: flex;\r\n overflow-x: auto;\r\n flex-grow: 1;\r\n /* Hide scrollbar Internet Explorer 10+ */\r\n -ms-overflow-style: none;\r\n /* Hide scrollbar Firefox */\r\n scrollbar-width: none\r\n}\r\n\r\n.HorizontalScrollContainer_buttonsContainer {\r\n display: flex;\r\n align-items: center;\r\n}\r\n\r\n.HorizontalScrollContainer_buttonsContainerShaking {\r\n z-index: 1;\r\n}\r\n\r\n.HorizontalScrollContainer_itemsContainer {\r\n width: 100%;\r\n box-sizing: border-box;\r\n display: flex;\r\n flex-basis: auto;\r\n overflow-x: scroll; \r\n -webkit-overflow-scrolling: touch;\r\n /* Hide scrollbar Internet Explorer 10+ */\r\n -ms-overflow-style: none;\r\n /* Hide scrollbar Firefox */\r\n scrollbar-width: none\r\n}\r\n\r\n/* Hide scrollbar Safari and Chrome */\r\n\r\n.HorizontalScrollContainer_itemsContainer::-webkit-scrollbar {\r\n display: none;\r\n}\r\n\r\n/* Hide scrollbar Safari and Chrome */\r\n\r\n.HorizontalScrollContainer_root::-webkit-scrollbar {\r\n display: none;\r\n}\r\n\r\n.HorizontalScrollContainer_tabsContainerIESupportWhenScrolling {\r\n flex-basis: 0;\r\n -webkit-flex-basis: 0;\r\n flex-grow: 1;\r\n -webkit-flex-grow: 1;\r\n}\r\n\r\n.HorizontalScrollContainer_shakeRight {\r\n animation-name: HorizontalScrollContainer_shakeRight;\r\n animation-duration: 0.3s;\r\n}\r\n\r\n.HorizontalScrollContainer_shakeLeft {\r\n animation-name: HorizontalScrollContainer_shakeLeft;\r\n animation-duration: 0.3s;\r\n}\r\n\r\n.HorizontalScrollContainer_defaultArrowContainer {\r\n min-width: 32px;\r\n height: 100%;\r\n align-items: center;\r\n justify-content: center;\r\n display: flex;\r\n cursor: pointer;\r\n}\r\n\r\n.HorizontalScrollContainer_defaultRightArrow {\r\n border: solid black;\r\n border-width: 0 3px 3px 0;\r\n display: inline-block;\r\n padding: 3px;\r\n transform: rotate(-45deg);\r\n}\r\n\r\n.HorizontalScrollContainer_defaultLeftArrow {\r\n border: solid black;\r\n border-width: 0 3px 3px 0;\r\n display: inline-block;\r\n padding: 3px;\r\n transform: rotate(135deg);\r\n}\r\n\r\n@keyframes HorizontalScrollContainer_shakeRight {\r\n 0%, 100% {\r\n transform: translateX(0);\r\n }\r\n 33% {\r\n transform: translateX(-32px);\r\n }\r\n}\r\n\r\n@keyframes HorizontalScrollContainer_shakeLeft {\r\n 0%, 100% {\r\n transform: translateX(0);\r\n }\r\n 33% {\r\n transform: translateX(32px);\r\n }\r\n}"; styleInject(css_248z); /** * A thin wrapper that enables the user of horizontalScrollContainer to completely ignore refs */ var HorizontalScrollItem = /** @class */ (function (_super) { __extends(HorizontalScrollItem, _super); function HorizontalScrollItem(props) { return _super.call(this, props) || this; } HorizontalScrollItem.prototype.render = function () { return React.createElement("div", __assign({}, this.props)); }; HorizontalScrollItem.displayName = "HorizontalScrollItem"; return HorizontalScrollItem; }(React.PureComponent)); /** * Returns true if the given JSX element matches the given component type. * * NOTE: This function only checks equality of `displayName` for performance and * to tolerate multiple minor versions of a component being included in one * application bundle. * @param element JSX element in question * @param ComponentType desired component type of element */ function isElementOfType(element, ComponentType) { return (element != null && element.type != null && element.type.displayName != null && element.type.displayName === ComponentType.displayName); } var HorizontalScrollContainer = /** @class */ (function (_super) { __extends(HorizontalScrollContainer, _super); function HorizontalScrollContainer(props) { var _this = _super.call(this, props) || this; _this.SCROLL_TIMEOUT_INTO_VIEW = 50; _this.SCROLL_TIMEOUT_WHEEL = 100; _this.SCROLL_TIMEOUT_ARROWS = 30; _this.scrollableContainer = React.createRef(); _this.selectedItem = React.createRef(); _this.handleWheel = function (e) { if (e.deltaY === 0 || e.deltaX !== 0 || _this.props.removeMouseWheelOverride === true) { return; } var element = _this.scrollableContainer.current; var direction = e.deltaY > 0 ? 'RIGHT' : 'LEFT'; if (_this.canScrollToSide(element, direction)) { _this.scrollTimeoutTimer = _this.SCROLL_TIMEOUT_WHEEL; element === null || element === void 0 ? void 0 : element.scrollBy({ top: 0, left: e.deltaY }); } e.preventDefault(); e.stopPropagation(); }; _this.handleScrollEnd = function () { _this.isScrolling = false; if (_this.props.onScrollEnd === undefined) { return; } var element = _this.scrollableContainer.current; _this.props.onScrollEnd(_this.getPositionAfterScrollEnd(element)); }; _this.handleScroll = function () { clearTimeout(_this.scrollTimeoutId); _this.scrollStart(); _this.scrollTimeoutId = window.setTimeout(_this.handleScrollEnd, _this.scrollTimeoutTimer); }; _this.resize = function () { if (_this.props.resizeListenerDebounce === undefined) { _this.resizeListener(); } else { _this.resizeWithDebounce(_this.props.resizeListenerDebounce); } }; _this.resizeListener = function () { var element = _this.scrollableContainer.current; if (element === null) { return; } // Do not use element.clientWidth because it gets ROUNDED which causes false positives // https://stackoverflow.com/questions/21064101/understanding-offsetwidth-clientwidth-scrollwidth-and-height-respectively // https://developer.mozilla.org/en-US/docs/Web/API/Element/clientWidth // TODO understand why ONLY in MAC a +1 is needed, seems to be a problem with the scaling var ableToScroll = Math.floor(element.scrollWidth) > Math.ceil(element.getBoundingClientRect().width) + 1; if (_this.wasScrollable !== ableToScroll) { _this.wasScrollable = ableToScroll; _this.setState({ isScrollable: ableToScroll }); _this.handleScrollStateChange(ableToScroll); } _this.scrollIntoViewIfNeeded(); }; _this.isScrolling = false; _this.scrollTimeoutTimer = _this.SCROLL_TIMEOUT_INTO_VIEW; _this.state = { shaking: null, isScrollable: false, }; return _this; } HorizontalScrollContainer.prototype.componentDidMount = function () { var _a; if (this.props.useExternalResizeListener !== true) { window.addEventListener('resize', this.resize); } (_a = this.scrollableContainer.current) === null || _a === void 0 ? void 0 : _a.addEventListener('wheel', this.handleWheel, { passive: false }); /** * Must happen this way to scroll the selected element into view */ this.resizeWithDebounce(0); }; HorizontalScrollContainer.prototype.componentWillUnmount = function () { var _a; (_a = this.scrollableContainer.current) === null || _a === void 0 ? void 0 : _a.removeEventListener('wheel', this.handleWheel); window.removeEventListener('resize', this.resize); }; HorizontalScrollContainer.prototype.componentDidUpdate = function () { this.resize(); }; HorizontalScrollContainer.prototype.render = function () { var _this = this; var _a, _b, _c; var isSeperate = ((_a = this.props.controlsConfig) === null || _a === void 0 ? void 0 : _a.position) === undefined || this.props.controlsConfig.position === 'SEPARATED'; var beforeChild = isSeperate || ((_b = this.props.controlsConfig) === null || _b === void 0 ? void 0 : _b.position) === 'BEFORE_CHILD'; var afterChild = isSeperate || ((_c = this.props.controlsConfig) === null || _c === void 0 ? void 0 : _c.position) === 'AFTER_CHILD'; return React.createElement("div", { className: 'HorizontalScrollContainer_root' }, this.state.isScrollable && beforeChild ? this.renderControls('BEFORE_CHILD') : null, React.createElement("div", { className: this.getChildrenContainerClass(), ref: this.scrollableContainer, onAnimationEnd: function () { return _this.setState({ shaking: null }); }, onScroll: this.handleScroll, style: { justifyContent: !this.state.isScrollable ? this.props.childPosition : undefined } }, !this.state.isScrollable && beforeChild ? this.renderControls('BEFORE_CHILD') : null, this.renderChildren(), !this.state.isScrollable && afterChild ? this.renderControls('AFTER_CHILD') : null), this.state.isScrollable && afterChild ? this.renderControls('AFTER_CHILD') : null); }; HorizontalScrollContainer.prototype.getMovementControls = function (position) { var _a, _b, _c, _d; var right = __assign(__assign({}, (_a = this.props.controlsConfig) === null || _a === void 0 ? void 0 : _a.right), { direction: 'RIGHT' }); var left = __assign(__assign({}, (_b = this.props.controlsConfig) === null || _b === void 0 ? void 0 : _b.left), { direction: 'LEFT' }); var controlsConfigPosition = (_d = (_c = this.props.controlsConfig) === null || _c === void 0 ? void 0 : _c.position) !== null && _d !== void 0 ? _d : 'SEPARATED'; switch (controlsConfigPosition) { case 'AFTER_CHILD': { if (position === 'AFTER_CHILD') { return React.createElement(React.Fragment, null, this.isMovementControlsVisible(left) ? this.renderMovementControl(left) : null, this.isMovementControlsVisible(right) ? this.renderMovementControl(right) : null); } break; } case 'BEFORE_CHILD': { if (position === 'BEFORE_CHILD') { return React.createElement(React.Fragment, null, this.isMovementControlsVisible(left) ? this.renderMovementControl(left) : null, this.isMovementControlsVisible(right) ? this.renderMovementControl(right) : null); } break; } case 'SEPARATED': { if (position === 'BEFORE_CHILD') { return this.isMovementControlsVisible(left) ? this.renderMovementControl(left) : null; } if (position === 'AFTER_CHILD') { return this.isMovementControlsVisible(right) ? this.renderMovementControl(right) : null; } break; } } }; HorizontalScrollContainer.prototype.renderControls = function (position) { if (!this.isControlVisible()) { return null; } return React.createElement("div", { className: 'HorizontalScrollContainer_buttonsContainer' + (this.state.shaking !== null ? ' HorizontalScrollContainer_buttonsContainerShaking' : '') }, this.getMovementControls(position)); }; HorizontalScrollContainer.prototype.scrollIntoViewIfNeeded = function () { var selected = this.selectedItem.current; if (selected !== null && this.lastSelectedItemId !== this.props.selectedItemId) { this.lastSelectedItemId = this.props.selectedItemId; this.scrollTimeoutTimer = this.SCROLL_TIMEOUT_INTO_VIEW; selected.scrollIntoView({ behavior: 'smooth' }); } }; HorizontalScrollContainer.prototype.getPositionAfterScrollEnd = function (element) { if (!this.canScrollToSide(element, 'LEFT')) { return 'LEFT'; } else if (!this.canScrollToSide(element, 'RIGHT')) { return 'RIGHT'; } return null; }; HorizontalScrollContainer.prototype.scrollStart = function () { if (!this.isScrolling) { this.isScrolling = true; if (this.props.onScrollStart !== undefined) { this.props.onScrollStart(); } } }; HorizontalScrollContainer.prototype.renderMovementControl = function (config) { var _this = this; var _a, _b; var iconClassName = config.direction === 'LEFT' ? 'HorizontalScrollContainer_defaultLeftArrow' : 'HorizontalScrollContainer_defaultRightArrow'; var scrollStepWithDirectiton = function () { return _this.scrollStep(config.direction); }; var defaultIcon = React.createElement("div", { onClick: scrollStepWithDirectiton, className: (_a = 'HorizontalScrollContainer_defaultArrowContainer ' + config.defaultIconContainerClassName) !== null && _a !== void 0 ? _a : '', style: config.defaultIconContainerStyle }, React.createElement("div", { className: (_b = iconClassName + ' ' + config.defaultIconClassName) !== null && _b !== void 0 ? _b : '', style: config.defaultIconStyle })); if (config.customComponent !== undefined) { return config.customComponent(scrollStepWithDirectiton, defaultIcon); } return defaultIcon; }; HorizontalScrollContainer.prototype.renderChildren = function () { var children = this.props.children; if (this.props.selectedItemId !== undefined) { children = this.getChildren(children); } return children; }; HorizontalScrollContainer.prototype.getChildren = function (children) { var _this = this; return React.Children.map(children, function (child) { if (isElementOfType(child, HorizontalScrollItem)) { return React.createElement("div", __assign({}, child.props, { ref: _this.props.selectedItemId === child.props.id ? _this.selectedItem : null })); } else if (React.isValidElement(child)) { return React.cloneElement(child, { children: _this.getChildren(child.props.children) }); } return child; }); }; HorizontalScrollContainer.prototype.isControlVisible = function () { var _a, _b; return this.isMovementControlsVisible((_a = this.props.controlsConfig) === null || _a === void 0 ? void 0 : _a.right) || this.isMovementControlsVisible((_b = this.props.controlsConfig) === null || _b === void 0 ? void 0 : _b.left); }; HorizontalScrollContainer.prototype.isMovementControlsVisible = function (config) { if (config === undefined) { return this.state.isScrollable; } else { return config.visibility === 'ALWAYS' || (this.state.isScrollable && config.visibility !== 'NONE'); } }; HorizontalScrollContainer.prototype.resizeWithDebounce = function (debounce) { clearTimeout(this.resizeTimeoutId); this.resizeTimeoutId = window.setTimeout(this.resizeListener, debounce); }; HorizontalScrollContainer.prototype.handleScrollStateChange = function (state) { if (this.props.onScrollStateChange !== undefined) { this.props.onScrollStateChange(state); } }; HorizontalScrollContainer.prototype.getChildrenContainerClass = function () { var classList = 'HorizontalScrollContainer_itemsContainer'; if (this.state.isScrollable) { classList += ' HorizontalScrollContainer_tabsContainerIESupportWhenScrolling'; } if (this.state.shaking === 'LEFT') { classList += ' HorizontalScrollContainer_shakeLeft'; } else if (this.state.shaking === 'RIGHT') { classList += ' HorizontalScrollContainer_shakeRight'; } return classList; }; HorizontalScrollContainer.prototype.canScrollToSide = function (element, direction) { if (element === null) { return false; } if (direction === 'LEFT') { return element.scrollLeft > 0; } else { // Math.ceil and floor to help support browser zoom return Math.ceil(element.scrollLeft) < Math.floor(element.scrollWidth - element.clientWidth); } }; HorizontalScrollContainer.prototype.getScrollBy = function (element, direction) { var sideModifier = direction === 'LEFT' ? -1 : 1; if (this.props.customScrollBy !== undefined) { return sideModifier * this.props.customScrollBy(element.clientWidth); } else { var minScrollBy = 208; // Arbitrary var scrollLeftBy = sideModifier * Math.max(element.clientWidth / 2, minScrollBy); return scrollLeftBy; } }; HorizontalScrollContainer.prototype.scrollStep = function (direction) { var element = this.scrollableContainer.current; if (!this.state.isScrollable || !this.canScrollToSide(element, direction) && this.state.shaking === null) { this.setState({ shaking: direction }); } else if (!this.isScrolling) { this.scrollTimeoutTimer = this.SCROLL_TIMEOUT_ARROWS; element === null || element === void 0 ? void 0 : element.scrollBy({ top: 0, left: this.getScrollBy(element, direction), behavior: 'smooth', }); } }; return HorizontalScrollContainer; }(React.Component)); export { HorizontalScrollContainer, HorizontalScrollItem }; //# sourceMappingURL=index.esm.js.map