@ryvora/react-menu
Version:
🍽️ The engine for interactive menus in React. Handles selection, navigation, and open state!
4 lines • 72.9 kB
Source Map (JSON)
{
"version": 3,
"sources": ["../src/menu.tsx"],
"sourcesContent": ["import * as React from 'react';\nimport { composeEventHandlers } from '@ryvora/primitive';\nimport { createCollection } from '@ryvora/react-collection';\nimport { useComposedRefs, composeRefs } from '@ryvora/react-compose-refs';\nimport { createContextScope } from '@ryvora/react-context';\nimport { useDirection } from '@ryvora/react-direction';\nimport { DismissableLayer } from '@ryvora/react-dismissable-layer';\nimport { useFocusGuards } from '@ryvora/react-focus-guards';\nimport { FocusScope } from '@ryvora/react-focus-scope';\nimport { useId } from '@ryvora/react-id';\nimport * as PopperPrimitive from '@ryvora/react-popper';\nimport { createPopperScope } from '@ryvora/react-popper';\nimport { Portal as PortalPrimitive } from '@ryvora/react-portal';\nimport { Presence } from '@ryvora/react-presence';\nimport { Primitive, dispatchDiscreteCustomEvent } from '@ryvora/react-primitive';\nimport * as RovingFocusGroup from '@ryvora/react-roving-focus';\nimport { createRovingFocusGroupScope } from '@ryvora/react-roving-focus';\nimport { createSlot } from '@ryvora/react-slot';\nimport { useCallbackRef } from '@ryvora/react-use-callback-ref';\nimport { hideOthers } from 'aria-hidden';\nimport { RemoveScroll } from 'react-remove-scroll';\n\nimport type { Scope } from '@ryvora/react-context';\n\ntype Direction = 'ltr' | 'rtl';\n\nconst SELECTION_KEYS = ['Enter', ' '];\nconst FIRST_KEYS = ['ArrowDown', 'PageUp', 'Home'];\nconst LAST_KEYS = ['ArrowUp', 'PageDown', 'End'];\nconst FIRST_LAST_KEYS = [...FIRST_KEYS, ...LAST_KEYS];\nconst SUB_OPEN_KEYS: Record<Direction, string[]> = {\n ltr: [...SELECTION_KEYS, 'ArrowRight'],\n rtl: [...SELECTION_KEYS, 'ArrowLeft'],\n};\nconst SUB_CLOSE_KEYS: Record<Direction, string[]> = {\n ltr: ['ArrowLeft'],\n rtl: ['ArrowRight'],\n};\n\n/** ----------------------------------------- Menu ----------------------------------------- */\n\nconst MENU_NAME = 'Menu';\n\ntype ItemData = { disabled: boolean; textValue: string };\nconst [Collection, useCollection, createCollectionScope] = createCollection<\n MenuItemElement,\n ItemData\n>(MENU_NAME);\n\ntype ScopedProps<P> = P & { __scopeMenu?: Scope };\nconst [createMenuContext, createMenuScope] = createContextScope(MENU_NAME, [\n createCollectionScope,\n createPopperScope,\n createRovingFocusGroupScope,\n]);\nconst usePopperScope = createPopperScope();\nconst useRovingFocusGroupScope = createRovingFocusGroupScope();\n\ntype MenuContextValue = {\n open: boolean;\n onOpenChange(open: boolean): void;\n content: MenuContentElement | null;\n onContentChange(content: MenuContentElement | null): void;\n};\n\nconst [MenuProvider, useMenuContext] = createMenuContext<MenuContextValue>(MENU_NAME);\n\ntype MenuRootContextValue = {\n onClose(): void;\n isUsingKeyboardRef: React.RefObject<boolean>;\n dir: Direction;\n modal: boolean;\n};\n\nconst [MenuRootProvider, useMenuRootContext] = createMenuContext<MenuRootContextValue>(MENU_NAME);\n\ninterface MenuProps {\n children?: React.ReactNode;\n open?: boolean;\n onOpenChange?(open: boolean): void;\n dir?: Direction;\n modal?: boolean;\n}\n\nconst Menu: React.FC<MenuProps> = (props: ScopedProps<MenuProps>) => {\n const { __scopeMenu, open = false, children, dir, onOpenChange, modal = true } = props;\n const popperScope = usePopperScope(__scopeMenu);\n const [content, setContent] = React.useState<MenuContentElement | null>(null);\n const isUsingKeyboardRef = React.useRef(false);\n const handleOpenChange = useCallbackRef(onOpenChange);\n const direction = useDirection(dir);\n\n React.useEffect(() => {\n // Capture phase ensures we set the boolean before any side effects execute\n // in response to the key or pointer event as they might depend on this value.\n const handleKeyDown = () => {\n isUsingKeyboardRef.current = true;\n document.addEventListener('pointerdown', handlePointer, { capture: true, once: true });\n document.addEventListener('pointermove', handlePointer, { capture: true, once: true });\n };\n const handlePointer = () => (isUsingKeyboardRef.current = false);\n document.addEventListener('keydown', handleKeyDown, { capture: true });\n return () => {\n document.removeEventListener('keydown', handleKeyDown, { capture: true });\n document.removeEventListener('pointerdown', handlePointer, { capture: true });\n document.removeEventListener('pointermove', handlePointer, { capture: true });\n };\n }, []);\n\n return (\n <PopperPrimitive.Root {...popperScope}>\n <MenuProvider\n scope={__scopeMenu}\n open={open}\n onOpenChange={handleOpenChange}\n content={content}\n onContentChange={setContent}\n >\n <MenuRootProvider\n scope={__scopeMenu}\n onClose={React.useCallback(() => handleOpenChange(false), [handleOpenChange])}\n isUsingKeyboardRef={isUsingKeyboardRef}\n dir={direction}\n modal={modal}\n >\n {children}\n </MenuRootProvider>\n </MenuProvider>\n </PopperPrimitive.Root>\n );\n};\n\nMenu.displayName = MENU_NAME;\n\n/** ----------------------------------------- Menu Anchor ----------------------------------------- */\n\nconst ANCHOR_NAME = 'MenuAnchor';\n\ntype MenuAnchorElement = React.ComponentRef<typeof PopperPrimitive.Anchor>;\ntype PopperAnchorProps = React.ComponentPropsWithoutRef<typeof PopperPrimitive.Anchor>;\ninterface MenuAnchorProps extends PopperAnchorProps {}\n\nconst MenuAnchor = React.forwardRef<MenuAnchorElement, MenuAnchorProps>(\n (props: ScopedProps<MenuAnchorProps>, forwardedRef) => {\n const { __scopeMenu, ...anchorProps } = props;\n const popperScope = usePopperScope(__scopeMenu);\n return <PopperPrimitive.Anchor {...popperScope} {...anchorProps} ref={forwardedRef} />;\n }\n);\n\nMenuAnchor.displayName = ANCHOR_NAME;\n\n/** ----------------------------------------- Menu Portal ----------------------------------------- */\n\nconst PORTAL_NAME = 'MenuPortal';\n\ntype PortalContextValue = { forceMount?: true };\nconst [PortalProvider, usePortalContext] = createMenuContext<PortalContextValue>(PORTAL_NAME, {\n forceMount: undefined,\n});\n\ntype PortalProps = React.ComponentPropsWithoutRef<typeof PortalPrimitive>;\ninterface MenuPortalProps {\n children?: React.ReactNode;\n /**\n * Specify a container element to portal the content into.\n */\n container?: PortalProps['container'];\n /**\n * Used to force mounting when more control is needed. Useful when\n * controlling animation with React animation libraries.\n */\n forceMount?: true;\n}\n\nconst MenuPortal: React.FC<MenuPortalProps> = (props: ScopedProps<MenuPortalProps>) => {\n const { __scopeMenu, forceMount, children, container } = props;\n const context = useMenuContext(PORTAL_NAME, __scopeMenu);\n return (\n <PortalProvider scope={__scopeMenu} forceMount={forceMount}>\n <Presence present={forceMount || context.open}>\n <PortalPrimitive asChild container={container}>\n {children}\n </PortalPrimitive>\n </Presence>\n </PortalProvider>\n );\n};\n\nMenuPortal.displayName = PORTAL_NAME;\n\n/** ----------------------------------------- Menu Content ----------------------------------------- */\n\nconst CONTENT_NAME = 'MenuContent';\n\ntype MenuContentContextValue = {\n onItemEnter(event: React.PointerEvent): void;\n onItemLeave(event: React.PointerEvent): void;\n onTriggerLeave(event: React.PointerEvent): void;\n searchRef: React.RefObject<string>;\n pointerGraceTimerRef: React.MutableRefObject<number>;\n onPointerGraceIntentChange(intent: GraceIntent | null): void;\n};\nconst [MenuContentProvider, useMenuContentContext] =\n createMenuContext<MenuContentContextValue>(CONTENT_NAME);\n\ntype MenuContentElement = MenuRootContentTypeElement;\n/**\n * We purposefully don't union MenuRootContent and MenuSubContent props here because\n * they have conflicting prop types. We agreed that we would allow MenuSubContent to\n * accept props that it would just ignore.\n */\ninterface MenuContentProps extends MenuRootContentTypeProps {\n /**\n * Used to force mounting when more control is needed. Useful when\n * controlling animation with React animation libraries.\n */\n forceMount?: true;\n}\n\nconst MenuContent = React.forwardRef<MenuContentElement, MenuContentProps>(\n (props: ScopedProps<MenuContentProps>, forwardedRef) => {\n const portalContext = usePortalContext(CONTENT_NAME, props.__scopeMenu);\n const { forceMount = portalContext.forceMount, ...contentProps } = props;\n const context = useMenuContext(CONTENT_NAME, props.__scopeMenu);\n const rootContext = useMenuRootContext(CONTENT_NAME, props.__scopeMenu);\n\n return (\n <Collection.Provider scope={props.__scopeMenu}>\n <Presence present={forceMount || context.open}>\n <Collection.Slot scope={props.__scopeMenu}>\n {rootContext.modal ? (\n <MenuRootContentModal {...contentProps} ref={forwardedRef} />\n ) : (\n <MenuRootContentNonModal {...contentProps} ref={forwardedRef} />\n )}\n </Collection.Slot>\n </Presence>\n </Collection.Provider>\n );\n }\n);\n\n/** ---------------------------------------------------------------------------------- */\n\ntype MenuRootContentTypeElement = MenuContentImplElement;\ninterface MenuRootContentTypeProps\n extends Omit<MenuContentImplProps, keyof MenuContentImplPrivateProps> {}\n\nconst MenuRootContentModal = React.forwardRef<MenuRootContentTypeElement, MenuRootContentTypeProps>(\n (props: ScopedProps<MenuRootContentTypeProps>, forwardedRef) => {\n const context = useMenuContext(CONTENT_NAME, props.__scopeMenu);\n const ref = React.useRef<MenuRootContentTypeElement>(null);\n const composedRefs = useComposedRefs(forwardedRef, ref);\n\n // Hide everything from ARIA except the `MenuContent`\n React.useEffect(() => {\n const content = ref.current;\n if (content) return hideOthers(content);\n }, []);\n\n return (\n <MenuContentImpl\n {...props}\n ref={composedRefs}\n // we make sure we're not trapping once it's been closed\n // (closed !== unmounted when animating out)\n trapFocus={context.open}\n // make sure to only disable pointer events when open\n // this avoids blocking interactions while animating out\n disableOutsidePointerEvents={context.open}\n disableOutsideScroll\n // When focus is trapped, a `focusout` event may still happen.\n // We make sure we don't trigger our `onDismiss` in such case.\n onFocusOutside={composeEventHandlers(\n props.onFocusOutside,\n (event) => event.preventDefault(),\n { checkForDefaultPrevented: false }\n )}\n onDismiss={() => context.onOpenChange(false)}\n />\n );\n }\n);\n\nconst MenuRootContentNonModal = React.forwardRef<\n MenuRootContentTypeElement,\n MenuRootContentTypeProps\n>((props: ScopedProps<MenuRootContentTypeProps>, forwardedRef) => {\n const context = useMenuContext(CONTENT_NAME, props.__scopeMenu);\n return (\n <MenuContentImpl\n {...props}\n ref={forwardedRef}\n trapFocus={false}\n disableOutsidePointerEvents={false}\n disableOutsideScroll={false}\n onDismiss={() => context.onOpenChange(false)}\n />\n );\n});\n\n/** ---------------------------------------------------------------------------------- */\n\ntype MenuContentImplElement = React.ComponentRef<typeof PopperPrimitive.Content>;\ntype FocusScopeProps = React.ComponentPropsWithoutRef<typeof FocusScope>;\ntype DismissableLayerProps = React.ComponentPropsWithoutRef<typeof DismissableLayer>;\ntype RovingFocusGroupProps = React.ComponentPropsWithoutRef<typeof RovingFocusGroup.Root>;\ntype PopperContentProps = React.ComponentPropsWithoutRef<typeof PopperPrimitive.Content>;\ntype MenuContentImplPrivateProps = {\n onOpenAutoFocus?: FocusScopeProps['onMountAutoFocus'];\n onDismiss?: DismissableLayerProps['onDismiss'];\n disableOutsidePointerEvents?: DismissableLayerProps['disableOutsidePointerEvents'];\n\n /**\n * Whether scrolling outside the `MenuContent` should be prevented\n * (default: `false`)\n */\n disableOutsideScroll?: boolean;\n\n /**\n * Whether focus should be trapped within the `MenuContent`\n * (default: false)\n */\n trapFocus?: FocusScopeProps['trapped'];\n};\ninterface MenuContentImplProps\n extends MenuContentImplPrivateProps,\n Omit<PopperContentProps, 'dir' | 'onPlaced'> {\n /**\n * Event handler called when auto-focusing on close.\n * Can be prevented.\n */\n onCloseAutoFocus?: FocusScopeProps['onUnmountAutoFocus'];\n\n /**\n * Whether keyboard navigation should loop around\n * @defaultValue false\n */\n loop?: RovingFocusGroupProps['loop'];\n\n onEntryFocus?: RovingFocusGroupProps['onEntryFocus'];\n onEscapeKeyDown?: DismissableLayerProps['onEscapeKeyDown'];\n onPointerDownOutside?: DismissableLayerProps['onPointerDownOutside'];\n onFocusOutside?: DismissableLayerProps['onFocusOutside'];\n onInteractOutside?: DismissableLayerProps['onInteractOutside'];\n}\n\nconst Slot = createSlot('MenuContent.ScrollLock');\n\nconst MenuContentImpl = React.forwardRef<MenuContentImplElement, MenuContentImplProps>(\n (props: ScopedProps<MenuContentImplProps>, forwardedRef) => {\n const {\n __scopeMenu,\n loop = false,\n trapFocus,\n onOpenAutoFocus,\n onCloseAutoFocus,\n disableOutsidePointerEvents,\n onEntryFocus,\n onEscapeKeyDown,\n onPointerDownOutside,\n onFocusOutside,\n onInteractOutside,\n onDismiss,\n disableOutsideScroll,\n ...contentProps\n } = props;\n const context = useMenuContext(CONTENT_NAME, __scopeMenu);\n const rootContext = useMenuRootContext(CONTENT_NAME, __scopeMenu);\n const popperScope = usePopperScope(__scopeMenu);\n const rovingFocusGroupScope = useRovingFocusGroupScope(__scopeMenu);\n const getItems = useCollection(__scopeMenu);\n const [currentItemId, setCurrentItemId] = React.useState<string | null>(null);\n const contentRef = React.useRef<HTMLDivElement>(null);\n const composedRefs = useComposedRefs(forwardedRef, contentRef, context.onContentChange);\n const timerRef = React.useRef(0);\n const searchRef = React.useRef('');\n const pointerGraceTimerRef = React.useRef(0);\n const pointerGraceIntentRef = React.useRef<GraceIntent | null>(null);\n const pointerDirRef = React.useRef<Side>('right');\n const lastPointerXRef = React.useRef(0);\n\n const ScrollLockWrapper = disableOutsideScroll ? RemoveScroll : React.Fragment;\n const scrollLockWrapperProps = disableOutsideScroll\n ? { as: Slot, allowPinchZoom: true }\n : undefined;\n\n const handleTypeaheadSearch = (key: string) => {\n const search = searchRef.current + key;\n const items = getItems().filter((item) => !item.disabled);\n const currentItem = document.activeElement;\n const currentMatch = items.find((item) => item.ref.current === currentItem)?.textValue;\n const values = items.map((item) => item.textValue);\n const nextMatch = getNextMatch(values, search, currentMatch);\n const newItem = items.find((item) => item.textValue === nextMatch)?.ref.current;\n\n // Reset `searchRef` 1 second after it was last updated\n (function updateSearch(value: string) {\n searchRef.current = value;\n window.clearTimeout(timerRef.current);\n if (value !== '') timerRef.current = window.setTimeout(() => updateSearch(''), 1000);\n })(search);\n\n if (newItem) {\n /**\n * Imperative focus during keydown is risky so we prevent React's batching updates\n * to avoid potential bugs. See: https://github.com/facebook/react/issues/20332\n */\n setTimeout(() => (newItem as HTMLElement).focus());\n }\n };\n\n React.useEffect(() => {\n return () => window.clearTimeout(timerRef.current);\n }, []);\n\n // Make sure the whole tree has focus guards as our `MenuContent` may be\n // the last element in the DOM (because of the `Portal`)\n useFocusGuards();\n\n const isPointerMovingToSubmenu = React.useCallback((event: React.PointerEvent) => {\n const isMovingTowards = pointerDirRef.current === pointerGraceIntentRef.current?.side;\n return isMovingTowards && isPointerInGraceArea(event, pointerGraceIntentRef.current?.area);\n }, []);\n\n return (\n <MenuContentProvider\n scope={__scopeMenu}\n searchRef={searchRef}\n onItemEnter={React.useCallback(\n (event) => {\n if (isPointerMovingToSubmenu(event)) event.preventDefault();\n },\n [isPointerMovingToSubmenu]\n )}\n onItemLeave={React.useCallback(\n (event) => {\n if (isPointerMovingToSubmenu(event)) return;\n contentRef.current?.focus();\n setCurrentItemId(null);\n },\n [isPointerMovingToSubmenu]\n )}\n onTriggerLeave={React.useCallback(\n (event) => {\n if (isPointerMovingToSubmenu(event)) event.preventDefault();\n },\n [isPointerMovingToSubmenu]\n )}\n pointerGraceTimerRef={pointerGraceTimerRef}\n onPointerGraceIntentChange={React.useCallback((intent) => {\n pointerGraceIntentRef.current = intent;\n }, [])}\n >\n <ScrollLockWrapper {...scrollLockWrapperProps}>\n <FocusScope\n asChild\n trapped={trapFocus}\n onMountAutoFocus={composeEventHandlers(onOpenAutoFocus, (event) => {\n // when opening, explicitly focus the content area only and leave\n // `onEntryFocus` in control of focusing first item\n event.preventDefault();\n contentRef.current?.focus({ preventScroll: true });\n })}\n onUnmountAutoFocus={onCloseAutoFocus}\n >\n <DismissableLayer\n asChild\n disableOutsidePointerEvents={disableOutsidePointerEvents}\n onEscapeKeyDown={onEscapeKeyDown}\n onPointerDownOutside={onPointerDownOutside}\n onFocusOutside={onFocusOutside}\n onInteractOutside={onInteractOutside}\n onDismiss={onDismiss}\n >\n <RovingFocusGroup.Root\n asChild\n {...rovingFocusGroupScope}\n dir={rootContext.dir}\n orientation=\"vertical\"\n loop={loop}\n currentTabStopId={currentItemId}\n onCurrentTabStopIdChange={setCurrentItemId}\n onEntryFocus={composeEventHandlers(onEntryFocus, (event) => {\n // only focus first item when using keyboard\n if (!rootContext.isUsingKeyboardRef.current) event.preventDefault();\n })}\n preventScrollOnEntryFocus\n >\n <PopperPrimitive.Content\n role=\"menu\"\n aria-orientation=\"vertical\"\n data-state={getOpenState(context.open)}\n data-ryvora-menu-content=\"\"\n dir={rootContext.dir}\n {...popperScope}\n {...contentProps}\n ref={composedRefs}\n style={{ outline: 'none', ...contentProps.style }}\n onKeyDown={composeEventHandlers(contentProps.onKeyDown, (event) => {\n // submenu key events bubble through portals. We only care about keys in this menu.\n const target = event.target as HTMLElement;\n const isKeyDownInside =\n target.closest('[data-ryvora-menu-content]') === event.currentTarget;\n const isModifierKey = event.ctrlKey || event.altKey || event.metaKey;\n const isCharacterKey = event.key.length === 1;\n if (isKeyDownInside) {\n // menus should not be navigated using tab key so we prevent it\n if (event.key === 'Tab') event.preventDefault();\n if (!isModifierKey && isCharacterKey) handleTypeaheadSearch(event.key);\n }\n // focus first/last item based on key pressed\n const content = contentRef.current;\n if (event.target !== content) return;\n if (!FIRST_LAST_KEYS.includes(event.key)) return;\n event.preventDefault();\n const items = getItems().filter((item) => !item.disabled);\n const candidateNodes = items.map((item) => item.ref.current!);\n if (LAST_KEYS.includes(event.key)) candidateNodes.reverse();\n focusFirst(candidateNodes);\n })}\n onBlur={composeEventHandlers(props.onBlur, (event) => {\n // clear search buffer when leaving the menu\n if (!event.currentTarget.contains(event.target)) {\n window.clearTimeout(timerRef.current);\n searchRef.current = '';\n }\n })}\n onPointerMove={composeEventHandlers(\n props.onPointerMove,\n whenMouse((event) => {\n const target = event.target as HTMLElement;\n const pointerXHasChanged = lastPointerXRef.current !== event.clientX;\n\n // We don't use `event.movementX` for this check because Safari will\n // always return `0` on a pointer event.\n if (event.currentTarget.contains(target) && pointerXHasChanged) {\n const newDir = event.clientX > lastPointerXRef.current ? 'right' : 'left';\n pointerDirRef.current = newDir;\n lastPointerXRef.current = event.clientX;\n }\n })\n )}\n />\n </RovingFocusGroup.Root>\n </DismissableLayer>\n </FocusScope>\n </ScrollLockWrapper>\n </MenuContentProvider>\n );\n }\n);\n\nMenuContent.displayName = CONTENT_NAME;\n\n/** ----------------------------------------- Menu Group ----------------------------------------- */\n\nconst GROUP_NAME = 'MenuGroup';\n\ntype MenuGroupElement = React.ComponentRef<typeof Primitive.div>;\ntype PrimitiveDivProps = React.ComponentPropsWithoutRef<typeof Primitive.div>;\ninterface MenuGroupProps extends PrimitiveDivProps {}\n\nconst MenuGroup = React.forwardRef<MenuGroupElement, MenuGroupProps>(\n (props: ScopedProps<MenuGroupProps>, forwardedRef) => {\n const { __scopeMenu, ...groupProps } = props;\n return <Primitive.div role=\"group\" {...groupProps} ref={forwardedRef} />;\n }\n);\n\nMenuGroup.displayName = GROUP_NAME;\n\n/** ----------------------------------------- Menu Label ----------------------------------------- */\n\nconst LABEL_NAME = 'MenuLabel';\n\ntype MenuLabelElement = React.ComponentRef<typeof Primitive.div>;\ninterface MenuLabelProps extends PrimitiveDivProps {}\n\nconst MenuLabel = React.forwardRef<MenuLabelElement, MenuLabelProps>(\n (props: ScopedProps<MenuLabelProps>, forwardedRef) => {\n const { __scopeMenu, ...labelProps } = props;\n return <Primitive.div {...labelProps} ref={forwardedRef} />;\n }\n);\n\nMenuLabel.displayName = LABEL_NAME;\n\n/** ----------------------------------------- Menu Item ----------------------------------------- */\n\nconst ITEM_NAME = 'MenuItem';\nconst ITEM_SELECT = 'menu.itemSelect';\n\ntype MenuItemElement = MenuItemImplElement;\ninterface MenuItemProps extends Omit<MenuItemImplProps, 'onSelect'> {\n onSelect?: (event: Event) => void;\n}\n\nconst MenuItem = React.forwardRef<MenuItemElement, MenuItemProps>(\n (props: ScopedProps<MenuItemProps>, forwardedRef) => {\n const { disabled = false, onSelect, ...itemProps } = props;\n const ref = React.useRef<HTMLDivElement>(null);\n const rootContext = useMenuRootContext(ITEM_NAME, props.__scopeMenu);\n const contentContext = useMenuContentContext(ITEM_NAME, props.__scopeMenu);\n const composedRefs = useComposedRefs(forwardedRef, ref);\n const isPointerDownRef = React.useRef(false);\n\n const handleSelect = () => {\n const menuItem = ref.current;\n if (!disabled && menuItem) {\n const itemSelectEvent = new CustomEvent(ITEM_SELECT, { bubbles: true, cancelable: true });\n menuItem.addEventListener(ITEM_SELECT, (event) => onSelect?.(event), { once: true });\n dispatchDiscreteCustomEvent(menuItem, itemSelectEvent);\n if (itemSelectEvent.defaultPrevented) {\n isPointerDownRef.current = false;\n } else {\n rootContext.onClose();\n }\n }\n };\n\n return (\n <MenuItemImpl\n {...itemProps}\n ref={composedRefs}\n disabled={disabled}\n onClick={composeEventHandlers(props.onClick, handleSelect)}\n onPointerDown={(event) => {\n props.onPointerDown?.(event);\n isPointerDownRef.current = true;\n }}\n onPointerUp={composeEventHandlers(props.onPointerUp, (event) => {\n // Pointer down can move to a different menu item which should activate it on pointer up.\n // We dispatch a click for selection to allow composition with click based triggers and to\n // prevent Firefox from getting stuck in text selection mode when the menu closes.\n if (!isPointerDownRef.current) event.currentTarget?.click();\n })}\n onKeyDown={composeEventHandlers(props.onKeyDown, (event) => {\n const isTypingAhead = contentContext.searchRef.current !== '';\n if (disabled || (isTypingAhead && event.key === ' ')) return;\n if (SELECTION_KEYS.includes(event.key)) {\n event.currentTarget.click();\n /**\n * We prevent default browser behaviour for selection keys as they should trigger\n * a selection only:\n * - prevents space from scrolling the page.\n * - if keydown causes focus to move, prevents keydown from firing on the new target.\n */\n event.preventDefault();\n }\n })}\n />\n );\n }\n);\n\nMenuItem.displayName = ITEM_NAME;\n\n/** ---------------------------------------------------------------------------------- */\n\ntype MenuItemImplElement = React.ComponentRef<typeof Primitive.div>;\ninterface MenuItemImplProps extends PrimitiveDivProps {\n disabled?: boolean;\n textValue?: string;\n}\n\nconst MenuItemImpl = React.forwardRef<MenuItemImplElement, MenuItemImplProps>(\n (props: ScopedProps<MenuItemImplProps>, forwardedRef) => {\n const { __scopeMenu, disabled = false, textValue, ...itemProps } = props;\n const contentContext = useMenuContentContext(ITEM_NAME, __scopeMenu);\n const rovingFocusGroupScope = useRovingFocusGroupScope(__scopeMenu);\n const ref = React.useRef<HTMLDivElement>(null);\n const composedRefs = useComposedRefs(forwardedRef, ref);\n const [isFocused, setIsFocused] = React.useState(false);\n\n // get the item's `.textContent` as default strategy for typeahead `textValue`\n const [textContent, setTextContent] = React.useState('');\n React.useEffect(() => {\n const menuItem = ref.current;\n if (menuItem) {\n setTextContent((menuItem.textContent ?? '').trim());\n }\n }, [itemProps.children]);\n\n return (\n <Collection.ItemSlot\n scope={__scopeMenu}\n disabled={disabled}\n textValue={textValue ?? textContent}\n >\n <RovingFocusGroup.Item asChild {...rovingFocusGroupScope} focusable={!disabled}>\n <Primitive.div\n role=\"menuitem\"\n data-highlighted={isFocused ? '' : undefined}\n aria-disabled={disabled || undefined}\n data-disabled={disabled ? '' : undefined}\n {...itemProps}\n ref={composedRefs}\n /**\n * We focus items on `pointerMove` to achieve the following:\n *\n * - Mouse over an item (it focuses)\n * - Leave mouse where it is and use keyboard to focus a different item\n * - Wiggle mouse without it leaving previously focused item\n * - Previously focused item should re-focus\n *\n * If we used `mouseOver`/`mouseEnter` it would not re-focus when the mouse\n * wiggles. This is to match native menu implementation.\n */\n onPointerMove={composeEventHandlers(\n props.onPointerMove,\n whenMouse((event) => {\n if (disabled) {\n contentContext.onItemLeave(event);\n } else {\n contentContext.onItemEnter(event);\n if (!event.defaultPrevented) {\n const item = event.currentTarget;\n item.focus({ preventScroll: true });\n }\n }\n })\n )}\n onPointerLeave={composeEventHandlers(\n props.onPointerLeave,\n whenMouse((event) => contentContext.onItemLeave(event))\n )}\n onFocus={composeEventHandlers(props.onFocus, () => setIsFocused(true))}\n onBlur={composeEventHandlers(props.onBlur, () => setIsFocused(false))}\n />\n </RovingFocusGroup.Item>\n </Collection.ItemSlot>\n );\n }\n);\n\n/** ----------------------------------------- Menu Checkbox Item ----------------------------------------- */\n\nconst CHECKBOX_ITEM_NAME = 'MenuCheckboxItem';\n\ntype MenuCheckboxItemElement = MenuItemElement;\n\ntype CheckedState = boolean | 'indeterminate';\n\ninterface MenuCheckboxItemProps extends MenuItemProps {\n checked?: CheckedState;\n // `onCheckedChange` can never be called with `\"indeterminate\"` from the inside\n onCheckedChange?: (checked: boolean) => void;\n}\n\nconst MenuCheckboxItem = React.forwardRef<MenuCheckboxItemElement, MenuCheckboxItemProps>(\n (props: ScopedProps<MenuCheckboxItemProps>, forwardedRef) => {\n const { checked = false, onCheckedChange, ...checkboxItemProps } = props;\n return (\n <ItemIndicatorProvider scope={props.__scopeMenu} checked={checked}>\n <MenuItem\n role=\"menuitemcheckbox\"\n aria-checked={isIndeterminate(checked) ? 'mixed' : checked}\n {...checkboxItemProps}\n ref={forwardedRef}\n data-state={getCheckedState(checked)}\n onSelect={composeEventHandlers(\n checkboxItemProps.onSelect,\n () => onCheckedChange?.(isIndeterminate(checked) ? true : !checked),\n { checkForDefaultPrevented: false }\n )}\n />\n </ItemIndicatorProvider>\n );\n }\n);\n\nMenuCheckboxItem.displayName = CHECKBOX_ITEM_NAME;\n\n/** ----------------------------------------- Menu Radio Group ----------------------------------------- */\n\nconst RADIO_GROUP_NAME = 'MenuRadioGroup';\n\nconst [RadioGroupProvider, useRadioGroupContext] = createMenuContext<MenuRadioGroupProps>(\n RADIO_GROUP_NAME,\n { value: undefined, onValueChange: () => {} }\n);\n\ntype MenuRadioGroupElement = React.ComponentRef<typeof MenuGroup>;\ninterface MenuRadioGroupProps extends MenuGroupProps {\n value?: string;\n onValueChange?: (value: string) => void;\n}\n\nconst MenuRadioGroup = React.forwardRef<MenuRadioGroupElement, MenuRadioGroupProps>(\n (props: ScopedProps<MenuRadioGroupProps>, forwardedRef) => {\n const { value, onValueChange, ...groupProps } = props;\n const handleValueChange = useCallbackRef(onValueChange);\n return (\n <RadioGroupProvider scope={props.__scopeMenu} value={value} onValueChange={handleValueChange}>\n <MenuGroup {...groupProps} ref={forwardedRef} />\n </RadioGroupProvider>\n );\n }\n);\n\nMenuRadioGroup.displayName = RADIO_GROUP_NAME;\n\n/** ----------------------------------------- Menu Radio Item ----------------------------------------- */\n\nconst RADIO_ITEM_NAME = 'MenuRadioItem';\n\ntype MenuRadioItemElement = React.ComponentRef<typeof MenuItem>;\ninterface MenuRadioItemProps extends MenuItemProps {\n value: string;\n}\n\nconst MenuRadioItem = React.forwardRef<MenuRadioItemElement, MenuRadioItemProps>(\n (props: ScopedProps<MenuRadioItemProps>, forwardedRef) => {\n const { value, ...radioItemProps } = props;\n const context = useRadioGroupContext(RADIO_ITEM_NAME, props.__scopeMenu);\n const checked = value === context.value;\n return (\n <ItemIndicatorProvider scope={props.__scopeMenu} checked={checked}>\n <MenuItem\n role=\"menuitemradio\"\n aria-checked={checked}\n {...radioItemProps}\n ref={forwardedRef}\n data-state={getCheckedState(checked)}\n onSelect={composeEventHandlers(\n radioItemProps.onSelect,\n () => context.onValueChange?.(value),\n { checkForDefaultPrevented: false }\n )}\n />\n </ItemIndicatorProvider>\n );\n }\n);\n\nMenuRadioItem.displayName = RADIO_ITEM_NAME;\n\n/** ----------------------------------------- Menu Item Indicator ----------------------------------------- */\n\nconst ITEM_INDICATOR_NAME = 'MenuItemIndicator';\n\ntype CheckboxContextValue = { checked: CheckedState };\n\nconst [ItemIndicatorProvider, useItemIndicatorContext] = createMenuContext<CheckboxContextValue>(\n ITEM_INDICATOR_NAME,\n { checked: false }\n);\n\ntype MenuItemIndicatorElement = React.ComponentRef<typeof Primitive.span>;\ntype PrimitiveSpanProps = React.ComponentPropsWithoutRef<typeof Primitive.span>;\ninterface MenuItemIndicatorProps extends PrimitiveSpanProps {\n /**\n * Used to force mounting when more control is needed. Useful when\n * controlling animation with React animation libraries.\n */\n forceMount?: true;\n}\n\nconst MenuItemIndicator = React.forwardRef<MenuItemIndicatorElement, MenuItemIndicatorProps>(\n (props: ScopedProps<MenuItemIndicatorProps>, forwardedRef) => {\n const { __scopeMenu, forceMount, ...itemIndicatorProps } = props;\n const indicatorContext = useItemIndicatorContext(ITEM_INDICATOR_NAME, __scopeMenu);\n return (\n <Presence\n present={\n forceMount ||\n isIndeterminate(indicatorContext.checked) ||\n indicatorContext.checked === true\n }\n >\n <Primitive.span\n {...itemIndicatorProps}\n ref={forwardedRef}\n data-state={getCheckedState(indicatorContext.checked)}\n />\n </Presence>\n );\n }\n);\n\nMenuItemIndicator.displayName = ITEM_INDICATOR_NAME;\n\n/** ----------------------------------------- Menu Seperator ----------------------------------------- */\n\nconst SEPARATOR_NAME = 'MenuSeparator';\n\ntype MenuSeparatorElement = React.ComponentRef<typeof Primitive.div>;\ninterface MenuSeparatorProps extends PrimitiveDivProps {}\n\nconst MenuSeparator = React.forwardRef<MenuSeparatorElement, MenuSeparatorProps>(\n (props: ScopedProps<MenuSeparatorProps>, forwardedRef) => {\n const { __scopeMenu, ...separatorProps } = props;\n return (\n <Primitive.div\n role=\"separator\"\n aria-orientation=\"horizontal\"\n {...separatorProps}\n ref={forwardedRef}\n />\n );\n }\n);\n\nMenuSeparator.displayName = SEPARATOR_NAME;\n\n/** ----------------------------------------- Menu Arrow ----------------------------------------- */\n\nconst ARROW_NAME = 'MenuArrow';\n\ntype MenuArrowElement = React.ComponentRef<typeof PopperPrimitive.Arrow>;\ntype PopperArrowProps = React.ComponentPropsWithoutRef<typeof PopperPrimitive.Arrow>;\ninterface MenuArrowProps extends PopperArrowProps {}\n\nconst MenuArrow = React.forwardRef<MenuArrowElement, MenuArrowProps>(\n (props: ScopedProps<MenuArrowProps>, forwardedRef) => {\n const { __scopeMenu, ...arrowProps } = props;\n const popperScope = usePopperScope(__scopeMenu);\n return <PopperPrimitive.Arrow {...popperScope} {...arrowProps} ref={forwardedRef} />;\n }\n);\n\nMenuArrow.displayName = ARROW_NAME;\n\n/** ----------------------------------------- Menu Sub ----------------------------------------- */\n\nconst SUB_NAME = 'MenuSub';\n\ntype MenuSubContextValue = {\n contentId: string;\n triggerId: string;\n trigger: MenuSubTriggerElement | null;\n onTriggerChange(trigger: MenuSubTriggerElement | null): void;\n};\n\nconst [MenuSubProvider, useMenuSubContext] = createMenuContext<MenuSubContextValue>(SUB_NAME);\n\ninterface MenuSubProps {\n children?: React.ReactNode;\n open?: boolean;\n onOpenChange?(open: boolean): void;\n}\n\nconst MenuSub: React.FC<MenuSubProps> = (props: ScopedProps<MenuSubProps>) => {\n const { __scopeMenu, children, open = false, onOpenChange } = props;\n const parentMenuContext = useMenuContext(SUB_NAME, __scopeMenu);\n const popperScope = usePopperScope(__scopeMenu);\n const [trigger, setTrigger] = React.useState<MenuSubTriggerElement | null>(null);\n const [content, setContent] = React.useState<MenuContentElement | null>(null);\n const handleOpenChange = useCallbackRef(onOpenChange);\n\n // Prevent the parent menu from reopening with open submenus.\n React.useEffect(() => {\n if (parentMenuContext.open === false) handleOpenChange(false);\n return () => handleOpenChange(false);\n }, [parentMenuContext.open, handleOpenChange]);\n\n return (\n <PopperPrimitive.Root {...popperScope}>\n <MenuProvider\n scope={__scopeMenu}\n open={open}\n onOpenChange={handleOpenChange}\n content={content}\n onContentChange={setContent}\n >\n <MenuSubProvider\n scope={__scopeMenu}\n contentId={useId()}\n triggerId={useId()}\n trigger={trigger}\n onTriggerChange={setTrigger}\n >\n {children}\n </MenuSubProvider>\n </MenuProvider>\n </PopperPrimitive.Root>\n );\n};\n\nMenuSub.displayName = SUB_NAME;\n\n/** ----------------------------------------- Menu Sub Trigger ----------------------------------------- */\n\nconst SUB_TRIGGER_NAME = 'MenuSubTrigger';\n\ntype MenuSubTriggerElement = MenuItemImplElement;\ninterface MenuSubTriggerProps extends MenuItemImplProps {}\n\nconst MenuSubTrigger = React.forwardRef<MenuSubTriggerElement, MenuSubTriggerProps>(\n (props: ScopedProps<MenuSubTriggerProps>, forwardedRef) => {\n const context = useMenuContext(SUB_TRIGGER_NAME, props.__scopeMenu);\n const rootContext = useMenuRootContext(SUB_TRIGGER_NAME, props.__scopeMenu);\n const subContext = useMenuSubContext(SUB_TRIGGER_NAME, props.__scopeMenu);\n const contentContext = useMenuContentContext(SUB_TRIGGER_NAME, props.__scopeMenu);\n const openTimerRef = React.useRef<number | null>(null);\n const { pointerGraceTimerRef, onPointerGraceIntentChange } = contentContext;\n const scope = { __scopeMenu: props.__scopeMenu };\n\n const clearOpenTimer = React.useCallback(() => {\n if (openTimerRef.current) window.clearTimeout(openTimerRef.current);\n openTimerRef.current = null;\n }, []);\n\n React.useEffect(() => clearOpenTimer, [clearOpenTimer]);\n\n React.useEffect(() => {\n const pointerGraceTimer = pointerGraceTimerRef.current;\n return () => {\n window.clearTimeout(pointerGraceTimer);\n onPointerGraceIntentChange(null);\n };\n }, [pointerGraceTimerRef, onPointerGraceIntentChange]);\n\n return (\n <MenuAnchor asChild {...scope}>\n <MenuItemImpl\n id={subContext.triggerId}\n aria-haspopup=\"menu\"\n aria-expanded={context.open}\n aria-controls={subContext.contentId}\n data-state={getOpenState(context.open)}\n {...props}\n ref={composeRefs(forwardedRef, subContext.onTriggerChange)}\n // This is redundant for mouse users but we cannot determine pointer type from\n // click event and we cannot use pointerup event (see git history for reasons why)\n onClick={(event) => {\n props.onClick?.(event);\n if (props.disabled || event.defaultPrevented) return;\n /**\n * We manually focus because iOS Safari doesn't always focus on click (e.g. buttons)\n * and we rely heavily on `onFocusOutside` for submenus to close when switching\n * between separate submenus.\n */\n event.currentTarget.focus();\n if (!context.open) context.onOpenChange(true);\n }}\n onPointerMove={composeEventHandlers(\n props.onPointerMove,\n whenMouse((event) => {\n contentContext.onItemEnter(event);\n if (event.defaultPrevented) return;\n if (!props.disabled && !context.open && !openTimerRef.current) {\n contentContext.onPointerGraceIntentChange(null);\n openTimerRef.current = window.setTimeout(() => {\n context.onOpenChange(true);\n clearOpenTimer();\n }, 100);\n }\n })\n )}\n onPointerLeave={composeEventHandlers(\n props.onPointerLeave,\n whenMouse((event) => {\n clearOpenTimer();\n\n const contentRect = context.content?.getBoundingClientRect();\n if (contentRect) {\n // TODO: make sure to update this when we change positioning logic\n const side = context.content?.dataset.side as Side;\n const rightSide = side === 'right';\n const bleed = rightSide ? -5 : +5;\n const contentNearEdge = contentRect[rightSide ? 'left' : 'right'];\n const contentFarEdge = contentRect[rightSide ? 'right' : 'left'];\n\n contentContext.onPointerGraceIntentChange({\n area: [\n // Apply a bleed on clientX to ensure that our exit point is\n // consistently within polygon bounds\n { x: event.clientX + bleed, y: event.clientY },\n { x: contentNearEdge, y: contentRect.top },\n { x: contentFarEdge, y: contentRect.top },\n { x: contentFarEdge, y: contentRect.bottom },\n { x: contentNearEdge, y: contentRect.bottom },\n ],\n side,\n });\n\n window.clearTimeout(pointerGraceTimerRef.current);\n pointerGraceTimerRef.current = window.setTimeout(\n () => contentContext.onPointerGraceIntentChange(null),\n 300\n );\n } else {\n contentContext.onTriggerLeave(event);\n if (event.defaultPrevented) return;\n\n // There's 100ms where the user may leave an item before the submenu was opened.\n contentContext.onPointerGraceIntentChange(null);\n }\n })\n )}\n onKeyDown={composeEventHandlers(props.onKeyDown, (event) => {\n const isTypingAhead = contentContext.searchRef.current !== '';\n if (props.disabled || (isTypingAhead && event.key === ' ')) return;\n if (SUB_OPEN_KEYS[rootContext.dir].includes(event.key)) {\n context.onOpenChange(true);\n // The trigger may hold focus if opened via pointer interaction\n // so we ensure content is given focus again when switching to keyboard.\n context.content?.focus();\n // prevent window from scrolling\n event.preventDefault();\n }\n })}\n />\n </MenuAnchor>\n );\n }\n);\n\nMenuSubTrigger.displayName = SUB_TRIGGER_NAME;\n\n/** ----------------------------------------- Menu Sub Content ----------------------------------------- */\n\nconst SUB_CONTENT_NAME = 'MenuSubContent';\n\ntype MenuSubContentElement = MenuContentImplElement;\ninterface MenuSubContentProps\n extends Omit<\n MenuContentImplProps,\n keyof MenuContentImplPrivateProps | 'onCloseAutoFocus' | 'onEntryFocus' | 'side' | 'align'\n > {\n /**\n * Used to force mounting when more control is needed. Useful when\n * controlling animation with React animation libraries.\n */\n forceMount?: true;\n}\n\nconst MenuSubContent = React.forwardRef<MenuSubContentElement, MenuSubContentProps>(\n (props: ScopedProps<MenuSubContentProps>, forwardedRef) => {\n const portalContext = usePortalContext(CONTENT_NAME, props.__scopeMenu);\n const { forceMount = portalContext.forceMount, ...subContentProps } = props;\n const context = useMenuContext(CONTENT_NAME, props.__scopeMenu);\n const rootContext = useMenuRootContext(CONTENT_NAME, props.__scopeMenu);\n const subContext = useMenuSubContext(SUB_CONTENT_NAME, props.__scopeMenu);\n const ref = React.useRef<MenuSubContentElement>(null);\n const composedRefs = useComposedRefs(forwardedRef, ref);\n return (\n <Collection.Provider scope={props.__scopeMenu}>\n <Presence present={forceMount || context.open}>\n <Collection.Slot scope={props.__scopeMenu}>\n <MenuContentImpl\n id={subContext.contentId}\n aria-labelledby={subContext.triggerId}\n {...subContentProps}\n ref={composedRefs}\n align=\"start\"\n side={rootContext.dir === 'rtl' ? 'left' : 'right'}\n disableOutsidePointerEvents={false}\n disableOutsideScroll={false}\n trapFocus={false}\n onOpenAutoFocus={(event) => {\n // when opening a submenu, focus content for keyboard users only\n if (rootContext.isUsingKeyboardRef.current) ref.current?.focus();\n event.preventDefault();\n }}\n // The menu might close because of focusing another menu item in the parent menu. We\n // don't want it to refocus the trigger in that case so we handle trigger focus ourselves.\n onCloseAutoFocus={(event) => event.preventDefault()}\n onFocusOutside={composeEventHandlers(props.onFocusOutside, (event) => {\n // We prevent closing when the trigger is focused to avoid triggering a re-open animation\n // on pointer interaction.\n if (event.target !== subContext.trigger) context.onOpenChange(false);\n })}\n onEscapeKeyDown={composeEventHandlers(props.onEscapeKeyDown, (event) => {\n rootContext.onClose();\n // ensure pressing escape in submenu doesn't escape full screen mode\n event.preventDefault();\n })}\n onKeyDown={composeEventHandlers(props.onKeyDown, (event) => {\n // Submenu key events bubble through portals. We only care about keys in this menu.\n const isKeyDownInside = event.currentTarget.contains(event.target as HTMLElement);\n const isCloseKey = SUB_CLOSE_KEYS[rootContext.dir].includes(event.key);\n if (isKeyDownInside && isCloseKey) {\n context.onOpenChange(false);\n // We focus manually because we prevented it in `onCloseAutoFocus`\n subContext.trigger?.focus();\n // prevent window from scrolling\n event.preventDefault();\n }\n })}\n />\n </Collection.Slot>\n </Presence>\n </Collection.Provider>\n );\n }\n);\n\nMenuSubContent.displayName = SUB_CONTENT_NAME;\n\n/** -----------------------------------------------------------------------------------------------*/\n\nfunction getOpenState(open: boolean) {\n return open ? 'open' : 'closed';\n}\n\nfunction isIndeterminate(checked?: CheckedState): checked is 'indeterminate' {\n return checked === 'indeterminate';\n}\n\nfunction getCheckedState(checked: CheckedState) {\n return isIndeterminate(checked) ? 'indeterminate' : checked ? 'checked' : 'unchecked';\n}\n\nfunction focusFirst(candidates: HTMLElement[]) {\n const PREVIOUSLY_FOCUSED_ELEMENT = document.activeElement;\n for (const candidate of candidates) {\n // if focus is already where we want to go, we don't want to keep going through the candidates\n if (candidate === PREVIOUSLY_FOCUSED_ELEMENT) return;\n candidate.focus();\n if (document.activeElement !== PREVIOUSLY_FOCUSED_ELEMENT) return;\n }\n}\n\n/**\n * Wraps an array around itself at a given start index\n * Example: `wrapArray(['a', 'b', 'c', 'd'], 2) === ['c', 'd', 'a', 'b']`\n */\nfunction wrapArray<T>(array: T[], startIndex: number) {\n return array.map<T>((_, index) => array[(startIndex + index) % array.length]!);\n}\n\n/**\n * This is the \"meat\" of the typeahead matching logic. It takes in all the values,\n * the search and the current match, and returns the next match (or `undefined`).\n *\n * We normalize the search because if a user has repeatedly pressed a character,\n * we want the exact same behavior as if we only had that one character\n * (ie. cycle through options starting with that character)\n *\n * We also reorder the values by wrapping the array around the current match.\n * This is so we always look forward from the current match, and picking the first\n