import React, { Children, useEffect, useRef } from 'react'; import Icon from '../../common/Icon'; import SiteNavigation from '../SiteNavigation'; import DSMobileMenu from '@scottish-government/design-system/dist/scripts/components/site-navigation/site-navigation'; import { SiteHeaderBrandProps, SiteHeaderProps } from './types'; import { SiteNavigationProps } from '../SiteNavigation/types'; const Brand = ({ children, homeUrl = '/', linkComponent, siteTitle }: SiteHeaderBrandProps) => { function processChildren(children: React.ReactNode) { const image = React.cloneElement(children as React.ReactElement, { className: 'ds_site-branding__logo-image' }); if (linkComponent) { return linkComponent({ className: 'ds_site-branding__logo ds_site-branding__link', href: homeUrl, children: image }); } else if (homeUrl) { return {image}; } } return ( <> {processChildren(children)} {siteTitle &&
{siteTitle}
} ); } const Navigation = ({ children }: React.AllHTMLAttributes) => { return children; } const Phase = ({ children }: React.AllHTMLAttributes) => { return children; } const Search = ({ children }: React.AllHTMLAttributes) => { return children; } const SiteHeader = ({ children, ...props }: SiteHeaderProps) => { const mobileMenuRef = useRef(null); let branding: React.ReactNode; let navigation: React.ReactNode; let mobileNavigation: React.ReactNode; let phase: React.ReactNode; let search: React.ReactNode; // assign to slots Children.forEach(children, (child: React.ReactNode) => { const thisChild = child as React.JSX.Element; if (thisChild && thisChild.type === Brand) { branding = thisChild; } else if (thisChild && thisChild.type === Navigation) { navigation = thisChild; if (thisChild.props.children.type === SiteNavigation) { mobileNavigation = React.cloneElement(thisChild.props.children as React.ReactElement, { className: 'ds_site-navigation--mobile', id: 'mobile-navigation', ref: mobileMenuRef}); } } else if (thisChild && thisChild.type === Phase) { phase = thisChild; } else if (thisChild && thisChild.type === Search) { search = thisChild; } }); useEffect(() => { /* istanbul ignore else */ if (mobileMenuRef.current) { new DSMobileMenu(mobileMenuRef.current).init(); } }, [mobileMenuRef]); return (
{branding}
{mobileNavigation && <>
} {mobileNavigation}
{search}
{phase} {navigation &&
{navigation}
}
); }; SiteHeader.Brand = Brand; SiteHeader.Navigation = Navigation; SiteHeader.Phase = Phase; SiteHeader.Search = Search; SiteHeader.displayName = 'SiteHeader'; Brand.displayName = 'SiteHeader.Brand'; Navigation.displayName = 'SiteHeader.Navigation'; Phase.displayName = 'SiteHeader.Phase'; Search.displayName = 'SiteHeader.Search'; export default SiteHeader;