All files DropdownMenu.tsx

100% Statements 390/390
100% Branches 88/88
100% Functions 33/33
100% Lines 390/390

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 5752x 1x 1x 1x 1x 1x     1x 1x 1x 2x 2x 2x                       2x                   2x           74x 74x 74x 74x   74x 37x 35x 2x 2x 35x 37x 37x 74x   74x 2x 2x   2x 2x 2x   74x 2x 2x   2x 2x 2x 2x 2x   74x 31x 31x   74x 74x 74x 74x 74x   74x 74x 74x 74x 74x 74x 74x 74x 74x   74x       74x               77x 77x 77x 77x 77x 77x 77x 74x 74x 74x 74x 74x 74x 74x   74x 77x 11x 11x 11x 63x 63x 63x     63x                 77x 77x 77x 77x 77x 77x 77x 77x 77x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x   28x   28x     28x 1x 27x 77x           1x 1x 1x 1x   1x             1x 1x 1x 1x 1x 1x   1x     1x                     34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 31x   31x 31x 31x   31x 7x 7x 7x 2x 2x 2x 2x 7x 2x 2x 7x 2x 2x 7x 1x 1x 7x 7x   31x 31x 31x 34x 34x 34x 4x 3x 3x 3x 4x 34x 34x 34x 34x 34x 34x 34x 34x 34x 1x 34x 34x 34x 34x 34x     34x     34x               1x 1x 1x 1x 1x 1x 1x 1x 1x   1x     1x           1x 1x 1x 1x     1x               2x 2x 2x 2x 2x 2x 2x 2x 2x 1x   2x     2x     2x   1x 1x 1x 1x 1x     1x             2x 2x 2x 2x 2x 2x   2x     2x             1x 1x 1x 1x 1x 1x 1x     1x     1x           17x 17x 17x 17x   17x 19x 3x 3x 3x 19x   17x 8x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 17x   17x 17x 17x 17x 17x 17x 7x 7x 7x 17x 3x 2x 2x 3x 3x 17x 1x 1x 1x 17x   17x       17x                 20x 20x 20x 20x 20x 20x 20x 20x 17x 17x 7x 7x 17x 2x 2x 17x 17x 17x 17x 17x 17x 20x 20x   20x 20x 2x 2x 2x 15x 15x 15x 15x     15x               27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x   27x 17x 7x 7x   7x 7x   7x 7x 7x 7x 7x 7x 7x 7x 7x 27x   27x 27x 27x   14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x   14x 14x 14x 14x 14x 14x   14x     14x 2x 12x 27x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
import React, {
  createContext,
  useContext,
  useState,
  useRef,
  useEffect,
  ReactNode,
  ReactElement,
  Children,
  cloneElement,
} from 'react';
import ReactDOM from 'react-dom';
import { CheckIcon, ChevronRightIcon, CircleIcon } from 'lucide-react';
import { cn } from '../lib/utils'; // Adjust path to your utility function
 
// Main dropdown context
interface DropdownContextValue {
  open: boolean;
  toggle: () => void;
  close: () => void;
  registerItem: (node: HTMLElement) => void;
  focusNext: () => void;
  focusPrev: () => void;
}
 
const DropdownContext = createContext<DropdownContextValue | null>(null);
 
// Submenu context
interface SubContextValue {
  open: boolean;
  toggle: () => void;
  close: () => void;
  keepOpen: () => void;
}
 
const SubContext = createContext<SubContextValue | null>(null);
 
interface DropdownMenuProps {
  children: ReactNode;
}
 
function DropdownMenu({ children }: DropdownMenuProps) {
  const [open, setOpen] = useState(false);
  const itemsRef = useRef<HTMLElement[]>([]);
  const rootRef = useRef<HTMLDivElement>(null);
 
  useEffect(() => {
    function onClick(e: MouseEvent) {
      if (rootRef.current && !rootRef.current.contains(e.target as Node)) {
        setOpen(false);
      }
    }
    document.addEventListener('mousedown', onClick);
    return () => document.removeEventListener('mousedown', onClick);
  }, []);
 
  const focusNext = () => {
    const idx = itemsRef.current.findIndex(
      (el) => el === document.activeElement
    );
    const next = itemsRef.current[idx + 1] || itemsRef.current[0];
    next?.focus();
  };
 
  const focusPrev = () => {
    const idx = itemsRef.current.findIndex(
      (el) => el === document.activeElement
    );
    const prev =
      itemsRef.current[idx - 1] ||
      itemsRef.current[itemsRef.current.length - 1];
    prev?.focus();
  };
 
  const registerItem = (node: HTMLElement) => {
    if (node && !itemsRef.current.includes(node)) itemsRef.current.push(node);
  };
 
  return (
    <div
      ref={rootRef}
      data-slot='dropdown-menu'
      className='relative inline-block'
    >
      <DropdownContext.Provider
        value={{
          open,
          toggle: () => setOpen((o) => !o),
          close: () => setOpen(false),
          registerItem,
          focusNext,
          focusPrev,
        }}
      >
        {children}
      </DropdownContext.Provider>
    </div>
  );
}
 
interface TriggerProps {
  children: ReactNode;
  className?: string;
  asChild?: boolean;
}
 
function DropdownMenuTrigger({
  children,
  className,
  asChild = false,
}: TriggerProps) {
  const ctx = useContext(DropdownContext);
  if (!ctx) throw new Error('DropdownMenuTrigger must be inside DropdownMenu');
  const props = {
    onClick: ctx.toggle,
    'aria-expanded': ctx.open,
    'data-slot': 'dropdown-menu-trigger',
    className: cn(
      'inline-flex items-center justify-center rounded-md px-3 py-2 text-sm font-medium transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 hover:bg-accent hover:text-accent-foreground',
      className
    ),
  };
  if (asChild) {
    const child = Children.only(children) as ReactElement;
    return cloneElement(child, props);
  }
  return (
    <button type='button' {...props}>
      {children}
    </button>
  );
}
 
interface ContentProps {
  children: ReactNode;
  className?: string;
  sideOffset?: number;
  asChild?: boolean;
}
 
function DropdownMenuContent({
  children,
  className,
  sideOffset = 4,
  asChild = false,
}: ContentProps) {
  const ctx = useContext(DropdownContext);
  if (!ctx) throw new Error('DropdownMenuContent must be inside DropdownMenu');
  if (!ctx.open) return null;
  const content = (
    <div
      data-slot='dropdown-menu-content'
      data-side='bottom'
      className={cn(
        'absolute top-full left-0',
        'bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out',
        'data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
        'data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95',
        'data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2',
        'data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
        'z-50 max-h-[var(--radix-dropdown-menu-content-available-height)] min-w-[8rem]',
        'origin-[var(--radix-dropdown-menu-content-transform-origin)] overflow-x-hidden overflow-y-auto',
        'rounded-md border p-1 shadow-md',
        className
      )}
      style={{ marginTop: sideOffset }}
    >
      {children}
    </div>
  );
  return asChild
    ? cloneElement(Children.only(children) as ReactElement, content.props)
    : content;
}
 
interface PortalProps {
  children: ReactNode;
}
 
function DropdownMenuPortal({ children }: PortalProps) {
  return ReactDOM.createPortal(
    <div data-slot='dropdown-menu-portal'>{children}</div>,
    document.body
  );
}
 
interface GroupProps {
  children: ReactNode;
  className?: string;
}
 
function DropdownMenuGroup({ children, className }: GroupProps) {
  return (
    <div
      data-slot='dropdown-menu-group'
      role='group'
      className={cn('py-1', className)}
    >
      {children}
    </div>
  );
}
 
interface ItemProps {
  children: ReactNode;
  onSelect?: () => void;
  disabled?: boolean;
  variant?: 'default' | 'destructive';
  className?: string;
  inset?: boolean;
}
 
function DropdownMenuItem({
  children,
  onSelect,
  disabled,
  variant = 'default',
  className,
  inset = false,
}: ItemProps) {
  const ctx = useContext(DropdownContext);
  if (!ctx) throw new Error('DropdownMenuItem must be inside DropdownMenu');
  const ref = useRef<HTMLDivElement>(null);
 
  useEffect(() => {
    if (ref.current) ctx.registerItem(ref.current);
  }, [ctx]);
 
  const handleKey = (e: React.KeyboardEvent) => {
    switch (e.key) {
      case 'Enter':
      case ' ':
        e.preventDefault();
        if (!disabled) onSelect?.();
        ctx.close();
        break;
      case 'ArrowDown':
        ctx.focusNext();
        break;
      case 'ArrowUp':
        ctx.focusPrev();
        break;
      case 'Escape':
        ctx.close();
        break;
    }
  };
 
  return (
    <div
      role='menuitem'
      tabIndex={disabled ? -1 : 0}
      ref={ref}
      onClick={() => {
        if (!disabled) {
          onSelect?.();
          ctx.close();
        }
      }}
      onKeyDown={handleKey}
      data-slot='dropdown-menu-item'
      data-inset={inset}
      data-variant={variant}
      data-disabled={disabled}
      className={cn(
        'relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none select-none',
        'hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground transition-colors',
        variant === 'destructive' &&
          'text-destructive hover:bg-destructive/10 focus:bg-destructive/10 dark:data-[variant=destructive]:hover:bg-destructive/20 dark:data-[variant=destructive]:focus:bg-destructive/20',
        'data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
        inset && 'pl-8',
        "[&_svg:not([class*='text-'])]:text-muted-foreground",
        "[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
        className
      )}
    >
      {children}
    </div>
  );
}
 
interface CheckboxItemProps {
  children: ReactNode;
  checked: boolean;
  onChange: (value: boolean) => void;
}
 
function DropdownMenuCheckboxItem({
  children,
  checked,
  onChange,
}: CheckboxItemProps) {
  return (
    <DropdownMenuItem inset onSelect={() => onChange(!checked)}>
      <span className='pointer-events-none absolute left-2 flex size-3.5 items-center'>
        {checked && <CheckIcon className='size-4' />}
      </span>
      {children}
    </DropdownMenuItem>
  );
}
 
interface RadioGroupProps {
  children: ReactNode;
}
 
function DropdownMenuRadioGroup({ children }: RadioGroupProps) {
  return (
    <div data-slot='dropdown-menu-radio-group' role='group'>
      {children}
    </div>
  );
}
 
interface RadioItemProps {
  children: ReactNode;
  checked: boolean;
  onSelect: () => void;
}
 
function DropdownMenuRadioItem({
  children,
  checked,
  onSelect,
}: RadioItemProps) {
  return (
    <DropdownMenuItem inset onSelect={onSelect}>
      <span className='pointer-events-none absolute left-2 flex size-3.5 items-center'>
        {checked ? (
          <CircleIcon className='size-2 fill-current' />
        ) : (
          <span className='size-2' />
        )}
      </span>
      {children}
    </DropdownMenuItem>
  );
}
 
function DropdownMenuSeparator() {
  return (
    <div
      data-slot='dropdown-menu-separator'
      className={cn('bg-border -mx-1 my-1 h-px')}
    />
  );
}
 
interface LabelProps {
  children: ReactNode;
  inset?: boolean;
}
 
function DropdownMenuLabel({ children, inset }: LabelProps) {
  return (
    <div
      data-slot='dropdown-menu-label'
      data-inset={inset}
      className={cn('px-2 py-1.5 text-sm font-medium', inset && 'pl-8')}
    >
      {children}
    </div>
  );
}
 
interface ShortcutProps {
  children: ReactNode;
  className?: string;
}
 
function DropdownMenuShortcut({ children, className }: ShortcutProps) {
  return (
    <span
      data-slot='dropdown-menu-shortcut'
      className={cn(
        'text-muted-foreground ml-auto text-xs tracking-widest',
        className
      )}
    >
      {children}
    </span>
  );
}
 
interface SubProps {
  children: ReactNode;
}
 
function DropdownMenuSub({ children }: SubProps) {
  const [open, setOpen] = useState(false);
  const rootRef = useRef<HTMLDivElement>(null);
  const timeoutId = useRef<NodeJS.Timeout | null>(null);
 
  const clearTimeoutId = () => {
    if (timeoutId.current) {
      clearTimeout(timeoutId.current);
      timeoutId.current = null;
    }
  };
 
  useEffect(() => {
    function onClick(e: MouseEvent) {
      if (rootRef.current && !rootRef.current.contains(e.target as Node)) {
        setOpen(false);
        clearTimeoutId();
      }
    }
    document.addEventListener('mousedown', onClick);
    return () => {
      document.removeEventListener('mousedown', onClick);
      clearTimeoutId();
    };
  }, []);
 
  return (
    <div ref={rootRef} data-slot='dropdown-menu-sub' className='relative'>
      <SubContext.Provider
        value={{
          open,
          toggle: () => {
            setOpen((o) => !o);
            clearTimeoutId();
          },
          close: () => {
            timeoutId.current = setTimeout(() => {
              setOpen(false);
              clearTimeoutId();
            }, 100); // 100ms delay for hover transition
          },
          keepOpen: () => {
            clearTimeoutId();
            setOpen(true);
          },
        }}
      >
        {children}
      </SubContext.Provider>
    </div>
  );
}
 
interface SubTriggerProps {
  children: ReactNode;
  inset?: boolean;
  className?: string;
  asChild?: boolean;
}
 
function DropdownMenuSubTrigger({
  children,
  inset,
  className,
  asChild = false,
}: SubTriggerProps) {
  const ctx = useContext(SubContext);
  if (!ctx) throw new Error('SubTrigger must be inside DropdownMenuSub');
  const props = {
    onMouseEnter: () => {
      ctx.toggle();
    },
    onMouseLeave: () => {
      ctx.close();
    },
    onClick: ctx.toggle,
    'data-slot': 'dropdown-menu-sub-trigger',
    'data-inset': inset,
    className: cn(
      'flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none',
      'hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground transition-colors',
      inset && 'pl-8',
      className
    ),
  };
  if (asChild) {
    const child = Children.only(children) as ReactElement;
    return cloneElement(child, props);
  }
  return (
    <div {...props}>
      {children}
      <ChevronRightIcon className='ml-auto size-4' />
    </div>
  );
}
 
interface SubContentProps {
  children: ReactNode;
  className?: string;
  asChild?: boolean;
}
 
function DropdownMenuSubContent({
  children,
  className,
  asChild = false,
}: SubContentProps) {
  const subCtx = useContext(SubContext);
  const dropdownCtx = useContext(DropdownContext);
  const [position, setPosition] = useState<{ top: number; left: number }>({
    top: 0,
    left: 0,
  });
 
  useEffect(() => {
    if (dropdownCtx?.open && subCtx?.open) {
      const contentEl = document.querySelector(
        '[data-slot="dropdown-menu-content"]'
      );
      const triggerEl = document.querySelector(
        '[data-slot="dropdown-menu-sub-trigger"]'
      );
      if (contentEl && triggerEl) {
        const contentRect = contentEl.getBoundingClientRect();
        const triggerRect = triggerEl.getBoundingClientRect();
        setPosition({
          top: triggerRect.top,
          left: contentRect.right + 4,
        });
      }
    }
  }, [dropdownCtx?.open, subCtx?.open]);
 
  if (!subCtx || !dropdownCtx)
    throw new Error('SubContent must be inside DropdownMenuSub');
  if (!subCtx.open) return null;
 
  const content = (
    <div
      data-slot='dropdown-menu-sub-content'
      data-side='right'
      className={cn(
        'fixed',
        'bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out',
        'data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
        'data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95',
        'data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2',
        'data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
        'z-50 max-h-[var(--radix-dropdown-menu-content-available-height)] min-w-[8rem]',
        'origin-[var(--radix-dropdown-menu-content-transform-origin)] overflow-x-hidden overflow-y-auto',
        'rounded-md border p-1 shadow-md',
        className
      )}
      style={{
        top: `${position.top}px`,
        left: `${position.left}px`,
      }}
      onMouseEnter={() => subCtx.keepOpen()}
      onMouseLeave={() => subCtx.close()}
    >
      {children}
    </div>
  );
  return asChild
    ? cloneElement(Children.only(children) as ReactElement, content.props)
    : content;
}
 
export {
  DropdownMenu,
  DropdownMenuPortal,
  DropdownMenuTrigger,
  DropdownMenuContent,
  DropdownMenuGroup,
  DropdownMenuLabel,
  DropdownMenuItem,
  DropdownMenuCheckboxItem,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuSeparator,
  DropdownMenuShortcut,
  DropdownMenuSub,
  DropdownMenuSubTrigger,
  DropdownMenuSubContent,
};