File size: 2,518 Bytes
1e92f2d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | import clsx from 'clsx';
import React, { useRef, forwardRef, Fragment } from 'react';
import { useSelector } from 'react-redux';
import { useCurrentRoute } from 'calypso/components/route';
import { getShouldShowCollapsedGlobalSidebar } from 'calypso/state/global-sidebar/selectors';
import { getSelectedSiteId } from 'calypso/state/ui/selectors';
import type { ReactNode, LegacyRef } from 'react';
interface Props {
url?: string;
tipTarget?: string;
onClick: () => void;
tooltip?: string;
tooltipPlacement?: 'bottom' | 'top' | 'right';
icon?: ReactNode;
className: string;
isActive?: boolean;
preloadSection?: () => void;
hasUnseen?: boolean;
alwaysShowContent?: boolean;
disabled?: boolean;
}
const SidebarMenuItem = forwardRef< HTMLButtonElement | HTMLAnchorElement, Props >(
(
{
url,
tipTarget,
onClick,
tooltip,
tooltipPlacement = 'bottom',
icon,
className,
isActive,
preloadSection,
hasUnseen,
alwaysShowContent,
disabled,
},
ref
) => {
const preloadedRef = useRef( false );
const selectedSiteId = useSelector( getSelectedSiteId );
const { currentSection, currentRoute } = useCurrentRoute() as {
currentSection: false | { group?: string; name?: string };
currentRoute: string;
};
const isSidebarCollapsed = useSelector( ( state ) => {
return getShouldShowCollapsedGlobalSidebar( {
state,
siteId: selectedSiteId,
section: currentSection as { group?: string },
route: currentRoute,
} );
} );
const preload = () => {
if ( ! preloadedRef.current && preloadSection ) {
preloadedRef.current = true;
preloadSection();
}
};
const renderChildren = () => {
return <Fragment>{ icon && <>{ icon }</> }</Fragment>;
};
const itemClasses = clsx( 'sidebar__item', className, {
'is-active': isActive,
'has-unseen': hasUnseen,
'sidebar__item--always-show-content': alwaysShowContent,
[ `tooltip tooltip-${ isSidebarCollapsed ? 'right' : tooltipPlacement }` ]: tooltip,
} );
const attributes = {
'data-tooltip': tooltip,
'data-tip-target': tipTarget,
onClick: onClick,
className: itemClasses,
onTouchStart: preload,
onMouseEnter: preload,
disabled: disabled,
};
return url ? (
<a { ...attributes } href={ url } ref={ ref as LegacyRef< HTMLAnchorElement > }>
{ renderChildren() }
</a>
) : (
<button { ...attributes } ref={ ref as LegacyRef< HTMLButtonElement > }>
{ renderChildren() }
</button>
);
}
);
export default SidebarMenuItem;
|