{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "tw-popover",
  "type": "registry:ui",
  "title": "react-tw/popover.tsx",
  "description": "Carbon `Popover` as a React + Tailwind component, the look and rules of `<ui-popover>` on the 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-hover-open",
    "@kanok-ui/core-position",
    "@kanok-ui/tw-dom",
    "@kanok-ui/tw-floating",
    "@kanok-ui/tw-i18n",
    "@kanok-ui/tw-refs",
    "@kanok-ui/tw-theme",
    "@kanok-ui/tw-utils"
  ],
  "files": [
    {
      "path": "src/react-tw/popover.tsx",
      "type": "registry:ui",
      "target": "components/ui/react-tw/popover.tsx",
      "content": "import { cloneElement, isValidElement, useEffect, useLayoutEffect, useRef, type CSSProperties, type FocusEvent, type PointerEvent, type ReactElement, type ReactNode, type ComponentProps } from 'react';\nimport type { Placement } from '../core/position.ts';\nimport { HOVER_CLOSE_DELAY, HOVER_OPEN_DELAY, hovers, taps } from '../core/hover-open.ts';\nimport { Popover as PopoverPrimitive } from '@purpurabog/ui/headless';\nimport { activeElementOf } from './lib/dom.ts';\nimport { caretClasses } from './lib/floating.ts';\nimport { useTranslation } from './lib/i18n.ts';\nimport { useMergedRefs } from './lib/refs.ts';\nimport { cn } from './lib/utils.ts';\n\n/** Carbon popover caret 12×6, 10px off the trigger (`popover-offset` with a caret). */\nconst CARET = { '--_caret-w': '12px', '--_caret-h': '6px' } as CSSProperties;\nconst CARET_GAP = 10;\n\nexport type PopoverCloseReason = 'escape' | 'outside';\n\n/** What asked for a change: `autoClose` / `openOnHover` closes, or (`openOnHover`) the pointer, focus or a tap on the trigger. */\nexport type PopoverChangeReason = PopoverCloseReason | 'hover' | 'focus' | 'focus-out' | 'trigger';\n\nexport interface PopoverProps extends Omit<ComponentProps<'span'>, 'open' | 'onOpenChange' | 'autoClose' | 'openOnHover' | 'trigger' | 'placement' | 'caret' | 'dropShadow' | 'highContrast' | 'tabTip' | 'label' | 'children' | 'className' | 'contentClassName'> {\n    /** Controlled: the box shows while true. */\n    open: boolean;\n    /** With `autoClose`: Escape and outside clicks ask to close (`false` + the reason); with `openOnHover`, hover, focus and taps ask too. */\n    onOpenChange?: (open: boolean, reason: PopoverChangeReason) => void;\n    autoClose?: boolean;\n    /**\n     * Beyond Carbon (as `<ui-popover open-on-hover>`; the tooltip's timings): asks to open after the mouse rests on\n     * the trigger for 100ms and to close 300ms after it leaves the trigger and the box (it can move onto the box);\n     * keyboard focus on the trigger asks to open at once, focus leaving both asks to close; a tap (touch, pen) on\n     * the trigger toggles; Escape and a press outside ask to close. Focus in the box, or on the trigger by keyboard, holds it open.\n     */\n    openOnHover?: boolean;\n    /** The element the box sits beside; gets `aria-expanded` / `aria-controls`. */\n    trigger: ReactElement<Record<string, unknown>>;\n    placement?: Placement;\n    /** On by default. */\n    caret?: boolean;\n    /** On by default. */\n    dropShadow?: boolean;\n    /** Inverse colours. */\n    highContrast?: boolean;\n    /** Carbon `isTabTip`: square, flush under the trigger, no caret. */\n    tabTip?: boolean;\n    /** Accessible name of the box (`role=\"group\"`). */\n    label?: string;\n    children: ReactNode;\n    className?: string;\n    contentClassName?: string;\n}\n\n/**\n * Carbon `Popover` as a React + Tailwind component, the look and rules of `<ui-popover>` on the\n * headless `Popover`: your own content beside a trigger, in the top layer with a caret (12×6, 10px\n * off), flipped when it doesn't fit. You hold `open`; `autoClose` asks to close on Escape (focus back to the trigger) and on\n * outside clicks. Variants: no caret, no drop shadow, high contrast, tab tip. Beyond Carbon, `openOnHover` asks to\n * open and close on hover, focus and taps, as a hover preview.\n */\nexport function Popover({ open, onOpenChange, autoClose, openOnHover = false, trigger, placement = 'bottom', caret = true, dropShadow = true, highContrast, tabTip, label, children, className, contentClassName, ref, ...rest }: Readonly<PopoverProps>) {\n    const withCaret = caret && !tabTip;\n    const hover = useHoverOpen(openOnHover, open, (next, reason) => onOpenChange?.(next, reason));\n    const areaRef = useMergedRefs(hover.area, ref);\n    return (\n        <PopoverPrimitive.Root\n            open={open}\n            onOpenChange={(next, reason) => {\n                // only autoClose / openOnHover ask (no Trigger part, no focus-out rule): Escape and outside presses\n                if (reason !== 'escape' && reason !== 'outside') return;\n                if (reason === 'escape') hover.escaped();\n                onOpenChange?.(next, reason);\n            }}\n            dismissible={!!autoClose || openOnHover}\n            placement={placement}\n            gap={withCaret ? CARET_GAP : 0}\n            caret={withCaret}\n        >\n            <PopoverPrimitive.Anchor {...rest} ref={areaRef} className={cn('inline-block', className)}>\n                <OwnTrigger trigger={trigger} handlers={hover.trigger} />\n                <PopoverPrimitive.Popup\n                    {...hover.popup}\n                    aria-label={label}\n                    style={CARET}\n                    className={cn(\n                        // the menu settings (--ui-menu-border / -radius): a design rounds and outlines every floating surface alike\n                        'group/bubble absolute inset-auto m-0 box-border w-max max-w-[368px] overflow-visible rounded-[var(--ui-menu-radius,var(--ui-radius-xs))] ui-menu-edge bg-[var(--ui-overlay-background,var(--ui-surface-1))] p-0 text-ink type-body-sm',\n                        dropShadow && '[filter:drop-shadow(0_2px_2px_rgb(0_0_0/0.2))]',\n                        highContrast && 'bg-inverse-surface-1 text-inverse-ink',\n                        tabTip && 'rounded-none',\n                        'forced-colors:border forced-colors:border-solid forced-colors:border-[CanvasText]',\n                        contentClassName,\n                    )}\n                >\n                    {children}\n                    {withCaret ? <span aria-hidden=\"true\" className={caretClasses} /> : null}\n                </PopoverPrimitive.Popup>\n            </PopoverPrimitive.Anchor>\n        </PopoverPrimitive.Root>\n    );\n}\n\ntype Handler = (event: never) => void;\n\n/** Your trigger element with `aria-expanded` / `aria-controls` (and the `openOnHover` handlers, after its own). */\nfunction OwnTrigger({ trigger, handlers }: Readonly<{ trigger: ReactElement<Record<string, unknown>>; handlers?: Record<string, Handler> }>) {\n    const { triggerProps } = PopoverPrimitive.usePopoverContext();\n    if (!isValidElement(trigger)) return trigger;\n    const chained: Record<string, Handler> = {};\n    for (const [name, handler] of Object.entries(handlers ?? {})) {\n        const own = trigger.props[name] as Handler | undefined;\n        chained[name] = (event) => {\n            own?.(event);\n            handler(event);\n        };\n    }\n    return cloneElement(trigger, { ...triggerProps, ...chained });\n}\n\ntype ChangeRequest = (open: boolean, reason: PopoverChangeReason) => void;\n\n/** The focused element, followed down through open shadow roots (a custom element's inner control). */\nfunction deepFocus(active: Element) {\n    let el = active;\n    while (el.shadowRoot?.activeElement) el = el.shadowRoot.activeElement;\n    return el;\n}\n\n/**\n * `openOnHover` (beyond Carbon, as `<ui-popover open-on-hover>`): handlers for the trigger and the box, the timers,\n * and Escape from elsewhere on the page while open; it only asks (`request`), the parent holds `open`. Off: no handlers.\n */\nfunction useHoverOpen(enabled: boolean, open: boolean, request: ChangeRequest) {\n    const area = useRef<HTMLSpanElement>(null);\n    const timer = useRef<ReturnType<typeof setTimeout>>(undefined);\n    const blurTimer = useRef<ReturnType<typeof setTimeout>>(undefined);\n    /** The mouse is on the trigger or the box. */\n    const hovered = useRef(false);\n    /** The pointer type of the last press on the trigger: its click toggles when it was a tap. */\n    const pressType = useRef('');\n    /** Escape asked to close from inside: focus going back to the trigger is not a new keyboard focus that opens it. */\n    const refocusing = useRef(false);\n    const latest = useRef({ open, request });\n    useLayoutEffect(() => {\n        latest.current = { open, request };\n    });\n\n    // off or unmounted: no timer left behind\n    useEffect(\n        () => () => {\n            clearTimeout(timer.current);\n            clearTimeout(blurTimer.current);\n            hovered.current = false;\n        },\n        [enabled],\n    );\n\n    // Escape from elsewhere (the mouse showed it, focus is not inside) closes this box only, as the tooltip;\n    // one from inside goes to the headless Root (dismissible), which gives focus back to the trigger\n    useEffect(() => {\n        if (!enabled || !open) return;\n        const onKey = (event: KeyboardEvent) => {\n            if (event.key !== 'Escape' || (area.current && event.composedPath().includes(area.current))) return;\n            event.preventDefault();\n            event.stopPropagation();\n            latest.current.request(false, 'escape');\n        };\n        document.addEventListener('keydown', onKey, true);\n        return () => document.removeEventListener('keydown', onKey, true);\n    }, [enabled, open]);\n\n    const change = (next: boolean, reason: PopoverChangeReason) => {\n        if (next !== latest.current.open) latest.current.request(next, reason);\n    };\n    /** Focus in the box holds it open, and on the trigger by keyboard (a click or a tap there doesn't). */\n    const focusHolds = () => {\n        const box = area.current;\n        const active = activeElementOf(box);\n        if (!box || !active || !box.contains(active)) return false;\n        return !box.firstElementChild?.contains(active) || deepFocus(active).matches(':focus-visible');\n    };\n    const closeUnlessHeld = (reason: PopoverChangeReason) => {\n        if (!hovered.current && !focusHolds()) change(false, reason);\n    };\n    const later = (next: boolean, ms: number) => {\n        clearTimeout(timer.current);\n        timer.current = setTimeout(() => {\n            if (next) change(true, 'hover');\n            else closeUnlessHeld('hover');\n        }, ms);\n    };\n    const leave = (event: PointerEvent) => {\n        if (!hovers(event.pointerType)) return;\n        hovered.current = false;\n        later(false, HOVER_CLOSE_DELAY);\n    };\n    // focus left the trigger or the box: a tick later it has landed\n    const blur = () => {\n        clearTimeout(blurTimer.current);\n        blurTimer.current = setTimeout(() => closeUnlessHeld('focus-out'), 0);\n    };\n\n    const trigger: Record<string, Handler> = {\n        onPointerEnter: (event: PointerEvent) => {\n            if (!hovers(event.pointerType)) return;\n            hovered.current = true;\n            later(true, HOVER_OPEN_DELAY);\n        },\n        onPointerLeave: leave,\n        // keyboard focus only, as the tooltip: a click or a tap has its own rule\n        onFocus: (event: FocusEvent) => {\n            if (refocusing.current || !event.target.matches(':focus-visible')) return;\n            clearTimeout(timer.current);\n            change(true, 'focus');\n        },\n        onBlur: blur,\n        onPointerDown: (event: PointerEvent) => {\n            pressType.current = event.pointerType;\n        },\n        onClick: () => {\n            const tapped = taps(pressType.current);\n            pressType.current = '';\n            if (tapped) change(!latest.current.open, 'trigger');\n        },\n    };\n    const popup = {\n        onPointerEnter: (event: PointerEvent) => {\n            if (!hovers(event.pointerType)) return;\n            hovered.current = true;\n            clearTimeout(timer.current);\n        },\n        onPointerLeave: leave,\n        onBlur: blur,\n    };\n    return {\n        area,\n        trigger: enabled ? trigger : undefined,\n        popup: enabled ? popup : undefined,\n        /** The headless Root asked to close on Escape: the focus it gives back to the trigger (in the same task) doesn't reopen. */\n        escaped: () => {\n            if (!enabled) return;\n            refocusing.current = true;\n            setTimeout(() => {\n                refocusing.current = false;\n            }, 0);\n        },\n    };\n}\n\nexport interface ToggletipProps extends Omit<ComponentProps<'span'>, 'label' | 'placement' | 'open' | 'onOpenChange' | 'icon' | 'lang' | 'children' | 'className'> {\n    /** Accessible name of the trigger and the box (default: \"More information\"). */\n    label?: string;\n    placement?: Placement;\n    /** Controlled visibility; without it the toggletip keeps its own. */\n    open?: boolean;\n    onOpenChange?: (open: boolean) => void;\n    /** Trigger icon (default: the \"i\" information icon). */\n    icon?: ReactNode;\n    lang?: string;\n    children: ReactNode;\n    className?: string;\n}\n\nconst info = (\n    <svg viewBox=\"0 0 16 16\" aria-hidden=\"true\">\n        <path d=\"M8.5 11V6.5h-2v1h1V11H6v1h4v-1h-1.5ZM8 3.5a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Z\" />\n        <path d=\"M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14ZM8 2a6 6 0 1 0 0 12A6 6 0 0 0 8 2Z\" />\n    </svg>\n);\n\n/**\n * Carbon `Toggletip` as a React + Tailwind component, the look and rules of `<ui-toggletip>` on the\n * headless `Popover` (its `Trigger` and `closeOnFocusOut`): a click-to-open bubble that may hold links or buttons, beside a 24px info button with\n * `aria-expanded`. Escape and outside clicks close it (focus back to the trigger when it was\n * inside); the content follows the trigger in tab order, and focus leaving both closes it.\n */\nexport function Toggletip({ label, placement = 'bottom', open, onOpenChange, icon, lang, children, className, ...rest }: Readonly<ToggletipProps>) {\n    const t = useTranslation(lang).common;\n    const name = label ?? t.moreInfo;\n    return (\n        <PopoverPrimitive.Root open={open} onOpenChange={(next) => onOpenChange?.(next)} closeOnFocusOut placement={placement} gap={CARET_GAP} caret>\n            <span {...rest} className={cn('inline-block align-middle', className)}>\n                <PopoverPrimitive.Trigger\n                    aria-label={name}\n                    className={cn(\n                        'grid size-6 cursor-pointer place-items-center rounded-[var(--ui-icon-control-radius,0px)] border-0 bg-transparent p-0 text-ink-muted outline-none',\n                        'hover:text-ink aria-expanded:text-ink 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                        '[&_svg]:size-4 [&_svg]:fill-current',\n                    )}\n                >\n                    {icon ?? info}\n                </PopoverPrimitive.Trigger>\n                <PopoverPrimitive.Popup\n                    aria-label={name}\n                    style={CARET}\n                    className={cn(\n                        'group/bubble absolute inset-auto m-0 box-border w-max max-w-[288px] overflow-visible rounded-[var(--ui-menu-radius,var(--ui-radius-xs))] ui-menu-edge bg-[var(--ui-overlay-background,var(--ui-surface-1))] p-4 text-ink type-body-sm leading-[20px]!',\n                        // its plain direct-child links, with no weight, in the link colour, as ::slotted(a) in <ui-toggletip>: a link's own colour (a Link) wins\n                        '[filter:drop-shadow(0_2px_2px_rgb(0_0_0/0.2))] [:where(&)>a]:text-link',\n                        'forced-colors:border forced-colors:border-solid forced-colors:border-[CanvasText]',\n                    )}\n                >\n                    {children}\n                    <span aria-hidden=\"true\" className={caretClasses} />\n                </PopoverPrimitive.Popup>\n            </span>\n        </PopoverPrimitive.Root>\n    );\n}\n"
    }
  ]
}
