import { mergeProps, useRender } from '@base-ui/react'; import clsx from 'clsx'; import { useIsomorphicLayoutEffect, useMergeRefs } from '@wordpress/compose'; import { Children, forwardRef, isValidElement, useCallback, useMemo, useRef, useState, } from '@wordpress/element'; import { __, _n, sprintf } from '@wordpress/i18n'; import type { ReactElement, ReactNode } from 'react'; import { inertValue } from '@wordpress/react-inert-value'; import * as Menu from '../menu'; import type { RootProps as MenuRootProps } from '../menu/types'; import * as Tooltip from '../tooltip'; import defenseStyles from '../utils/css/global-css-defense.module.css'; import resetStyles from '../utils/css/resets.module.css'; import { BreadcrumbItemRenderContext } from './context'; import { ButtonItem } from './button-item'; import { CurrentItem } from './current-item'; import { enforceRenderProps } from './enforce-render-props'; import { Item } from './item'; import { getCollapsedLayout } from './layout'; import { LinkItem } from './link-item'; import { OverflowTriggerButton } from './overflow-trigger-button'; import { Separator } from './separator'; import styles from './style.module.css'; import type { ButtonItemProps, CurrentItemProps, LinkItemProps, RootProps, } from './types'; type BreadcrumbItemDescriptor = { element: ReactElement< LinkItemProps | ButtonItemProps | CurrentItemProps >; itemKey: string; kind: 'link' | 'button' | 'current'; }; type ResponsiveState = { collapsedKeys: string[]; shouldTruncateCurrent: boolean; }; const FULL_TRAIL_STATE: ResponsiveState = { collapsedKeys: [], shouldTruncateCurrent: false, }; function validateNestedArrayKeys( children: ReactNode ) { if ( ! Array.isArray( children ) ) { return; } for ( const child of children ) { if ( ! Array.isArray( child ) ) { continue; } for ( const arrayChild of child ) { if ( isValidElement( arrayChild ) && arrayChild.key === null ) { throw new Error( 'Breadcrumb: Items rendered from an array need stable React keys.' ); } } validateNestedArrayKeys( child ); } } function getBreadcrumbItems( children: ReactNode ) { if ( process.env.NODE_ENV !== 'production' ) { validateNestedArrayKeys( children ); } const childArray = Children.toArray( children ); const items: BreadcrumbItemDescriptor[] = []; childArray.forEach( ( child, index ) => { if ( ! isValidElement< LinkItemProps | ButtonItemProps | CurrentItemProps >( child ) ) { if ( process.env.NODE_ENV !== 'production' ) { throw new Error( 'Breadcrumb: only accepts , , and as direct children.' ); } return; } let kind: BreadcrumbItemDescriptor[ 'kind' ] | undefined; if ( child.type === LinkItem ) { kind = 'link'; } else if ( child.type === ButtonItem ) { kind = 'button'; } else if ( child.type === CurrentItem ) { kind = 'current'; } if ( ! kind ) { if ( process.env.NODE_ENV !== 'production' ) { throw new Error( 'Breadcrumb: only accepts , , and as direct children.' ); } return; } const label = child.props.children; if ( typeof label !== 'string' || ! label.trim() ) { if ( process.env.NODE_ENV !== 'production' ) { throw new Error( `Breadcrumb: requires a non-empty text label.` ); } return; } if ( kind === 'link' && ( typeof ( child.props as LinkItemProps ).href !== 'string' || ! ( child.props as LinkItemProps ).href.trim() ) ) { if ( process.env.NODE_ENV !== 'production' ) { throw new Error( 'Breadcrumb: requires a usable `href`.' ); } return; } items.push( { element: child, itemKey: String( child.key ?? `item-${ index }` ), kind, } ); } ); if ( process.env.NODE_ENV !== 'production' ) { const linkItems = items.filter( ( item ) => item.kind === 'link' ); const currentItems = items.filter( ( item ) => item.kind === 'current' ); if ( linkItems.length > 0 && items.some( ( item ) => item.kind === 'button' ) ) { throw new Error( 'Breadcrumb: Ancestors must all be LinkItem or all be ButtonItem. Mixed trails are not supported.' ); } if ( currentItems.length === 0 ) { throw new Error( 'Breadcrumb: requires one final .' ); } if ( currentItems.length > 1 ) { throw new Error( 'Breadcrumb: accepts exactly one .' ); } if ( items.at( -1 )?.kind !== 'current' ) { throw new Error( 'Breadcrumb: must be the final child of .' ); } } return items; } function responsiveStatesAreEqual( current: ResponsiveState, next: ResponsiveState ) { return ( current.shouldTruncateCurrent === next.shouldTruncateCurrent && current.collapsedKeys.length === next.collapsedKeys.length && current.collapsedKeys.every( ( itemKey, index ) => itemKey === next.collapsedKeys[ index ] ) ); } function itemKeysAreEqual( current: BreadcrumbItemDescriptor[], next: BreadcrumbItemDescriptor[] ) { return ( current.length === next.length && current.every( ( item, index ) => item.itemKey === next[ index ].itemKey && item.kind === next[ index ].kind ) ); } function getContentBoxInlineSize( element: HTMLElement ) { const computedStyles = getComputedStyle( element ); const shorthandValues = computedStyles.paddingInline .split( /\s+/ ) .map( ( value ) => Number.parseFloat( value ) ) .filter( Number.isFinite ); const shorthandStart = shorthandValues[ 0 ] ?? 0; const shorthandEnd = shorthandValues[ 1 ] ?? shorthandStart; const paddingInlineStart = Number.parseFloat( computedStyles.paddingInlineStart ) || Number.parseFloat( computedStyles.paddingLeft ) || shorthandStart; const paddingInlineEnd = Number.parseFloat( computedStyles.paddingInlineEnd ) || Number.parseFloat( computedStyles.paddingRight ) || shorthandEnd; const paddingBoxWidth = element.clientWidth || element.getBoundingClientRect().width; return Math.max( 0, paddingBoxWidth - paddingInlineStart - paddingInlineEnd ); } /** * Renders a labelled page-navigation landmark or hierarchy-selection list. * Automatically moves ancestors that do not fit into an accessible overflow menu. * * ```jsx * * Dashboard * Settings * * ``` */ const Root = forwardRef< HTMLElement, RootProps >( function BreadcrumbRoot( { 'aria-label': ariaLabel, 'aria-labelledby': ariaLabelledBy, children, className, render, role: _role, ...props }, forwardedRef ) { const items = useMemo( () => getBreadcrumbItems( children ), [ children ] ); const ancestorItems = useMemo( () => items.filter( ( item ) => item.kind !== 'current' ), [ items ] ); const currentItem = useMemo( () => items.find( ( item ) => item.kind === 'current' ), [ items ] ); const currentAriaCurrent = currentItem && 'aria-current' in currentItem.element.props ? currentItem.element.props[ 'aria-current' ] : undefined; const variant = ancestorItems[ 0 ]?.kind === 'button' || ( ancestorItems.length === 0 && ( currentAriaCurrent === true || currentAriaCurrent === 'true' ) ) ? 'selection' : 'navigation'; const hasAriaLabel = typeof ariaLabel === 'string' && ariaLabel.trim().length > 0; const hasAriaLabelledBy = typeof ariaLabelledBy === 'string' && ariaLabelledBy.trim().length > 0; const resolvedAriaLabel = hasAriaLabel || hasAriaLabelledBy ? ariaLabel : __( 'Breadcrumbs' ); const [ rootElement, setRootElement ] = useState< HTMLElement | null >( null ); const [ responsiveState, setResponsiveState ] = useState< ResponsiveState >( FULL_TRAIL_STATE ); const [ measurementVersion, setMeasurementVersion ] = useState( 0 ); const [ menuOpen, setMenuOpen ] = useState( false ); const [ pinnedItemKey, setPinnedItemKey ] = useState< string | null >( null ); const [ isOverflowTriggerFocused, setIsOverflowTriggerFocused ] = useState( false ); const [ frozenItems, setFrozenItems ] = useState( items ); const mergedRootRef = useMergeRefs( [ forwardedRef, setRootElement ] ); const visibleListRef = useRef< HTMLOListElement | null >( null ); const intrinsicRowRef = useRef< HTMLDivElement | null >( null ); const intrinsicItemRefs = useRef( new Map< string, HTMLSpanElement >() ); const intrinsicSeparatorRef = useRef< HTMLSpanElement | null >( null ); const intrinsicOverflowTriggerRef = useRef< HTMLSpanElement | null >( null ); const activationFocusRef = useRef< HTMLElement | null >( null ); const menuPopupRef = useRef< HTMLDivElement | null >( null ); const currentItemRef = useRef< HTMLSpanElement | null >( null ); const focusedElementRef = useRef< HTMLElement | null >( null ); const overflowTriggerRef = useRef< HTMLButtonElement | null >( null ); const pendingStateRef = useRef< ResponsiveState | null >( null ); const focusOverflowAfterLayoutRef = useRef( false ); const menuOpenRef = useRef( false ); const selectionChanged = ( variant === 'selection' || frozenItems.some( ( item ) => item.kind === 'button' ) ) && ! itemKeysAreEqual( frozenItems, items ); const focusCurrentItem = useCallback( () => { const current = currentItemRef.current; if ( current ) { current.tabIndex = -1; current.focus(); } }, [] ); useIsomorphicLayoutEffect( () => { if ( selectionChanged ) { setMenuOpen( false ); menuOpenRef.current = false; setIsOverflowTriggerFocused( false ); setFrozenItems( items ); } const focused = focusedElementRef.current; if ( focused && ! focused.isConnected && focused.ownerDocument.activeElement === focused.ownerDocument.body ) { focusCurrentItem(); } } ); const applyResponsiveState = useCallback( ( next: ResponsiveState ) => { if ( menuOpen && ! selectionChanged ) { pendingStateRef.current = next; return; } if ( isOverflowTriggerFocused && ! selectionChanged && ( next.collapsedKeys.length === 0 || ! itemKeysAreEqual( frozenItems, items ) ) ) { pendingStateRef.current = next; return; } pendingStateRef.current = null; setResponsiveState( ( current ) => responsiveStatesAreEqual( current, next ) ? current : next ); }, [ frozenItems, isOverflowTriggerFocused, items, menuOpen, selectionChanged, ] ); useIsomorphicLayoutEffect( () => { if ( ! rootElement || ! intrinsicRowRef.current ) { return; } if ( typeof ResizeObserver !== 'function' ) { applyResponsiveState( FULL_TRAIL_STATE ); return; } let isActive = true; let animationFrame: number | undefined; const measureElement = ( element: HTMLElement | null ) => { if ( ! element ) { return 0; } return Math.max( element.getBoundingClientRect().width, element.scrollWidth ); }; const measure = () => { if ( ! isActive ) { return; } const availableWidth = visibleListRef.current ? getContentBoxInlineSize( visibleListRef.current ) : rootElement.clientWidth || rootElement.getBoundingClientRect().width; const currentItemWidth = currentItem ? measureElement( intrinsicItemRefs.current.get( currentItem.itemKey ) ?? null ) : 0; const linkItemWidths = ancestorItems.map( ( item ) => measureElement( intrinsicItemRefs.current.get( item.itemKey ) ?? null ) ); const pinnedIndex = pinnedItemKey ? ancestorItems.findIndex( ( item ) => item.itemKey === pinnedItemKey ) : undefined; const nextLayout = getCollapsedLayout( { availableWidth, currentItemWidth, linkItemWidths, overflowTriggerWidth: measureElement( intrinsicOverflowTriggerRef.current ), separatorWidth: measureElement( intrinsicSeparatorRef.current ), }, pinnedIndex === -1 ? undefined : pinnedIndex ); const nextState = { collapsedKeys: nextLayout.collapsedIndices.map( ( index ) => ancestorItems[ index ].itemKey ), shouldTruncateCurrent: nextLayout.shouldTruncateCurrent, }; if ( nextLayout.shouldMoveFocusToOverflow ) { focusOverflowAfterLayoutRef.current = true; setPinnedItemKey( null ); } setMeasurementVersion( ( current ) => current + 1 ); applyResponsiveState( nextState ); }; const scheduleMeasurement = () => { if ( animationFrame !== undefined ) { return; } animationFrame = requestAnimationFrame( () => { animationFrame = undefined; measure(); } ); }; const resizeObserver = new ResizeObserver( scheduleMeasurement ); resizeObserver.observe( rootElement ); if ( visibleListRef.current ) { resizeObserver.observe( visibleListRef.current ); } resizeObserver.observe( intrinsicRowRef.current ); for ( const itemElement of intrinsicItemRefs.current.values() ) { resizeObserver.observe( itemElement ); } if ( intrinsicSeparatorRef.current ) { resizeObserver.observe( intrinsicSeparatorRef.current ); } if ( intrinsicOverflowTriggerRef.current ) { resizeObserver.observe( intrinsicOverflowTriggerRef.current ); } measure(); if ( document.fonts ) { document.fonts.ready.then( scheduleMeasurement ); } return () => { isActive = false; resizeObserver.disconnect(); if ( animationFrame !== undefined ) { cancelAnimationFrame( animationFrame ); } }; }, [ applyResponsiveState, children, currentItem, ancestorItems, pinnedItemKey, props.dir, rootElement, ] ); useIsomorphicLayoutEffect( () => { if ( focusOverflowAfterLayoutRef.current && responsiveState.collapsedKeys.length > 0 && overflowTriggerRef.current ) { focusOverflowAfterLayoutRef.current = false; overflowTriggerRef.current.focus(); } }, [ responsiveState.collapsedKeys ] ); const applyPendingResponsiveState = useCallback( () => { if ( ! pendingStateRef.current ) { return; } const pendingState = pendingStateRef.current; pendingStateRef.current = null; setResponsiveState( pendingState ); }, [] ); const handleMenuOpenChange = useCallback( ( open: boolean, eventDetails: Parameters< NonNullable< MenuRootProps[ 'onOpenChange' ] > >[ 1 ] ) => { menuOpenRef.current = open; if ( ! open && eventDetails.reason === 'item-press' ) { // Menu's click handling focuses the item after consumer handlers. // Restore an intentional focus move before Menu returns to its trigger. // Upstream: https://github.com/mui/base-ui/issues/5930 activationFocusRef.current?.focus(); activationFocusRef.current = null; } if ( ! open && variant === 'selection' && rootElement ) { // Menu cleanup can run before the consumer's activation handler. // Resolve focus after that handler has had a chance to move it. const ownerDocument = rootElement.ownerDocument; queueMicrotask( () => { const active = ownerDocument.activeElement; if ( active === ownerDocument.body || ( active && menuPopupRef.current?.contains( active ) ) ) { if ( overflowTriggerRef.current ) { overflowTriggerRef.current.focus(); } else { focusCurrentItem(); } } } ); } if ( open ) { setFrozenItems( items ); activationFocusRef.current = null; } else if ( eventDetails.reason !== 'escape-key' && eventDetails.reason !== 'trigger-press' ) { setIsOverflowTriggerFocused( false ); applyPendingResponsiveState(); } setMenuOpen( open ); }, [ applyPendingResponsiveState, focusCurrentItem, items, rootElement, variant, ] ); const handleOverflowTriggerBlur = useCallback( () => { if ( menuOpenRef.current ) { return; } setIsOverflowTriggerFocused( false ); applyPendingResponsiveState(); }, [ applyPendingResponsiveState ] ); const displayedItems = variant !== 'selection' && ! selectionChanged && ( menuOpen || isOverflowTriggerFocused ) ? frozenItems : items; const displayedAncestors = displayedItems.filter( ( item ) => item.kind !== 'current' ); const displayedCurrentItem = displayedItems.find( ( item ) => item.kind === 'current' ); const collapsedKeySet = new Set( responsiveState.collapsedKeys ); const collapsedItems = displayedAncestors.filter( ( item ) => collapsedKeySet.has( item.itemKey ) ); const visibleAncestors = displayedAncestors.filter( ( item ) => ! collapsedKeySet.has( item.itemKey ) ); const overflowLabel = collapsedItems.length ? sprintf( /* translators: %d: number of breadcrumb ancestors hidden in the overflow menu. */ _n( 'Show %d hidden breadcrumb item', 'Show %d hidden breadcrumb items', collapsedItems.length ), collapsedItems.length ) : ''; let visiblePosition = 0; const renderVisibleItem = ( item: BreadcrumbItemDescriptor ) => { const showSeparator = visiblePosition > 0; visiblePosition++; return ( setPinnedItemKey( ( current ) => current === itemKey ? null : current ), onLinkFocus: setPinnedItemKey, showSeparator, shouldTruncateCurrent: responsiveState.shouldTruncateCurrent, } } > { item.element } ); }; const rootAncestor = visibleAncestors.find( ( item ) => item.itemKey === displayedAncestors[ 0 ]?.itemKey ); const remainingVisibleAncestors = rootAncestor ? visibleAncestors.filter( ( item ) => item !== rootAncestor ) : visibleAncestors; const visibleListContent = ( <> { rootAncestor && renderVisibleItem( rootAncestor ) } { collapsedItems.length > 0 && ( { visiblePosition++ > 0 && } { if ( ! menuOpen && ! isOverflowTriggerFocused ) { setFrozenItems( items ); } setIsOverflowTriggerFocused( true ); } } render={ } /> } > { overflowLabel } { focusedElementRef.current = event.target as HTMLElement; } } ref={ menuPopupRef } finalFocus={ variant === 'selection' ? false : undefined } > { collapsedItems.map( ( item ) => ( { activationFocusRef.current = target; }, onLinkBlur: () => {}, onLinkFocus: () => {}, showSeparator: false, shouldTruncateCurrent: false, } } > { item.element } ) ) } ) } { remainingVisibleAncestors.map( renderVisibleItem ) } { displayedCurrentItem && renderVisibleItem( displayedCurrentItem ) } ); const componentContent = ( <> { /* eslint-disable-next-line jsx-a11y/no-redundant-roles -- Safari needs an explicit list role when list markers are hidden outside a nav element. */ }
    { visibleListContent }
); const enforcedRender = useMemo( () => enforceRenderProps( render, { 'aria-label': variant === 'navigation' ? resolvedAriaLabel : undefined, 'aria-labelledby': variant === 'navigation' && hasAriaLabelledBy ? ariaLabelledBy : undefined, role: variant === 'navigation' ? 'navigation' : undefined, } ), [ ariaLabelledBy, hasAriaLabelledBy, render, resolvedAriaLabel, variant, ] ); const root = useRender( { render: enforcedRender, defaultTagName: variant === 'selection' ? 'div' : 'nav', ref: mergedRootRef, props: mergeProps< 'nav' >( props, { 'aria-label': variant === 'navigation' ? resolvedAriaLabel : undefined, 'aria-labelledby': variant === 'navigation' && hasAriaLabelledBy ? ariaLabelledBy : undefined, children: componentContent, onFocusCapture: ( event ) => { focusedElementRef.current = event.target as HTMLElement; }, className: clsx( resetStyles[ 'box-sizing' ], styles.root, className ), role: variant === 'navigation' ? 'navigation' : undefined, } ), } ); return root; } ); Root.displayName = 'Breadcrumb.Root'; export { Root };