import React, { useRef, useEffect, useMemo, useState } from 'react'; import classnames from 'classnames'; import { BlockSize, Display, JustifyContent, } from '../../../helpers/constants/design-system'; import { Box } from '..'; import type { PolymorphicRef, BoxProps } from '../box'; import { HeaderBaseProps, HeaderBaseComponent } from './header-base.types'; export const HeaderBase: HeaderBaseComponent = React.forwardRef( ( { startAccessory, endAccessory, className = '', children, childrenWrapperProps, startAccessoryWrapperProps, endAccessoryWrapperProps, ...props }: HeaderBaseProps, ref?: PolymorphicRef, ) => { const startAccessoryRef = useRef(null); const endAccessoryRef = useRef(null); const [accessoryMinWidth, setAccessoryMinWidth] = useState(); useEffect(() => { function handleResize() { if (startAccessoryRef.current && endAccessoryRef.current) { const accMinWidth = Math.max( startAccessoryRef.current.scrollWidth, endAccessoryRef.current.scrollWidth, ); setAccessoryMinWidth(accMinWidth); } else if (startAccessoryRef.current && !endAccessoryRef.current) { setAccessoryMinWidth(startAccessoryRef.current.scrollWidth); } else if (!startAccessoryRef.current && endAccessoryRef.current) { setAccessoryMinWidth(endAccessoryRef.current.scrollWidth); } else { setAccessoryMinWidth(0); } } handleResize(); window.addEventListener('resize', handleResize); return () => { window.removeEventListener('resize', handleResize); }; }, [startAccessoryRef, endAccessoryRef, children]); const getTitleStyles = useMemo(() => { if (startAccessory && !endAccessory) { return { marginRight: `${accessoryMinWidth}px`, }; } else if (!startAccessory && endAccessory) { return { marginLeft: `${accessoryMinWidth}px`, }; } return {}; }, [accessoryMinWidth, startAccessory, endAccessory]); return ( )} > {startAccessory && ( )} > {startAccessory} )} {children && ( )} > {children} )} {endAccessory && ( )} > {endAccessory} )} ); }, );