Debian Codegraph @

node/@patternfly/react-core/src/components/Pagination/examples/PaginationDynamicStickyBottom.tsx

raw
1 import { useLayoutEffect, useState, useRef } from 'react';
2 import { Pagination, PaginationVariant, Gallery, GalleryItem, Card, CardBody } from '@patternfly/react-core';
3
4 const useIsStuckFromScrollParent = ({
5 shouldTrack,
6 scrollParentRef
7 }: {
8 /** Indicates whether to track the scroll top position of the scroll parent element */
9 shouldTrack: boolean;
10 /** Reference to the scroll parent element */
11 scrollParentRef: React.RefObject<any>;
12 }): boolean => {
13 const [isStuck, setIsStuck] = useState(false);
14
15 useLayoutEffect(() => {
16 if (!shouldTrack) {
17 setIsStuck(false);
18 return;
19 }
20
21 const scrollElement = scrollParentRef.current;
22 if (!scrollElement) {
23 setIsStuck(false);
24 return;
25 }
26
27 const syncFromScroll = () => {
28 setIsStuck(scrollElement.scrollTop + scrollElement.clientHeight < scrollElement.scrollHeight);
29 };
30 syncFromScroll();
31 scrollElement.addEventListener('scroll', syncFromScroll, { passive: true });
32 return () => scrollElement.removeEventListener('scroll', syncFromScroll);
33 }, [shouldTrack, scrollParentRef]);
34
35 return isStuck;
36 };
37
38 export const PaginationDynamicStickyBottom: React.FunctionComponent = () => {
39 const scrollParentRef = useRef<HTMLDivElement>(null);
40 const isStickyStuck = useIsStuckFromScrollParent({ shouldTrack: true, scrollParentRef });
41 const [page, setPage] = useState(1);
42 const [perPage, setPerPage] = useState(50);
43 const itemCount = 523;
44
45 const onSetPage = (_event: React.MouseEvent | React.KeyboardEvent | MouseEvent, newPage: number) => {
46 setPage(newPage);
47 };
48
49 const onPerPageSelect = (
50 _event: React.MouseEvent | React.KeyboardEvent | MouseEvent,
51 newPerPage: number,
52 newPage: number
53 ) => {
54 setPerPage(newPerPage);
55 setPage(newPage);
56 };
57
58 const buildCards = () => {
59 const numberOfCards = (page - 1) * perPage + perPage - 1 >= itemCount ? itemCount - (page - 1) * perPage : perPage;
60
61 return Array.from({ length: numberOfCards }).map((_value, index) => (
62 <GalleryItem key={index}>
63 <Card>
64 <CardBody>This is card {(page - 1) * perPage + index + 1}</CardBody>
65 </Card>
66 </GalleryItem>
67 ));
68 };
69
70 return (
71 <div ref={scrollParentRef} style={{ overflowY: 'scroll', height: '400px' }}>
72 <Gallery hasGutter>{buildCards()}</Gallery>
73 <Pagination
74 itemCount={itemCount}
75 perPage={perPage}
76 page={page}
77 onSetPage={onSetPage}
78 widgetId="dynamic-sticky-bottom-example"
79 onPerPageSelect={onPerPageSelect}
80 variant={PaginationVariant.bottom}
81 isStickyBase
82 isStickyStuck={isStickyStuck}
83 />
84 </div>
85 );
86 };