1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-11-25 20:02:58 +01:00
metamask-extension/ui/hooks/useScrollRequired.js
Frederik Bolding 789779f4d5
[FLASK] Rework Snaps headers and footers (#19442)
* Add new snap header and footer to snap install

* Add new snap header and footer to snap result and snap update

* Fix loading state

* Fix lint

* Add required scrolling

* Adjust avatar component

* Apply new headers and footers to snaps confirmations

* Rename previous SnapAuthorship component to SnapAuthorshipExpanded

* Fix lint

* Fix font weight

* Fix fencing

* Fix a test

* Fix lint after rebase

* Fix E2E

* Fix locale lint

* Fix another E2E

* Fix test ID

* Address PR comments

* Better scroll button centering

* Address design comments

* Fix unit test

* Fix E2Es
2023-06-07 15:18:49 +02:00

45 lines
1.5 KiB
JavaScript

import { useEffect, useRef, useState } from 'react';
import { debounce } from 'lodash';
/**
* Utility hook for requiring users to scroll through content.
* Returns an object containing state and helpers to accomplish this.
*
* The hook expects both the `ref` and the `onScroll` handler to be passed to the scrolling element.
*
* @param dependencies - Any optional hook dependencies for updating the scroll state.
* @returns Flags for isScrollable and isScrollToBottom, a ref to use for the scrolling content, a scrollToBottom function and a onScroll handler.
*/
export const useScrollRequired = (dependencies = []) => {
const ref = useRef();
const [isScrollableState, setIsScrollable] = useState(false);
const [isScrolledToBottomState, setIsScrolledToBottom] = useState(false);
const update = () => {
const isScrollable =
ref.current && ref.current.scrollHeight > ref.current.clientHeight;
const isScrolledToBottom = isScrollable
? Math.round(ref.current.scrollTop) + ref.current.offsetHeight >=
ref.current.scrollHeight
: true;
setIsScrollable(isScrollable);
setIsScrolledToBottom(isScrolledToBottom);
};
useEffect(update, [ref, ...dependencies]);
const scrollToBottom = () => {
if (ref.current) {
ref.current.scrollTo(0, ref.current.scrollHeight);
}
};
return {
isScrollable: isScrollableState,
isScrolledToBottom: isScrolledToBottomState,
scrollToBottom,
ref,
onScroll: debounce(update, 25),
};
};