{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "tw-menu",
  "type": "registry:ui",
  "title": "react-tw/menu.tsx",
  "description": "Carbon `Menu` and its items as React + Tailwind components, the look and keyboard of `<ui-menu>` Copied from @purpurabog/ui 2.3.0; the package is the maintained source, this copy is yours to change. Icons from the Carbon Design System (Apache-2.0, © IBM Corp.; see THIRD-PARTY-NOTICES.md in the package).",
  "dependencies": [
    "@purpurabog/ui@^2.3.0"
  ],
  "registryDependencies": [
    "@kanok-ui/core-position",
    "@kanok-ui/tw-button",
    "@kanok-ui/tw-i18n",
    "@kanok-ui/tw-refs",
    "@kanok-ui/tw-theme",
    "@kanok-ui/tw-tooltip",
    "@kanok-ui/tw-utils"
  ],
  "files": [
    {
      "path": "src/react-tw/menu.tsx",
      "type": "registry:ui",
      "target": "components/ui/react-tw/menu.tsx",
      "content": "import { Children, createContext, Fragment, isValidElement, useContext, useLayoutEffect, useMemo, useRef, useState, type ReactNode, type RefObject, type ComponentProps } from 'react';\nimport type { Placement } from '../core/position.ts';\nimport { Menu as MenuPrimitive } from '@purpurabog/ui/headless';\nimport { Button, type ButtonKind } from './button.tsx';\nimport { Tooltip } from './tooltip.tsx';\nimport { useTranslation } from './lib/i18n.ts';\nimport { cn } from './lib/utils.ts';\nimport { useMergedRefs } from './lib/refs.ts';\n\n/**\n * Carbon `Menu` and its items as React + Tailwind components, the look and keyboard of `<ui-menu>`\n * on the headless `Menu` (restyle it from there): a `role=\"menu\"` list in the top layer beside its\n * anchor. Opening focuses the first item (or the last); ↑ / ↓ wrap, Home / End jump, letters jump\n * (typeahead); Esc or Tab close and give focus back; so do picking an item, clicking outside or\n * focus leaving. Items with child items open them in a submenu beside (hover, click, Enter, Space,\n * →; ← or Esc close just that level). `MenuButton` and `OverflowMenu` are the triggers Carbon ships.\n */\nexport type MenuSize = 'xs' | 'sm' | 'md' | 'lg';\nexport type MenuFocus = MenuPrimitive.MenuFocus;\n\n/** What the rows need to look right; the state (open, focus, checks) is the primitive's. */\ninterface MenuLookValue {\n    size: MenuSize;\n    /** Some item has an icon: every row gets the icon column (Carbon `with-icons`). */\n    icons: boolean;\n    /** Some item is selectable or a radio: every row gets the check column. */\n    selectable: boolean;\n}\n\nconst MenuLookContext = createContext<MenuLookValue | null>(null);\n/** Inside a single-selection `MenuItemGroup`: items are radios. */\nconst RadioGroupContext = createContext(false);\n\n/** Whether the menu's own items (not those of submenus) have icons / checks. */\nfunction columns(children: ReactNode): { icons: boolean; selectable: boolean } {\n    let icons = false;\n    let selectable = false;\n    const visit = (nodes: ReactNode, inRadioGroup: boolean) => {\n        Children.forEach(nodes, (child) => {\n            if (!isValidElement(child)) return;\n            const props = child.props as Record<string, unknown>;\n            if (child.type === MenuItem) {\n                icons ||= !!props.icon;\n                selectable ||= !!props.selectable || inRadioGroup;\n            } else if (child.type === MenuItemGroup) visit(props.children as ReactNode, props.selection === 'single');\n            else if (child.type === Fragment) visit(props.children as ReactNode, inRadioGroup);\n        });\n    };\n    visit(children, false);\n    return { icons, selectable };\n}\n\nexport interface MenuPopupProps extends Omit<ComponentProps<'div'>, 'children' | 'className'> {\n    label?: string;\n    size: MenuSize;\n    placement?: Placement;\n    matchWidth?: boolean;\n    anchor?: RefObject<Element | null>;\n    children: ReactNode;\n    className?: string;\n}\n\n/**\n * The menu's box on the headless `Menu.Popup` (inside a `Menu.Root` with a trigger of your own, as\n * ComboButton); tells its rows which columns they all get.\n */\nexport function MenuPopup({ label, size, placement, matchWidth, anchor, children, className, ref, ...rest }: Readonly<MenuPopupProps>) {\n    const menu = useRef<HTMLDivElement>(null);\n    const menuRef = useMergedRefs(menu, ref);\n    // from the children; corrected from the DOM after render for items inside components of your own\n    const fromChildren = columns(children);\n    const [fromDom, setFromDom] = useState<{ icons: boolean; selectable: boolean } | null>(null);\n    const { icons, selectable } = fromDom ?? fromChildren;\n    // which rows have icons or checks, read back from the rendered items after every render; set only when it changed\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    useLayoutEffect(() => {\n        const el = menu.current;\n        if (!el) return;\n        const items = MenuPrimitive.ownItems(el);\n        const found = { icons: items.some((i) => i.dataset.icon !== undefined), selectable: items.some((i) => i.hasAttribute('aria-checked')) };\n        if (found.icons !== icons || found.selectable !== selectable) setFromDom(found);\n    });\n    const look = useMemo<MenuLookValue>(() => ({ size, icons, selectable }), [size, icons, selectable]);\n    return (\n        <MenuLookContext.Provider value={look}>\n            <MenuPrimitive.Popup {...rest}\n                ref={menuRef}\n                anchor={anchor}\n                placement={placement}\n                matchWidth={matchWidth}\n                aria-label={label}\n                className={cn(\n                    // the menu settings (--ui-menu-*), as the dropdown lists (list.tsx); 4px above the first row and below the last\n                    'absolute inset-auto m-0 box-border max-h-[var(--ui-available-height,none)] max-w-[var(--ui-menu-max-width,288px)] min-w-[var(--ui-menu-min-width,160px)] overflow-y-auto overscroll-contain ui-menu-edge rounded-[var(--ui-menu-radius,0px)] bg-[var(--ui-overlay-background,var(--ui-surface-1))] px-[var(--ui-menu-padding,0px)] py-[calc(var(--ui-menu-padding,0px)+4px)] font-sans text-ink outline-none',\n                    'shadow-[var(--ui-menu-shadow,0_2px_6px_rgb(0_0_0/0.3))] data-[side=top]:shadow-[var(--ui-menu-shadow,0_-2px_6px_rgb(0_0_0/0.3))] focus:outline-1 focus:outline-solid focus:outline-focus [@media_screen_and_(prefers-contrast)]:focus:outline-dotted',\n                    icons && 'min-w-48',\n                    'forced-colors:border forced-colors:border-solid forced-colors:border-[CanvasText]',\n                    className,\n                )}\n            >\n                {children}\n            </MenuPrimitive.Popup>\n        </MenuLookContext.Provider>\n    );\n}\n\nexport interface MenuProps extends Omit<ComponentProps<'div'>, 'open' | 'onOpenChange' | 'anchor' | 'label' | 'size' | 'placement' | 'matchWidth' | 'initialFocus' | 'submenu' | 'onPick' | 'id' | 'children' | 'className'> {\n    open: boolean;\n    onOpenChange: (open: boolean) => void;\n    /** What the menu sits beside (and gives focus back to). */\n    anchor: RefObject<Element | null>;\n    /** Accessible name (the trigger's label). */\n    label?: string;\n    size?: MenuSize;\n    placement?: Placement;\n    /** As wide as the anchor (Carbon menu button with `bottom` / `top`). */\n    matchWidth?: boolean;\n    /** Which item takes focus on open (`none`: a submenu opened by hover). */\n    initialFocus?: MenuFocus;\n    /** Internal: this menu is a submenu beside its item. */\n    submenu?: boolean;\n    /** Called when an item is picked (every level closes). */\n    onPick?: () => void;\n    id?: string;\n    children: ReactNode;\n    className?: string;\n}\n\nexport function Menu({ open, onOpenChange, anchor, label, size = 'sm', placement = 'bottom-start', matchWidth, initialFocus = 'first', submenu, onPick, id, children, className, ref, ...rest }: Readonly<MenuProps>) {\n    const MenuRoot = submenu ? MenuPrimitive.SubmenuRoot : MenuPrimitive.Root;\n    const changed = (next: boolean, reason: MenuPrimitive.OpenChangeReason) => {\n        onOpenChange(next);\n        if (reason === 'item-press') onPick?.();\n    };\n    return (\n        <MenuRoot open={open} onOpenChange={changed} initialFocus={initialFocus}>\n            <MenuPopup {...rest} ref={ref} id={id} anchor={anchor} label={label} size={size} placement={placement} matchWidth={matchWidth} className={className}>\n                {children}\n            </MenuPopup>\n        </MenuRoot>\n    );\n}\n\nexport interface MenuItemProps extends Omit<ComponentProps<'div'>, 'label' | 'onClick' | 'shortcut' | 'kind' | 'dangerDescription' | 'disabled' | 'selectable' | 'checked' | 'defaultChecked' | 'onCheckedChange' | 'value' | 'icon' | 'children'> {\n    label: string;\n    /** Activating it (click, Enter, Space); the menu closes. */\n    onClick?: () => void;\n    /** A hint only (nothing is registered). */\n    shortcut?: string;\n    kind?: 'default' | 'danger';\n    /** Read after the label of a danger item. */\n    dangerDescription?: string;\n    disabled?: boolean;\n    /** Carbon `MenuItemSelectable`: a menuitemcheckbox. */\n    selectable?: boolean;\n    checked?: boolean;\n    defaultChecked?: boolean;\n    onCheckedChange?: (checked: boolean) => void;\n    /** Inside a single-selection group: the value it stands for (default: the label). */\n    value?: string;\n    /** 16px icon (every row gets the icon column when one item has one). */\n    icon?: ReactNode;\n    /** Child items: shown in a submenu beside this item. */\n    children?: ReactNode;\n}\n\nconst checkmark = <path d=\"M6 12.4 2.3 8.7l.7-.7 3 3 6.3-6.3.7.7z\" />;\n\n// --ui-menu-item-height: a design can give every menu one row height\nconst ROW_HEIGHT: Record<MenuSize, string> = { xs: 'h-[var(--ui-menu-item-height,24px)]', sm: 'h-[var(--ui-menu-item-height,32px)]', md: 'h-[var(--ui-menu-item-height,40px)]', lg: 'h-[var(--ui-menu-item-height,48px)]' };\n\n/** A row: every row of a menu gets the selection and icon columns when any row needs them (Carbon). */\nfunction itemClasses(look: MenuLookValue, danger: boolean, disabled: boolean) {\n    let grid = 'grid-cols-[1fr_max-content]';\n    if (look.icons && look.selectable) grid = 'grid-cols-[1rem_1rem_1fr_max-content]';\n    else if (look.icons || look.selectable) grid = 'grid-cols-[1rem_1fr_max-content]';\n    return cn(\n        'box-border grid cursor-pointer items-center gap-x-2 px-4 rounded-[var(--ui-menu-item-radius,0px)] text-[color:var(--ui-menu-item-ink,var(--ui-ink-muted))] type-body-sm leading-[18px]! outline-none transition-[background-color] duration-(--ui-duration-fast) ease-carbon',\n        grid,\n        ROW_HEIGHT[look.size],\n        'hover:bg-ghost-hover hover:text-ink focus:outline-[length:var(--ui-focus-width,2px)] focus:outline-solid focus:-outline-offset-2 focus:outline-[color:var(--ui-menu-item-active-outline,var(--ui-focus))] focus:not-focus-visible:outline-[color:var(--ui-menu-item-pointer-outline,var(--ui-menu-item-active-outline,var(--ui-focus)))] [@media_screen_and_(prefers-contrast)]:focus:outline-dotted aria-expanded:bg-ghost-hover aria-expanded:text-ink forced-colors:focus:outline-[Highlight]',\n        // --ui-menu-item-active-*: a design can show the focused row as a fill instead of the ring, as the lists' highlight\n        !danger && 'focus:not-hover:not-aria-expanded:bg-[color:var(--ui-menu-item-active-background,transparent)]',\n        danger && 'hover:bg-button-danger hover:text-on-primary focus:bg-button-danger focus:text-on-primary',\n        disabled && 'cursor-not-allowed bg-transparent text-ink-disabled hover:bg-transparent hover:text-ink-disabled',\n    );\n}\n\n/** The check mark column: the mark on a checked checkbox or radio item. */\nfunction CheckCell() {\n    const { checked } = MenuPrimitive.useMenuItemContext();\n    return (\n        <span className=\"flex items-center\" aria-hidden=\"true\">\n            <svg className=\"size-4 fill-current\" viewBox=\"0 0 16 16\">\n                {checked ? checkmark : null}\n            </svg>\n        </span>\n    );\n}\n\ninterface ItemCellsProps {\n    look: MenuLookValue;\n    icon?: ReactNode;\n    label: string;\n    /** Read after a danger item's label. */\n    dangerDescription?: string;\n    submenu: boolean;\n    shortcut?: ReactNode;\n}\n\n/** A row's cells: the check mark and icon columns (when the menu has them), the label, then the submenu arrow or the shortcut. */\nfunction ItemCells({ look, icon, label, dangerDescription, submenu, shortcut }: Readonly<ItemCellsProps>) {\n    return (\n        <>\n            {look.selectable ? <CheckCell /> : null}\n            {look.icons ? <span className=\"flex items-center [&_svg]:size-4 [&_svg]:fill-current\">{icon}</span> : null}\n            <span className=\"truncate\">\n                {label}\n                {dangerDescription ? <span className=\"sr-only\">{dangerDescription}</span> : null}\n            </span>\n            {submenu ? (\n                <span className=\"flex\" aria-hidden=\"true\">\n                    <svg className=\"size-4 fill-current rtl:-scale-x-100\" viewBox=\"0 0 16 16\">\n                        <path d=\"M11 8 6 13l-.7-.7L9.6 8 5.3 3.7 6 3z\" />\n                    </svg>\n                </span>\n            ) : (\n                <span className=\"flex\">{shortcut}</span>\n            )}\n        </>\n    );\n}\n\nexport function MenuItem({ label, onClick, shortcut, kind = 'default', dangerDescription, disabled, selectable, checked, defaultChecked = false, onCheckedChange, value, icon, children, ...rest }: Readonly<MenuItemProps>) {\n    const look = useContext(MenuLookContext);\n    const radio = useContext(RadioGroupContext);\n    if (!look) throw new Error('<MenuItem> goes inside <Menu>');\n    const hasSubmenu = Children.toArray(children).some(isValidElement);\n    const part = { ...rest, label, disabled, 'data-icon': icon ? '' : undefined, className: itemClasses(look, kind === 'danger', !!disabled) };\n    const cells = <ItemCells look={look} icon={icon} label={label} dangerDescription={kind === 'danger' ? dangerDescription : undefined} submenu={hasSubmenu} shortcut={shortcut} />;\n    if (hasSubmenu) {\n        return (\n            <MenuPrimitive.SubmenuRoot>\n                <MenuPrimitive.SubmenuTrigger {...part}>\n                    {cells}\n                    <MenuPopup label={label} size={look.size}>\n                        {children}\n                    </MenuPopup>\n                </MenuPrimitive.SubmenuTrigger>\n            </MenuPrimitive.SubmenuRoot>\n        );\n    }\n    if (radio) {\n        return (\n            <MenuPrimitive.RadioItem {...part} value={value ?? label} onClick={onClick}>\n                {cells}\n            </MenuPrimitive.RadioItem>\n        );\n    }\n    if (selectable) {\n        return (\n            <MenuPrimitive.CheckboxItem {...part} checked={checked} defaultChecked={defaultChecked} onCheckedChange={onCheckedChange} onClick={onClick}>\n                {cells}\n            </MenuPrimitive.CheckboxItem>\n        );\n    }\n    return (\n        <MenuPrimitive.Item {...part} onClick={onClick}>\n            {cells}\n        </MenuPrimitive.Item>\n    );\n}\n\n/** Carbon `MenuItemDivider`: a 1px separator with 4px above and below. */\nexport function MenuItemDivider({ ...rest }: Readonly<ComponentProps<'hr'>>) {\n    return <MenuPrimitive.Separator {...rest} className=\"mx-0 my-1 block h-px w-full border-0 bg-hairline\" />;\n}\n\n/**\n * Carbon `MenuItemGroup` (`role=\"group\"` named by `label`) and `MenuItemRadioGroup`\n * (`selection=\"single\"`: its items are menuitemradio, exactly one checked).\n */\nexport function MenuItemGroup({ label, selection = 'none', value, defaultValue = '', onChange, children }: Readonly<{ label?: string; selection?: 'none' | 'single'; value?: string; defaultValue?: string; onChange?: (value: string) => void; children: ReactNode }>) {\n    if (selection !== 'single') {\n        return (\n            <MenuPrimitive.Group aria-label={label} className=\"block\">\n                {children}\n            </MenuPrimitive.Group>\n        );\n    }\n    return (\n        <RadioGroupContext.Provider value>\n            <MenuPrimitive.RadioGroup aria-label={label} className=\"block\" value={value} defaultValue={defaultValue} onValueChange={onChange}>\n                {children}\n            </MenuPrimitive.RadioGroup>\n        </RadioGroupContext.Provider>\n    );\n}\n\n/** A menu trigger's state with the APG menu button keys: ↓ opens on the first item, ↑ on the last (for a trigger of your own beside a `Menu`). */\nexport function useMenuTrigger() {\n    const [open, setOpen] = useState(false);\n    const [focus, setFocus] = useState<MenuFocus>('first');\n    const onKeyDown = (event: { key: string; preventDefault: () => void }) => {\n        if ((event.key !== 'ArrowDown' && event.key !== 'ArrowUp') || open) return;\n        event.preventDefault();\n        setFocus(event.key === 'ArrowUp' ? 'last' : 'first');\n        setOpen(true);\n    };\n    const toggle = () => {\n        setFocus('first');\n        setOpen(!open);\n    };\n    return { open, setOpen, focus, onKeyDown, toggle };\n}\n\n/** The 16px chevron of a menu trigger, turned while the menu is open. */\nexport const menuChevron = (open: boolean) => (\n    <svg className={cn('fill-current transition-transform duration-(--ui-duration-moderate) ease-carbon forced-colors:fill-[CanvasText]', open && '[transform:rotate(180deg)]')} viewBox=\"0 0 16 16\" aria-hidden=\"true\">\n        <path d=\"M8 11 3 6l.7-.7L8 9.6l4.3-4.3.7.7z\" />\n    </svg>\n);\n\n/** The open state of a menu trigger (MenuButton, ComboButton, OverflowMenu), controlled or not. */\nexport interface MenuOpenProps {\n    /** Whether the menu is open, controlled (Lit `open`); opening it moves focus to its first item as a click does. */\n    open?: boolean;\n    /** Open on first render, uncontrolled. */\n    defaultOpen?: boolean;\n    /** After the user opened or closed the menu: the trigger, Esc, Tab, a click outside, an item picked (Lit `ui-toggle`). */\n    onOpenChange?: (open: boolean) => void;\n}\n\n/**\n * Carbon `MenuButton`: a button (primary, tertiary or ghost) with a chevron that opens a menu of\n * its children; menu rows follow the button size. With `placement` bottom / top the menu is as wide\n * as the button.\n */\nexport function MenuButton({ label, kind = 'primary', size = 'lg', placement = 'bottom', disabled, open, defaultOpen, onOpenChange, children, className, ...rest }: Readonly<Omit<ComponentProps<'span'>, 'label' | 'kind' | 'size' | 'placement' | 'disabled' | 'children' | 'className' | keyof MenuOpenProps> & MenuOpenProps & { label: string; kind?: Extract<ButtonKind, 'primary' | 'tertiary' | 'ghost'>; size?: 'sm' | 'md' | 'lg'; placement?: Placement; disabled?: boolean; children: ReactNode; className?: string }>) {\n    return (\n        <span {...rest} className={cn('inline-block', className)}>\n            <MenuPrimitive.Root open={open} defaultOpen={defaultOpen} onOpenChange={onOpenChange}>\n                <MenuPrimitive.Trigger\n                    disabled={disabled}\n                    render={(props, { open: shown }) => (\n                        <Button {...props} kind={kind} size={size} icon={menuChevron(shown)} className={kind === 'ghost' ? undefined : 'min-w-48'}>\n                            {label}\n                        </Button>\n                    )}\n                />\n                <MenuPopup label={label} size={size} placement={placement} matchWidth={placement === 'bottom' || placement === 'top'}>\n                    {children}\n                </MenuPopup>\n            </MenuPrimitive.Root>\n        </span>\n    );\n}\n\nconst dots = (\n    <svg viewBox=\"0 0 16 16\" aria-hidden=\"true\">\n        <circle cx=\"8\" cy=\"4\" r=\"1.5\" />\n        <circle cx=\"8\" cy=\"8\" r=\"1.5\" />\n        <circle cx=\"8\" cy=\"12\" r=\"1.5\" />\n    </svg>\n);\n\n/**\n * Carbon `OverflowMenu`: an icon button (⋮ by default) named by its tooltip, opening a menu of its children.\n * `triggerClassName` restyles the button (as `<ui-overflow-menu>`'s `trigger` part; a collapsed breadcrumb's \"…\").\n */\nexport function OverflowMenu({ label, size = 'md', placement = 'bottom-start', tooltipPlacement = 'bottom', icon, disabled, lang, open, defaultOpen, onOpenChange, children, className, triggerClassName, ...rest }: Readonly<Omit<ComponentProps<'span'>, 'label' | 'size' | 'placement' | 'tooltipPlacement' | 'icon' | 'disabled' | 'lang' | 'children' | 'className' | keyof MenuOpenProps> & MenuOpenProps & { label?: string; size?: 'sm' | 'md' | 'lg'; placement?: Placement; tooltipPlacement?: Placement; icon?: ReactNode; disabled?: boolean; lang?: string; children: ReactNode; className?: string; triggerClassName?: string }>) {\n    const t = useTranslation(lang).common;\n    const name = label ?? t.options;\n    const side = { sm: 'size-8', md: 'size-10', lg: 'size-12' }[size];\n    return (\n        <span {...rest} className={cn('inline-block', className)}>\n            <MenuPrimitive.Root open={open} defaultOpen={defaultOpen} onOpenChange={onOpenChange}>\n                <Tooltip text={name} asLabel placement={tooltipPlacement}>\n                    <MenuPrimitive.Trigger\n                        tabIndex={0} // as Carbon's overflow menu trigger: Safari then focuses it on click and Tab reaches it\n                        aria-haspopup=\"true\"\n                        disabled={disabled}\n                        className={cn(\n                            'flex cursor-pointer items-center justify-center rounded-[var(--ui-button-radius,0px)] border-0 bg-transparent p-0 text-icon-primary outline-none [&_svg]:size-4 [&_svg]:fill-current',\n                            side,\n                            'transition-[outline,background-color] duration-(--ui-duration-moderate) ease-(--ui-easing-entrance) hover:bg-canvas-hover focus-visible:outline-[length:var(--ui-focus-width,2px)] focus-visible:outline-solid focus-visible:[outline-offset:var(--ui-focus-offset,-2px)] focus-visible:outline-focus',\n                            // open: it joins the menu (Carbon); --ui-overflow-open-* let a design keep it a plain button\n                            'aria-expanded:bg-[color:var(--ui-overflow-open-background,var(--ui-surface-1))] aria-expanded:shadow-[var(--ui-overflow-open-shadow,0_2px_6px_rgb(0_0_0/0.3))] aria-expanded:transition-none',\n                            'disabled:cursor-not-allowed disabled:bg-transparent disabled:text-icon-disabled',\n                            'forced-colors:text-[CanvasText] forced-colors:disabled:text-[GrayText]',\n                            triggerClassName,\n                        )}\n                    >\n                        {icon ?? dots}\n                    </MenuPrimitive.Trigger>\n                </Tooltip>\n                <MenuPopup label={name} size={size} placement={placement}>\n                    {children}\n                </MenuPopup>\n            </MenuPrimitive.Root>\n        </span>\n    );\n}\n"
    }
  ]
}
