Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BD-46] Add fixed increment scroll behavior to useOverflowScroll #2151

Merged
merged 2 commits into from
Jun 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions src/OverflowScroll/OverflowScroll.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ function OverflowScroll({
disableOpacityMasks,
onScrollPrevious,
onScrollNext,
offset,
offsetType,
}) {
const [overflowRef, setOverflowRef] = useState();

Expand All @@ -29,6 +31,8 @@ function OverflowScroll({
onScrollPrevious,
onScrollNext,
overflowRef,
offset,
offsetType,
});

const contextValue = useMemo(() => ({
Expand Down Expand Up @@ -80,6 +84,8 @@ OverflowScroll.propTypes = {
onScrollPrevious: PropTypes.func,
/** Callback function for when the user scrolls to the next element. */
onScrollNext: PropTypes.func,
offset: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
offsetType: PropTypes.oneOf(['percentage', 'fixed']),
};

OverflowScroll.defaultProps = {
Expand All @@ -89,6 +95,8 @@ OverflowScroll.defaultProps = {
disableOpacityMasks: false,
onScrollPrevious: undefined,
onScrollNext: undefined,
offset: undefined,
offsetType: 'percentage',
};

export default OverflowScroll;
80 changes: 80 additions & 0 deletions src/OverflowScroll/data/tests/useOverflowScrollActions.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -114,4 +114,84 @@ describe('useOverflowScrollActions', () => {
);
expect(mockScrollTo).toBeCalledTimes(1);
});

it('scrollToPrevious moves scroll to specified percentage', () => {
const scrollWidth = 1000;
const clientWidth = 200;

const overflowRef = {
scrollWidth,
clientWidth,
scrollTo: jest.fn(),
};
const activeChildElementIndex = 2;
const childrenElements = [...Array(5)];
const offset = '20';
const offsetType = 'percentage';
const currentOffset = 500;
const onChangeOffset = jest.fn();
const scrollAnimationBehavior = 'smooth';

const { result } = renderHook(() => useOverflowScrollActions({
overflowRef,
activeChildElementIndex,
childrenElements,
offset,
offsetType,
currentOffset,
onChangeOffset,
scrollAnimationBehavior,
}));
const { scrollToPrevious } = result.current;

act(() => {
scrollToPrevious();
});

expect(onChangeOffset).toHaveBeenCalledWith(currentOffset - 160);
expect(overflowRef.scrollTo).toHaveBeenCalledWith({
left: currentOffset - 160,
behavior: scrollAnimationBehavior,
});
});

it('scrollToNext moves scroll to specified fixed value', async () => {
const scrollWidth = 1000;
const clientWidth = 200;

const overflowRef = {
scrollWidth,
clientWidth,
scrollTo: jest.fn(),
};
const activeChildElementIndex = 2;
const childrenElements = [...Array(5)];
const offset = '20';
const offsetType = 'percentage';
const currentOffset = 0;
const onChangeOffset = jest.fn();
const scrollAnimationBehavior = 'smooth';

const { result } = renderHook(() => useOverflowScrollActions({
overflowRef,
activeChildElementIndex,
childrenElements,
offset,
offsetType,
currentOffset,
onChangeOffset,
scrollAnimationBehavior,
}));
const { scrollToNext } = result.current;

act(() => {
scrollToNext();
});

expect(onChangeOffset).toHaveBeenCalledWith(currentOffset + 160);
expect(overflowRef.scrollTo).toHaveBeenCalledWith({
left: currentOffset + 160,
behavior: scrollAnimationBehavior,
});
});
});
8 changes: 8 additions & 0 deletions src/OverflowScroll/data/useOverflowScroll.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import getOverflowElementScrollLeft from './getOverflowElementScrollLeft';
* @param {boolean} args.disableOpacityMasks Whether the start/end opacity masks should be shown, when applicable.
* @param {string} args.scrollAnimationBehavior Optional override for the scroll behavior. See https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTo for
* more details.
* @param {string} args.offset Fixed increment in pixels or percentage for scroll.
*
* @returns {object} An object with the following properties:
* - overflowRef
Expand All @@ -45,7 +46,10 @@ const useOverflowScroll = ({
disableScroll = false,
disableOpacityMasks = false,
scrollAnimationBehavior = 'smooth',
offset,
offsetType = 'percentage',
}) => {
const [currentOffset, setCurrentOffset] = useState(0);
const [isScrolledToStart, setIsScrolledToStart] = useState(true);
const [isScrolledToEnd, setIsScrolledToEnd] = useState(true);

Expand Down Expand Up @@ -153,6 +157,10 @@ const useOverflowScroll = ({
scrollAnimationBehavior,
onScrollPrevious: handleScrollPrevious,
onScrollNext: handleScrollNext,
onChangeOffset: setCurrentOffset,
currentOffset,
offset,
offsetType,
});

return {
Expand Down
74 changes: 54 additions & 20 deletions src/OverflowScroll/data/useOverflowScrollActions.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,19 @@ const useOverflowScrollActions = ({
scrollAnimationBehavior = 'smooth',
onScrollPrevious,
onScrollNext,
onChangeOffset,
currentOffset,
offset,
offsetType = 'percentage',
}) => {
const getOffset = useCallback((value, type, maxOffset) => {
const numOffset = parseInt(value, 10);

return type === 'percentage'
? Math.round(maxOffset * (numOffset / 100))
: numOffset;
}, []);

/**
* A helper function to scroll to the previous element in the overflow container.
*/
Expand All @@ -34,22 +46,33 @@ const useOverflowScrollActions = ({

const previousChildElementIndex = activeChildElementIndex - 1;
const previousChildElement = getPreviousChildElement(previousChildElementIndex);
const calculatedOffsetLeft = calculateOffsetLeft(previousChildElement);
let calculatedOffsetLeft = calculateOffsetLeft(previousChildElement);

if (offset) {
const maxOffset = overflowRef.scrollWidth - overflowRef.clientWidth;
const offsetValue = getOffset(offset, offsetType, maxOffset);
calculatedOffsetLeft = currentOffset - offsetValue;
if (onChangeOffset) {
if (calculatedOffsetLeft < 0) {
onChangeOffset(0);
} else {
onChangeOffset(calculatedOffsetLeft);
}
}
}

overflowRef.scrollTo({
left: calculatedOffsetLeft,
behavior: scrollAnimationBehavior,
});
const currentActiveChildElementIndex = previousChildElementIndex <= 0 ? 0 : previousChildElementIndex;
onScrollPrevious({
currentActiveChildElementIndex,
});
}, [
overflowRef,
childrenElements,
activeChildElementIndex,
scrollAnimationBehavior,
onScrollPrevious,
]);
if (onScrollPrevious) {
onScrollPrevious({
currentActiveChildElementIndex,
});
}
}, [overflowRef, activeChildElementIndex, offset, scrollAnimationBehavior, onScrollPrevious, childrenElements,
getOffset, offsetType, currentOffset, onChangeOffset]);

/**
* A helper function to scroll to the next element in the overflow container.
Expand All @@ -73,20 +96,31 @@ const useOverflowScrollActions = ({
};

const nextChildElement = getNextChildElement();
const calculatedOffsetLeft = calculateOffsetLeft(nextChildElement);
let calculatedOffsetLeft = calculateOffsetLeft(nextChildElement);

if (offset) {
const maxOffset = overflowRef.scrollWidth - overflowRef.clientWidth;
const offsetValue = getOffset(offset, offsetType, maxOffset);
calculatedOffsetLeft = currentOffset + offsetValue;
if (onChangeOffset) {
if (calculatedOffsetLeft > maxOffset) {
onChangeOffset(maxOffset);
} else {
onChangeOffset(calculatedOffsetLeft);
}
}
}

overflowRef.scrollTo({
left: calculatedOffsetLeft,
behavior: scrollAnimationBehavior,
});
const currentActiveChildElementIndex = isNextChildIndexAtEnd ? lastChildElementIndex : nextChildElementIndex;
onScrollNext({ currentActiveChildElementIndex });
}, [
overflowRef,
activeChildElementIndex,
scrollAnimationBehavior,
childrenElements,
onScrollNext,
]);
if (onScrollNext) {
onScrollNext({ currentActiveChildElementIndex });
}
}, [overflowRef, childrenElements, activeChildElementIndex, offset, scrollAnimationBehavior, onScrollNext,
getOffset, offsetType, currentOffset, onChangeOffset]);

return {
scrollToPrevious,
Expand Down
92 changes: 92 additions & 0 deletions src/OverflowScroll/useOverflowScroll.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -98,3 +98,95 @@ The hook returns the following:
* `activeChildElementIndex`. The index of the child element that is currently deemed to be "active", i.e. the child element used as the reference position for any `scrollToPrevious` or `scrollToNext` calls.

See [`OverflowScroll`](/components/overflowscroll/overflowscroll) for React components that encapsulate the logic within `useOverflowScroll`.

### Use of `offset` and `offsetType`

```jsx live
() => {
const [offset, setOffset] = useState(50);
const [offsetType, setOffsetType] = useState('percentage');

const [overflowRef, setOverflowRef] = useState();

const {
isScrolledToStart,
isScrolledToEnd,
scrollToPrevious,
scrollToNext,
} = useOverflowScroll({
childQuerySelector: '.example-item',
overflowRef,
offset,
offsetType,
});

const ExampleItem = ({ className }) => (
<div
className={classNames('example-item border flex-shrink-0 text-center', className)}
style={{ width: 160 }}
>
Item
</div>
);
const itemCount = 20;
const items = useMemo(() => Array.from({ length: itemCount }).map((index) => {
if (index !== itemCount - 1) {
return <ExampleItem key={uuidv4()} className="mr-2" />;
}
// last element, no right margin
return <ExampleItem key={uuidv4()} />;
}), []);

return (
<>
{/* start example form block */}
<ExamplePropsForm
inputs={[
{
value: offset,
setValue: setOffset,
range: {
min: 0,
max: offsetType === 'percentage' ? 100 : 1000,
step: offsetType === 'percentage' ? 1 : 50,
},
name: 'offset'
},
{
value: offsetType,
setValue: setOffsetType,
options: ['percentage', 'fixed'],
name: 'offsetType'
},
]}
/>
{/* end example form block */}

<div className="mb-3">
<Button
onClick={scrollToPrevious}
disabled={isScrolledToStart}
size="sm"
className="mr-2"
>
Previous
</Button>
<Button
onClick={scrollToNext}
disabled={isScrolledToEnd}
size="sm"
>
Next
</Button>
</div>
<div
ref={setOverflowRef}
aria-label="example overflow scroll container"
className="d-flex"
>
{items}
</div>
</>
);
};
```