|
| 1 | +import React, { useEffect, useRef, useState } from 'react'; |
| 2 | +import { Flex, Heading, Text, forwardRef, FlexProps } from '@chakra-ui/react'; |
| 3 | + |
| 4 | +interface InnerPageHeaderProps extends FlexProps { |
| 5 | + title: string; |
| 6 | + overline?: string; |
| 7 | + actions?: React.ReactNode; |
| 8 | +} |
| 9 | + |
| 10 | +export const InnerPageHeader = forwardRef<InnerPageHeaderProps, 'div'>( |
| 11 | + ({ title, overline, actions, ...rest }, ref) => { |
| 12 | + return ( |
| 13 | + <Flex |
| 14 | + ref={ref} |
| 15 | + bg='base.50' |
| 16 | + borderRadius='md' |
| 17 | + p={4} |
| 18 | + direction='column' |
| 19 | + gap={2} |
| 20 | + {...rest} |
| 21 | + > |
| 22 | + {overline && ( |
| 23 | + <Text as='p' color='base.400'> |
| 24 | + {overline} |
| 25 | + </Text> |
| 26 | + )} |
| 27 | + <Flex gap={4} justifyContent='space-between' alignItems='center'> |
| 28 | + <Heading size='md'>{title}</Heading> |
| 29 | + {actions && <Flex gap={2}>{actions}</Flex>} |
| 30 | + </Flex> |
| 31 | + </Flex> |
| 32 | + ); |
| 33 | + } |
| 34 | +); |
| 35 | + |
| 36 | +export const InnerPageHeaderSticky = forwardRef<InnerPageHeaderProps, 'div'>( |
| 37 | + (props, ref) => { |
| 38 | + const [isAtTop, setIsAtTop] = useState(false); |
| 39 | + |
| 40 | + const localRef = useRef<HTMLDivElement | null>(null); |
| 41 | + |
| 42 | + useEffect(() => { |
| 43 | + const el = localRef.current; |
| 44 | + if (!el) return; |
| 45 | + const observer = new IntersectionObserver( |
| 46 | + ([entry]) => { |
| 47 | + setIsAtTop(entry.intersectionRatio < 1); |
| 48 | + }, |
| 49 | + { threshold: [1] } |
| 50 | + ); |
| 51 | + |
| 52 | + observer.observe(el); |
| 53 | + |
| 54 | + return () => { |
| 55 | + observer.unobserve(el); |
| 56 | + }; |
| 57 | + }, []); |
| 58 | + |
| 59 | + const headerRef: React.RefCallback<HTMLDivElement> = (v) => { |
| 60 | + localRef.current = v; |
| 61 | + if (typeof ref === 'function') { |
| 62 | + ref(v); |
| 63 | + } else if (ref != null) { |
| 64 | + (ref as React.MutableRefObject<any>).current = v; |
| 65 | + } |
| 66 | + }; |
| 67 | + |
| 68 | + return ( |
| 69 | + <InnerPageHeader |
| 70 | + ref={headerRef} |
| 71 | + position='sticky' |
| 72 | + top='-1px' |
| 73 | + boxShadow={isAtTop ? 'md' : 'none'} |
| 74 | + zIndex={100} |
| 75 | + {...props} |
| 76 | + /> |
| 77 | + ); |
| 78 | + } |
| 79 | +); |
0 commit comments