|
1 | | -import React from 'react'; |
| 1 | +import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; |
2 | 2 | import PropTypes from 'prop-types'; |
3 | 3 |
|
4 | 4 | import { createCssClassNames } from '../helpers/css.class.names'; |
5 | 5 |
|
6 | 6 | const Table = ({ extraClasses, children, isLastColumnSticky }) => { |
| 7 | + const scrollableWrapperRef = useRef(null); |
| 8 | + const [hasLastColumnShadow, setHasLastColumnShadow] = useState(false); |
7 | 9 | const className = createCssClassNames({ |
8 | 10 | 'ibexa-table table': true, |
9 | 11 | 'ibexa-table--last-column-sticky': isLastColumnSticky, |
| 12 | + 'ibexa-table--last-column-shadow': isLastColumnSticky && hasLastColumnShadow, |
10 | 13 | [extraClasses]: true, |
11 | 14 | }); |
| 15 | + const updateLastColumnShadowState = useCallback(() => { |
| 16 | + const offsetRoundingCompensator = 0.5; |
| 17 | + const shouldShowRightColumnShadow = |
| 18 | + scrollableWrapperRef.current.scrollLeft < |
| 19 | + scrollableWrapperRef.current.scrollWidth - scrollableWrapperRef.current.offsetWidth - 2 * offsetRoundingCompensator; |
12 | 20 |
|
13 | | - return <table className={className}>{children}</table>; |
| 21 | + setHasLastColumnShadow(shouldShowRightColumnShadow); |
| 22 | + }, [scrollableWrapperRef, setHasLastColumnShadow]); |
| 23 | + const scrollableWrapperResizeObserver = useMemo( |
| 24 | + () => |
| 25 | + new ResizeObserver(() => { |
| 26 | + updateLastColumnShadowState(); |
| 27 | + }), |
| 28 | + [updateLastColumnShadowState], |
| 29 | + ); |
| 30 | + const handleScrollableWrapperRef = (ref) => { |
| 31 | + if (!ref || (scrollableWrapperRef.current !== null && scrollableWrapperRef.current !== ref)) { |
| 32 | + scrollableWrapperResizeObserver.unobserve(scrollableWrapperRef.current); |
| 33 | + } |
| 34 | + |
| 35 | + scrollableWrapperRef.current = ref; |
| 36 | + |
| 37 | + if (ref) { |
| 38 | + scrollableWrapperResizeObserver.observe(ref); |
| 39 | + |
| 40 | + if (isLastColumnSticky) { |
| 41 | + updateLastColumnShadowState(); |
| 42 | + ref.addEventListener('scroll', updateLastColumnShadowState, false); |
| 43 | + } |
| 44 | + } |
| 45 | + }; |
| 46 | + |
| 47 | + useEffect(() => { |
| 48 | + if (isLastColumnSticky) { |
| 49 | + updateLastColumnShadowState(); |
| 50 | + scrollableWrapperRef.current?.addEventListener('scroll', updateLastColumnShadowState, false); |
| 51 | + |
| 52 | + return () => { |
| 53 | + scrollableWrapperRef.current?.removeEventListener('scroll', updateLastColumnShadowState, false); |
| 54 | + }; |
| 55 | + } |
| 56 | + }, [isLastColumnSticky, updateLastColumnShadowState]); |
| 57 | + |
| 58 | + return ( |
| 59 | + <div className="ibexa-scrollable-wrapper" ref={handleScrollableWrapperRef}> |
| 60 | + <table className={className}>{children}</table> |
| 61 | + </div> |
| 62 | + ); |
14 | 63 | }; |
15 | 64 |
|
16 | 65 | Table.propTypes = { |
|
0 commit comments