Debian Codegraph @

node/@patternfly/react-core/src/components/Toolbar/examples/ToolbarDynamicSticky.tsx

raw
1 import { useLayoutEffect, useState, useRef } from 'react';
2 import { Toolbar, ToolbarItem, ToolbarContent, SearchInput, Checkbox } 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 > 0);
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 ToolbarDynamicSticky = () => {
39 const scrollParentRef = useRef<HTMLDivElement>(null);
40 const isStickyStuck = useIsStuckFromScrollParent({ shouldTrack: true, scrollParentRef });
41 const [showEvenOnly, setShowEvenOnly] = useState(true);
42 const [searchValue, setSearchValue] = useState('');
43 const array = Array.from(Array(30), (_, x) => x); // create array of numbers from 1-30 for demo purposes
44 const numbers = showEvenOnly ? array.filter((number) => number % 2 === 0) : array;
45
46 return (
47 <div id="dynamic-sticky-scroll-parent" ref={scrollParentRef} style={{ overflowY: 'scroll', height: '200px' }}>
48 <Toolbar id="toolbar-dynamic-sticky" inset={{ default: 'insetNone' }} isStickyBase isStickyStuck={isStickyStuck}>
49 <ToolbarContent>
50 <ToolbarItem>
51 <SearchInput
52 aria-label="Sticky example search input"
53 value={searchValue}
54 onChange={(_event, value) => setSearchValue(value)}
55 onClear={() => setSearchValue('')}
56 />
57 </ToolbarItem>
58 <ToolbarItem alignSelf="center">
59 <Checkbox
60 label="Show only even number items"
61 isChecked={showEvenOnly}
62 onChange={(_event, checked) => setShowEvenOnly(checked)}
63 id="showOnlyEvenCheckbox"
64 />
65 </ToolbarItem>
66 </ToolbarContent>
67 </Toolbar>
68 <ul>
69 {numbers.map((number) => (
70 <li key={number}>{`item ${number}`}</li>
71 ))}
72 </ul>
73 </div>
74 );
75 };