1 | import { __rest } from "tslib";
|
2 | import * as React from 'react';
|
3 | import styles from '@patternfly/react-styles/css/components/BackToTop/back-to-top';
|
4 | import { css } from '@patternfly/react-styles';
|
5 | import AngleUpIcon from '@patternfly/react-icons/dist/esm/icons/angle-up-icon';
|
6 | import { canUseDOM } from '../../helpers/util';
|
7 | import { Button } from '../Button';
|
8 | const BackToTopBase = (_a) => {
|
9 | var { className, title = 'Back to top', innerRef, scrollableSelector, isAlwaysVisible = false } = _a, props = __rest(_a, ["className", "title", "innerRef", "scrollableSelector", "isAlwaysVisible"]);
|
10 | const [visible, setVisible] = React.useState(isAlwaysVisible);
|
11 | React.useEffect(() => {
|
12 | setVisible(isAlwaysVisible);
|
13 | }, [isAlwaysVisible]);
|
14 | const [scrollElement, setScrollElement] = React.useState(null);
|
15 | const toggleVisible = () => {
|
16 | const scrolled = scrollElement.scrollY ? scrollElement.scrollY : scrollElement.scrollTop;
|
17 | if (!isAlwaysVisible) {
|
18 | if (scrolled > 400) {
|
19 | setVisible(true);
|
20 | }
|
21 | else {
|
22 | setVisible(false);
|
23 | }
|
24 | }
|
25 | };
|
26 | React.useEffect(() => {
|
27 | const hasScrollSpy = Boolean(scrollableSelector);
|
28 | if (hasScrollSpy) {
|
29 | const scrollEl = document.querySelector(scrollableSelector);
|
30 | if (!canUseDOM || !(scrollEl instanceof HTMLElement)) {
|
31 | return;
|
32 | }
|
33 | setScrollElement(scrollEl);
|
34 | scrollEl.addEventListener('scroll', toggleVisible);
|
35 | return () => {
|
36 | scrollEl.removeEventListener('scroll', toggleVisible);
|
37 | };
|
38 | }
|
39 | else {
|
40 | if (!canUseDOM) {
|
41 | return;
|
42 | }
|
43 | const scrollEl = window;
|
44 | setScrollElement(scrollEl);
|
45 | scrollEl.addEventListener('scroll', toggleVisible);
|
46 | return () => {
|
47 | scrollEl.removeEventListener('scroll', toggleVisible);
|
48 | };
|
49 | }
|
50 | }, [scrollableSelector, toggleVisible]);
|
51 | const handleClick = () => {
|
52 | scrollElement.scrollTo({ top: 0, behavior: 'smooth' });
|
53 | };
|
54 | return (React.createElement("div", Object.assign({ className: css(styles.backToTop, !visible && styles.modifiers.hidden, className), ref: innerRef, onClick: handleClick }, props),
|
55 | React.createElement(Button, { variant: "primary", icon: React.createElement(AngleUpIcon, { "aria-hidden": "true" }), iconPosition: "right" }, title)));
|
56 | };
|
57 | export const BackToTop = React.forwardRef((props, ref) => (React.createElement(BackToTopBase, Object.assign({ innerRef: ref }, props))));
|
58 | BackToTop.displayName = 'BackToTop';
|
59 |
|
\ | No newline at end of file |