Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
109 changes: 70 additions & 39 deletions packages/core/src/components/navigation-menu/navigation-menu.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
'use client';

import type { CSSProperties, ComponentPropsWithoutRef, ReactElement } from 'react';
import { forwardRef, useEffect, useMemo, useRef, useState } from 'react';
import type { ComponentPropsWithoutRef, ReactElement, RefObject } from 'react';
import { forwardRef, useEffect, useRef, useState } from 'react';

import { NavigationMenu as BaseNavigationMenu } from '@base-ui/react/navigation-menu';
import { ChevronDownOutlineIcon } from '@vapor-ui/icons';

import { useArrowPosition } from '~/hooks/use-arrow-position';
import { useMutationObserverRef } from '~/hooks/use-mutation-observer-ref';
import { useRenderElement } from '~/hooks/use-render-element';
import { createContext } from '~/libs/create-context';
Expand All @@ -21,6 +22,24 @@ import type { VaporUIComponentProps } from '~/utils/types';
import type { LinkVariants, ListVariants } from './navigation-menu.css';
import * as styles from './navigation-menu.css';

/* -------------------------------------------------------------------------------------------------
* NavigationMenuArrowContext (internal)
* -----------------------------------------------------------------------------------------------*/

interface NavigationMenuArrowContextValue {
activeTriggerElement: Element | null;
setActiveTriggerElement: (element: Element | null) => void;
positionerRef: RefObject<HTMLElement | null>;
}

const [NavigationMenuArrowProvider, useNavigationMenuArrowContext] =
createContext<NavigationMenuArrowContextValue>({
name: 'NavigationMenuArrowContext',
strict: false,
hookName: 'useNavigationMenuArrowContext',
providerName: 'NavigationMenuRoot',
});

type NavigationMenuVariants = ListVariants & LinkVariants;
type NavigationMenuSharedProps = NavigationMenuVariants & { disabled?: boolean };
type NavigationMenuContextType = NavigationMenuSharedProps;
Expand All @@ -47,15 +66,22 @@ export const NavigationMenuRoot = forwardRef<HTMLElement, NavigationMenuRoot.Pro

const { direction } = variantProps;

const [activeTriggerElement, setActiveTriggerElement] = useState<Element | null>(null);
const positionerRef = useRef<HTMLElement>(null);
Comment on lines +70 to +71

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unlike tooltips and popovers, the navigation menu contains multiple triggers within the Root. As a result, there are limitations to specifying the trigger element using a ref, so the element is managed via state.


return (
<NavigationMenuProvider value={variantProps}>
<BaseNavigationMenu.Root
ref={ref}
orientation={direction}
className={className}
{...otherProps}
/>
</NavigationMenuProvider>
<NavigationMenuArrowProvider
value={{ activeTriggerElement, setActiveTriggerElement, positionerRef }}
>
<NavigationMenuProvider value={variantProps}>
<BaseNavigationMenu.Root
ref={ref}
orientation={direction}
className={className}
{...otherProps}
/>
</NavigationMenuProvider>
</NavigationMenuArrowProvider>
);
},
);
Expand Down Expand Up @@ -149,13 +175,36 @@ export const NavigationMenuTriggerPrimitive = forwardRef<
>((props, ref) => {
const { disabled: disabledProp, className, ...componentProps } = resolveStyles(props);
const { size, disabled: contextDisabled } = useNavigationMenuContext();
const arrowCtx = useNavigationMenuArrowContext();
const setActiveTrigger = arrowCtx?.setActiveTriggerElement;

const internalRef = useRef<HTMLButtonElement>(null);
const composedRef = arrowCtx ? composeRefs(internalRef, ref) : ref;

useEffect(() => {
const node = internalRef.current;
if (!node || !setActiveTrigger) return;

if (node.hasAttribute('data-popup-open')) {
setActiveTrigger(node);
}

const observer = new MutationObserver(() => {
if (node.hasAttribute('data-popup-open')) {
setActiveTrigger(node);
}
});
observer.observe(node, { attributes: true, attributeFilter: ['data-popup-open'] });

return () => observer.disconnect();
}, [setActiveTrigger]);

const disabled = disabledProp ?? contextDisabled;
const dataAttrs = createDataAttributes({ disabled });

return (
<BaseNavigationMenu.Trigger
ref={ref}
ref={composedRef}
disabled={disabled}
className={cn(styles.link({ size }), styles.trigger, className)}
{...dataAttrs}
Expand Down Expand Up @@ -260,10 +309,12 @@ export const NavigationMenuPositionerPrimitive = forwardRef<
className,
...componentProps
} = resolveStyles(props);
const arrowCtx = useNavigationMenuArrowContext();
const composedRef = arrowCtx ? composeRefs(arrowCtx.positionerRef, ref) : ref;

return (
<BaseNavigationMenu.Positioner
ref={ref}
ref={composedRef}
side={side}
align={align}
sideOffset={sideOffset}
Expand All @@ -290,7 +341,13 @@ export const NavigationMenuPopupPrimitive = forwardRef<
const [side, setSide] = useState<NavigationMenuPositionerPrimitive.Props['side']>();
const [align, setAlign] = useState<NavigationMenuPositionerPrimitive.Props['align']>();

const position = useMemo(() => getArrowPosition({ side, align }), [side, align]);
const arrowCtx = useNavigationMenuArrowContext();
const position = useArrowPosition({
triggerElement: arrowCtx?.activeTriggerElement ?? null,
positionerElement: arrowCtx?.positionerRef.current ?? null,
side: side ?? 'bottom',
align: align ?? 'center',
});
Comment thread
MaxLee-dev marked this conversation as resolved.

const popupRef = useRef<HTMLDivElement>(null);
const composedRef = composeRefs(popupRef, ref);
Expand Down Expand Up @@ -344,32 +401,6 @@ const extractPositions = (dataset: DOMStringMap) => {

/* -----------------------------------------------------------------------------------------------*/

type ArrowPositionProps = Pick<NavigationMenuPositionerPrimitive.Props, 'side' | 'align'> & {
offset?: number;
};

const getArrowPosition = ({
side = 'top',
align = 'center',
offset = 12,
}: ArrowPositionProps): CSSProperties => {
const positionMap = {
'top-start': { left: offset, right: 'unset' },
'top-end': { left: 'unset', right: offset },
'bottom-start': { left: offset, right: 'unset' },
'bottom-end': { left: 'unset', right: offset },
'left-start': { top: offset, bottom: 'unset' },
'left-end': { top: 'unset', bottom: offset },
'right-start': { top: offset, bottom: 'unset' },
'right-end': { top: 'unset', bottom: offset },
};

const key = `${side}-${align}` as keyof typeof positionMap;
return positionMap[key] || {};
};

/* -----------------------------------------------------------------------------------------------*/

const ArrowIcon = (props: ComponentPropsWithoutRef<'svg'>) => {
return (
<svg
Expand Down
1 change: 0 additions & 1 deletion packages/core/src/components/popover/popover.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,6 @@ export const TestBed: StoryObj<Popover.Root.Props & Popover.PositionerPrimitive.
<Popover.PositionerPrimitive
side="bottom"
align="end"
alignOffset={100}
collisionAvoidance={{ align: 'flip' }}
/>
}
Expand Down
73 changes: 41 additions & 32 deletions packages/core/src/components/popover/popover.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
'use client';

import type { CSSProperties, ComponentProps, ReactElement } from 'react';
import { forwardRef, useEffect, useMemo, useRef, useState } from 'react';
import type { ComponentProps, ReactElement, RefObject } from 'react';
import { forwardRef, useEffect, useRef, useState } from 'react';

import { Popover as BasePopover } from '@base-ui/react/popover';

import { useArrowPosition } from '~/hooks/use-arrow-position';
import { createContext } from '~/libs/create-context';
import { useMutationObserverRef } from '~/hooks/use-mutation-observer-ref';
import { useRenderElement } from '~/hooks/use-render-element';
import { vars } from '~/styles/themes.css';
Expand All @@ -16,12 +18,35 @@ import type { VaporUIComponentProps } from '~/utils/types';

import * as styles from './popover.css';

/* -------------------------------------------------------------------------------------------------
* PopoverArrowContext (internal)
* -----------------------------------------------------------------------------------------------*/

interface PopoverArrowContextValue {
triggerRef: RefObject<Element | null>;
positionerRef: RefObject<HTMLElement | null>;
}

const [PopoverArrowProvider, usePopoverArrowContext] = createContext<PopoverArrowContextValue>({
name: 'PopoverArrowContext',
strict: false,
hookName: 'usePopoverArrowContext',
providerName: 'PopoverRoot',
});

/* -------------------------------------------------------------------------------------------------
* Popover.Root
* -----------------------------------------------------------------------------------------------*/

export const PopoverRoot = (props: PopoverRoot.Props) => {
return <BasePopover.Root {...props} />;
const triggerRef = useRef<Element>(null);
const positionerRef = useRef<HTMLElement>(null);

return (
<PopoverArrowProvider value={{ triggerRef, positionerRef }}>
<BasePopover.Root {...props} />
</PopoverArrowProvider>
);
};
PopoverRoot.displayName = 'Popover.Root';

Expand All @@ -31,8 +56,10 @@ PopoverRoot.displayName = 'Popover.Root';

export const PopoverTrigger = forwardRef<HTMLButtonElement, PopoverTrigger.Props>((props, ref) => {
const componentProps = resolveStyles(props);
const ctx = usePopoverArrowContext();
const composedRef = ctx ? composeRefs(ctx.triggerRef, ref) : ref;

return <BasePopover.Trigger ref={ref} {...componentProps} />;
return <BasePopover.Trigger ref={composedRef} {...componentProps} />;
});
PopoverTrigger.displayName = 'Popover.Trigger';

Expand Down Expand Up @@ -75,10 +102,12 @@ export const PopoverPositionerPrimitive = forwardRef<
collisionAvoidance,
...componentProps
} = resolveStyles(props);
const ctx = usePopoverArrowContext();
const composedRef = ctx ? composeRefs(ctx.positionerRef, ref) : ref;

return (
<BasePopover.Positioner
ref={ref}
ref={composedRef}
side={side}
align={align}
sideOffset={sideOffset}
Expand All @@ -103,7 +132,13 @@ export const PopoverPopupPrimitive = forwardRef<HTMLDivElement, PopoverPopupPrim
const [side, setSide] = useState<PopoverPositionerPrimitive.Props['side']>('bottom');
const [align, setAlign] = useState<PopoverPositionerPrimitive.Props['align']>('start');

const position = useMemo(() => getArrowPosition({ side, align }), [side, align]);
const ctx = usePopoverArrowContext();
const position = useArrowPosition({
triggerElement: ctx?.triggerRef.current ?? null,
positionerElement: ctx?.positionerRef.current ?? null,
side: side ?? 'bottom',
align: align ?? 'center',
});

const popupRef = useRef<HTMLDivElement>(null);
const composedRef = composeRefs(popupRef, ref);
Expand Down Expand Up @@ -209,32 +244,6 @@ PopoverDescription.displayName = 'Popover.Description';

/* -----------------------------------------------------------------------------------------------*/

type ArrowPositionProps = Pick<PopoverPositionerPrimitive.Props, 'side' | 'align'> & {
offset?: number;
};

const getArrowPosition = ({
side = 'top',
align = 'center',
offset = 12,
}: ArrowPositionProps): CSSProperties => {
const positionMap = {
'top-start': { left: offset, right: 'unset' },
'top-end': { left: 'unset', right: offset },
'bottom-start': { left: offset, right: 'unset' },
'bottom-end': { left: 'unset', right: offset },
'left-start': { top: offset, bottom: 'unset' },
'left-end': { top: 'unset', bottom: offset },
'right-start': { top: offset, bottom: 'unset' },
'right-end': { top: 'unset', bottom: offset },
};

const key = `${side}-${align}` as keyof typeof positionMap;
return positionMap[key] || {};
};

/* -----------------------------------------------------------------------------------------------*/

const ArrowIcon = (props: ComponentProps<'svg'>) => {
return (
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 16" fill="none" {...props}>
Expand Down
Loading
Loading