{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "tw-header-mega-menu",
  "type": "registry:ui",
  "title": "react-tw/header-mega-menu.tsx",
  "description": "The panel in the bar (Lit `.panel`): a manual popover — the top layer, above a host app's own fixed bars — placed 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": [],
  "registryDependencies": [
    "@kanok-ui/core-mega-menu",
    "@kanok-ui/core-popup",
    "@kanok-ui/tw-header",
    "@kanok-ui/tw-refs",
    "@kanok-ui/tw-theme",
    "@kanok-ui/tw-utils"
  ],
  "files": [
    {
      "path": "src/react-tw/header-mega-menu.tsx",
      "type": "registry:ui",
      "target": "components/ui/react-tw/header-mega-menu.tsx",
      "content": "import { Children, isValidElement, useContext, useEffect, useId, useLayoutEffect, useRef, useState, type ComponentProps, type ReactNode, type RefObject } from 'react';\nimport { outsidePress } from '../core/popup.ts';\nimport { MEGA_HOVER_CLOSE_MS, megaClosed, megaClosesOnLeave, megaHoverDelay, megaHoverPointer, megaTriggerPress, type MegaOpenedBy, type MegaState } from '../core/mega-menu.ts';\nimport { chevron, clearPlacement, InSideNav, menuTitleClass, placeUnderHeader, useBarMenu } from './header.tsx';\nimport { useMergedRefs } from './lib/refs.ts';\nimport { cn } from './lib/utils.ts';\n\n/*\n * The header mega menu as React + Tailwind components, the look and rules of `<ui-header-mega-menu>`,\n * `<ui-header-mega-group>` and `<ui-header-mega-item>`: a menu-bar entry that opens a full-width panel of\n * columns under the header (Vercel's header). The hover delays and what a click does to a panel the\n * pointer opened are core/mega-menu's, shared with the Lit element.\n */\n\n/** Whether an element in `children` (or nested in theirs) is `current`: read from the elements as written, so right on the server too. */\nfunction holdsCurrent(children: ReactNode): boolean {\n    return Children.toArray(children).some((child) => {\n        if (!isValidElement<{ current?: unknown; children?: ReactNode }>(child)) return false;\n        return child.props.current === true || holdsCurrent(child.props.children);\n    });\n}\n\ninterface Timers {\n    open?: ReturnType<typeof setTimeout>;\n    close?: ReturnType<typeof setTimeout>;\n}\n\nconst clearTimers = (timers: Timers) => {\n    clearTimeout(timers.open);\n    clearTimeout(timers.close);\n};\n\nconst hoverOpen: MegaState = { open: true, openedBy: 'hover' };\n\n/**\n * The panel in the bar (Lit `.panel`): a manual popover — the top layer, above a host app's own fixed bars — placed\n * under the header at the width of it, fading in over 110ms (not with reduced motion).\n */\nconst PANEL_CLASS = cn(\n    'fixed inset-auto m-0 box-border max-h-[calc(100vh-var(--_top,48px))] overflow-y-auto border-x-0 border-t-0 p-0 [border-block-end:var(--ui-mega-panel-border,none)]',\n    'bg-[color:var(--ui-mega-panel-background,var(--ui-overlay-background,var(--ui-surface-1)))] shadow-[var(--ui-mega-panel-shadow,0_4px_8px_0_rgb(0_0_0/0.5))]',\n    'transition-[opacity,transform] duration-[var(--ui-duration-fast,110ms)] ease-(--ui-easing) starting:opacity-0 starting:[transform:translateY(-4px)] motion-reduce:transition-none',\n    'forced-colors:[border-block-end:1px_solid_CanvasText]',\n);\n\n/** The columns of groups (Lit `.content`); in the narrow sheet or the side nav, one column. */\nconst GRID_CLASS = 'box-border grid grid-cols-[repeat(auto-fill,minmax(var(--ui-mega-column-width,240px),1fr))] gap-[var(--ui-mega-gap,32px)] p-[var(--ui-mega-padding,24px_32px_32px)]';\nconst COLUMN_CLASS = 'box-border grid grid-cols-[minmax(0,1fr)] gap-6 px-4 pt-2 pb-6';\n\nexport interface HeaderMegaMenuProps extends Omit<ComponentProps<'li'>, 'label' | 'open' | 'defaultOpen' | 'onToggle' | 'current' | 'children'> {\n    /** The entry's text (Lit `label`). */\n    label: string;\n    /** Open (controlled; Lit `open`). */\n    open?: boolean;\n    /** Open at first (uncontrolled). */\n    defaultOpen?: boolean;\n    /** It opened or closed (Lit `ui-toggle`). */\n    onToggle?: (open: boolean) => void;\n    /** Mark it as the current section even while open (Lit `current`). */\n    current?: boolean;\n    /** `<HeaderMegaGroup>`s (Lit's default slot). */\n    children: ReactNode;\n}\n\n/** While the panel shows in the bar: placed under the header (again on resize and scroll), and Escape, a press outside and the latest `apply` close it. */\nfunction usePanel(open: boolean, collapsed: boolean, parts: { entry: HTMLLIElement | null; panel: HTMLDivElement | null; trigger: RefObject<HTMLButtonElement | null> }, close: () => void) {\n    const { entry, panel, trigger } = parts;\n    const live = useRef(close);\n    useLayoutEffect(() => {\n        live.current = close;\n    });\n    useLayoutEffect(() => {\n        if (!open || collapsed || !entry || !panel) return;\n        // placed before it shows: no frame at the wrong place\n        const place = () => {\n            placeUnderHeader(panel, entry);\n            panel.style.setProperty('--_top', panel.style.top);\n        };\n        place();\n        if (!panel.matches(':popover-open')) panel.showPopover();\n        // a finger scroll doesn't close it: only a tap outside does\n        const stopOutside = outsidePress(document, (event: PointerEvent) => {\n            if (!event.composedPath().includes(entry)) live.current();\n        });\n        const onKey = (event: KeyboardEvent) => {\n            if (event.key !== 'Escape') return;\n            event.stopPropagation();\n            live.current();\n            trigger.current?.focus();\n        };\n        document.addEventListener('keydown', onKey, true);\n        window.addEventListener('resize', place);\n        window.addEventListener('scroll', place, { capture: true, passive: true });\n        return () => {\n            if (panel.matches(':popover-open')) panel.hidePopover();\n            clearPlacement(panel);\n            stopOutside();\n            document.removeEventListener('keydown', onKey, true);\n            window.removeEventListener('resize', place);\n            window.removeEventListener('scroll', place, { capture: true });\n        };\n    }, [open, collapsed, entry, panel, trigger]);\n}\n\n/**\n * A header menu-bar entry that opens a full-width panel of HeaderMegaGroup columns under the header (a mega menu, as\n * Vercel's), as `<ui-header-mega-menu>`: put it in HeaderNavigation next to HeaderMenuItems and HeaderMenus.\n * With a mouse, resting on it opens the panel after 150ms (at once while another one of the bar is open); leaving it\n * and its panel closes a panel the pointer opened after 300ms; a finger opens it by a tap. Click / Enter / Space\n * toggle it (a panel the pointer opened stays open); ↓ opens it and moves to the first link. Escape, a press outside,\n * Tab out of it and following one of its links close it (Escape and a link return focus to it). One panel at a time.\n * In a narrow `collapse`d HeaderNavigation or in a SideNav it is an accordion row instead.\n */\nexport function HeaderMegaMenu({ label, open: openProp, defaultOpen = false, onToggle, current = false, children, ref, ...rest }: Readonly<HeaderMegaMenuProps>) {\n    const panelId = useId();\n    const collapsed = useContext(InSideNav);\n    const [own, setOwn] = useState(defaultOpen);\n    const open = openProp ?? own;\n    const [entry, setEntry] = useState<HTMLLIElement | null>(null);\n    const [panel, setPanel] = useState<HTMLDivElement | null>(null);\n    const trigger = useRef<HTMLButtonElement>(null);\n    const entryRef = useMergedRefs(setEntry, ref);\n    const openedBy = useRef<MegaOpenedBy | null>(null);\n    const timers = useRef<Timers>({});\n    const focusFirst = useRef(false);\n    // what the timers read and call: the latest render's\n    const live = useRef({ open, apply: (_next: MegaState) => {} });\n    const state = (): MegaState => ({ open: live.current.open, openedBy: openedBy.current });\n    const bar = useBarMenu(open, () => live.current.apply(megaClosed));\n    const apply = (next: MegaState) => {\n        openedBy.current = next.openedBy;\n        if (next.open && !collapsed) bar.closeOthers();\n        if (next.open === live.current.open) return;\n        live.current = { ...live.current, open: next.open };\n        setOwn(next.open);\n        onToggle?.(next.open);\n    };\n    useLayoutEffect(() => {\n        live.current = { open, apply };\n    });\n    usePanel(open, collapsed, { entry, panel, trigger }, () => apply(megaClosed));\n    useLayoutEffect(() => {\n        if (!open) {\n            openedBy.current = null;\n            clearTimers(timers.current);\n        } else if (focusFirst.current) {\n            focusFirst.current = false;\n            panel?.querySelector<HTMLElement>('a[href]')?.focus();\n        }\n    }, [open, panel]);\n    useEffect(() => {\n        const pending = timers.current;\n        return () => clearTimers(pending);\n    }, []);\n\n    const hoverable = (pointerType: string) => !collapsed && megaHoverPointer(pointerType);\n    const onEnter = () => {\n        clearTimers(timers.current);\n        if (open) return;\n        const delay = megaHoverDelay(bar.anotherOpen());\n        if (delay === 0) apply(hoverOpen);\n        else timers.current.open = setTimeout(() => live.current.apply(hoverOpen), delay);\n    };\n    const onLeave = () => {\n        clearTimeout(timers.current.open);\n        if (!megaClosesOnLeave(state())) return;\n        timers.current.close = setTimeout(() => {\n            if (megaClosesOnLeave(state())) live.current.apply(megaClosed);\n        }, MEGA_HOVER_CLOSE_MS);\n    };\n    const onArrowDown = () => {\n        if (open) {\n            panel?.querySelector<HTMLElement>('a[href]')?.focus();\n            return;\n        }\n        focusFirst.current = true;\n        apply({ open: true, openedBy: 'keyboard' });\n    };\n    // closed, it shows the current bar when one of its items is current\n    const showCurrent = current || (!open && holdsCurrent(children));\n    return (\n        <li {...rest}\n            ref={entryRef}\n            className={cn('relative block', collapsed ? 'h-auto' : 'h-full')}\n            onPointerEnter={(event) => {\n                rest.onPointerEnter?.(event);\n                if (hoverable(event.pointerType)) onEnter();\n            }}\n            onPointerLeave={(event) => {\n                rest.onPointerLeave?.(event);\n                if (hoverable(event.pointerType)) onLeave();\n            }}\n            onBlur={(event) => {\n                rest.onBlur?.(event);\n                const next = event.relatedTarget as Node | null;\n                if (!collapsed && next && !event.currentTarget.contains(next)) apply(megaClosed);\n            }}\n        >\n            <button\n                ref={trigger}\n                type=\"button\"\n                tabIndex={0} // as HeaderMenu's title: Safari then focuses it on click and Tab reaches it\n                aria-expanded={open}\n                aria-controls={panelId}\n                className={cn(menuTitleClass(open, showCurrent, collapsed), collapsed && 'h-12 w-full justify-between')}\n                onClick={(event) => {\n                    clearTimers(timers.current);\n                    // a click from Enter / Space has no pointer position (detail 0)\n                    apply(megaTriggerPress(state(), event.detail === 0 ? 'keyboard' : 'click'));\n                }}\n                onKeyDown={(event) => {\n                    if (event.key !== 'ArrowDown') return;\n                    event.preventDefault();\n                    onArrowDown();\n                }}\n            >\n                {label}\n                {chevron(open)}\n            </button>\n            <div /* NOSONAR: following one of its links closes the panel; the links take the keyboard */\n                ref={setPanel}\n                id={panelId}\n                popover={collapsed ? undefined : 'manual'}\n                hidden={collapsed && !open}\n                className={cn('text-ink', !collapsed && PANEL_CLASS)}\n                onClick={(event) => {\n                    if (collapsed || !(event.target as Element).closest('a[href]')) return;\n                    apply(megaClosed);\n                    trigger.current?.focus();\n                }}\n            >\n                <div className={collapsed ? COLUMN_CLASS : GRID_CLASS}>{children}</div>\n            </div>\n        </li>\n    );\n}\n\nexport interface HeaderMegaGroupProps extends Omit<ComponentProps<'div'>, 'children'> {\n    /** The small heading over the links, which names their list (Lit `heading`). */\n    heading?: string;\n    /** `<HeaderMegaItem>`s (Lit's default slot). */\n    children: ReactNode;\n}\n\n/** A column of a HeaderMegaMenu panel, as `<ui-header-mega-group>`: a small heading over a list of HeaderMegaItems, the list named by it. */\nexport function HeaderMegaGroup({ heading, children, ...rest }: Readonly<HeaderMegaGroupProps>) {\n    const headingId = useId();\n    return (\n        <div {...rest} className=\"block min-w-0\">\n            {heading ? (\n                <p id={headingId} className=\"m-0 mb-2 text-ink-muted [font:var(--ui-mega-heading-font,var(--ui-font-caption))] tracking-[var(--ui-tracking-caption,0.32px)]\">\n                    {heading}\n                </p>\n            ) : null}\n            <ul aria-labelledby={heading ? headingId : undefined} className=\"m-0 flex list-none flex-col gap-0.5 p-0\">\n                {children}\n            </ul>\n        </div>\n    );\n}\n\nexport interface HeaderMegaItemProps extends Omit<ComponentProps<'a'>, 'children' | 'className'> {\n    /** Where it goes (Lit `href`). */\n    href?: string;\n    /** A line under the title (Lit `description`). */\n    description?: string;\n    /** A 20px icon before the title (Lit's `icon` slot). */\n    icon?: ReactNode;\n    /** The current page: `aria-current=\"page\"` (Lit `current`). */\n    current?: boolean;\n    /** The title (Lit's default slot). */\n    children: ReactNode;\n}\n\n/** One link of a HeaderMegaGroup, as `<ui-header-mega-item>`: a title, optionally an icon and a description; following it closes the mega menu. */\nexport function HeaderMegaItem({ href = '#', description, icon, current = false, children, ...rest }: Readonly<HeaderMegaItemProps>) {\n    return (\n        <li className=\"block\">\n            <a {...rest}\n                href={href}\n                aria-current={current ? 'page' : undefined}\n                className={cn(\n                    '-mx-2 box-border flex items-start gap-3 rounded-[var(--ui-mega-item-radius,0px)] p-2 text-[color:var(--ui-mega-item-ink,var(--ui-ink-muted))] no-underline outline-none transition-[background-color,color] duration-(--ui-duration-moderate) ease-[ease]',\n                    'hover:bg-[color:var(--ui-mega-item-hover-background,var(--ui-layer-hover-1))] hover:text-ink focus-visible:outline-[length:var(--ui-focus-width,2px)] focus-visible:-outline-offset-2 focus-visible:outline-focus focus-visible:outline-solid',\n                    current && 'text-ink forced-colors:outline-1 forced-colors:outline-[Highlight] forced-colors:outline-solid',\n                )}\n            >\n                {icon ? (\n                    <span aria-hidden=\"true\" className=\"mt-0.5 grid size-5 flex-none place-items-center fill-current\">\n                        {icon}\n                    </span>\n                ) : null}\n                <span className=\"flex min-w-0 flex-col gap-0.5\">\n                    <span className={cn('[font:var(--ui-mega-item-font,var(--ui-font-body-sm))] tracking-[var(--ui-tracking-body)]', current && 'font-semibold!')}>{children}</span>\n                    {description ? <span className=\"text-ink-muted [font:var(--ui-font-body-sm)] tracking-[var(--ui-tracking-body)]\">{description}</span> : null}\n                </span>\n            </a>\n        </li>\n    );\n}\n"
    }
  ]
}
