{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "popover",
  "type": "registry:ui",
  "title": "<ui-popover>",
  "description": "Carbon `Popover`: the floating box primitive behind tooltips, toggletips and menus, for when you need your own content next to a trigger. Put the trigger in slot `trigger` and the content in the default slot; set `open` yourself (or use `auto-close` to let Escape and outside clicks close it). Variants: `caret` (default on, 12×6, 10px offset), `drop-shadow` (default on), `high-contrast` (inverse colours), `tab-tip` (square, flush under the trigger, no caret). Lives in the top layer at document coordinates and flips when it does not fit. Beyond Carbon, `open-on-hover` lets it open itself, as a hover preview: see `openOnHover`. 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": [
    "lit@^3.3.0"
  ],
  "registryDependencies": [
    "@kanok-ui/core-hover-open",
    "@kanok-ui/core-popup",
    "@kanok-ui/shared-align",
    "@kanok-ui/shared-element",
    "@kanok-ui/shared-events",
    "@kanok-ui/shared-field",
    "@kanok-ui/shared-position",
    "@kanok-ui/tokens"
  ],
  "files": [
    {
      "path": "src/primitives/popover/popover.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/popover/popover.ts",
      "content": "import { html, css, nothing } from 'lit';\nimport { customElement, property, query, queryAssignedElements } from 'lit/decorators.js';\nimport { uid, deepActiveElement, defaultTrue } from '../shared/field.ts';\nimport { caretStyles, placeWithCaret, placeFloating, type Placement } from '../shared/position.ts';\nimport type { OpenDetail, CloseDetail } from '../shared/events.ts';\nimport { WithAlign } from '../shared/align.ts';\nimport { UiElement } from '../shared/element.ts';\nimport { outsidePress, trackAnchor } from '../../core/popup.ts';\nimport { HOVER_CLOSE_DELAY, HOVER_OPEN_DELAY, hovers, taps } from '../../core/hover-open.ts';\n\n/** Whether `node` is `root` or inside it, across shadow roots. */\nfunction within(root: Node, node: Node | null): boolean {\n    for (let at = node; at; at = at.parentNode ?? (at as ShadowRoot).host ?? null) if (at === root) return true;\n    return false;\n}\n\n/**\n * Carbon `Popover`: the floating box primitive behind tooltips, toggletips and menus, for when\n * you need your own content next to a trigger. Put the trigger in slot `trigger` and the content\n * in the default slot; set `open` yourself (or use `auto-close` to let Escape and outside clicks\n * close it). Variants: `caret` (default on, 12×6, 10px offset), `drop-shadow` (default on),\n * `high-contrast` (inverse colours), `tab-tip` (square, flush under the trigger, no caret).\n * Lives in the top layer at document coordinates and flips when it does not fit.\n * Beyond Carbon, `open-on-hover` lets it open itself, as a hover preview: see `openOnHover`.\n *\n * @slot trigger - The element the box is positioned against\n * @slot - Box content\n * @fires ui-toggle - detail: { open } after it opens or closes\n * @fires ui-request-close - cancelable; `auto-close` fires it before closing on Escape / outside click\n * @csspart content - The floating box\n * @csspart caret - The arrow\n * @attr align - Carbon's name for `placement` (same values)\n * @cssprop --ui-menu-border / --ui-menu-radius - Border and corners of the bubble (the menu settings)\n */\n@customElement('ui-popover')\nexport class UiPopover extends WithAlign(UiElement) {\n    static override readonly styles = [caretStyles, css`\n        :host {\n            display: inline-block;\n        }\n\n        .bubble {\n            --_caret-w: 12px;\n            --_caret-h: 6px;\n\n            position: absolute; /* document coordinates in the top layer, see position.ts */\n            inset: auto;\n            box-sizing: border-box;\n            inline-size: max-content;\n            max-inline-size: 368px;\n            margin: 0;\n            padding: 0;\n            /* the menu settings (shared/listbox.ts): a design rounds and outlines every floating surface alike */\n            border: var(--ui-menu-border, none);\n            border-radius: var(--ui-menu-radius, var(--ui-radius-xs));\n            background-color: var(--ui-overlay-background, var(--ui-surface-1)); /* a design can raise floating surfaces (--ui-overlay-background) */\n            color: var(--ui-ink);\n            font: var(--ui-font-body-sm);\n            letter-spacing: var(--ui-tracking-body);\n            overflow: visible;\n        }\n\n        :host([drop-shadow]:not([drop-shadow='false'])) .bubble {\n            filter: drop-shadow(0 2px 2px rgb(0 0 0 / 0.2));\n        }\n\n        :host([high-contrast]) .bubble {\n            background-color: var(--ui-inverse-surface-1);\n            color: var(--ui-inverse-ink);\n        }\n\n        :host(:not([caret])) .caret,\n        :host([caret='false']) .caret,\n        :host([tab-tip]) .caret {\n            display: none;\n        }\n\n        :host([tab-tip]) .bubble {\n            border-radius: 0;\n        }\n\n        /* no fade: Carbon's popover shows and hides at once (its CSS has no transition or animation) */\n\n        @media (forced-colors: active) {\n            .bubble {\n                border: 1px solid CanvasText;\n            }\n        }\n    `];\n\n    @property({ type: Boolean, reflect: true }) open = false;\n\n    @property({ reflect: true }) placement: Placement = 'bottom';\n\n    /** On by default; `caret=\"false\"` hides it. */\n    @property({ reflect: true, converter: defaultTrue }) caret = true;\n\n    /** On by default; `drop-shadow=\"false\"` removes it. */\n    @property({ reflect: true, attribute: 'drop-shadow', converter: defaultTrue }) dropShadow = true;\n\n    @property({ type: Boolean, reflect: true, attribute: 'high-contrast' }) highContrast = false;\n\n    /** Carbon `isTabTip`: square box flush against the trigger (toolbar settings panels). */\n    @property({ type: Boolean, reflect: true, attribute: 'tab-tip' }) tabTip = false;\n\n    /** Close on Escape and on clicks outside the trigger and the box. */\n    @property({ type: Boolean, attribute: 'auto-close' }) autoClose = false;\n\n    /** Accessible name of the box (`role=group`). */\n    @property() label = '';\n\n    /**\n     * Beyond Carbon (its Popover has no hover mode; the tooltip's timings): the popover opens and closes itself. A\n     * mouse resting on the trigger opens it after 100ms, and leaving the trigger and the box closes it after 300ms\n     * (the pointer can move onto the box, WCAG 1.4.13); keyboard focus on the trigger opens it at once, and focus\n     * leaving the trigger and the box closes it; a tap (touch, pen) on the trigger toggles it; Escape and a press\n     * outside close it. While focus is in the box, or on the trigger by keyboard, it stays open.\n     */\n    @property({ type: Boolean, attribute: 'open-on-hover' }) openOnHover = false;\n\n    @query('.bubble') private readonly content!: HTMLElement;\n\n    @queryAssignedElements({ slot: 'trigger' }) private readonly triggers!: HTMLElement[];\n\n    private readonly contentId = uid('ui-popover');\n\n    override connectedCallback() {\n        super.connectedCallback();\n        if (this.hasUpdated) this.syncHoverMode();\n    }\n\n    override disconnectedCallback() {\n        super.disconnectedCallback();\n        this.stopTracking();\n        this.syncHoverMode();\n    }\n\n    show() {\n        this.open = true;\n    }\n\n    hide() {\n        this.open = false;\n    }\n\n    private get anchor(): Element | null {\n        return this.triggers[0] ?? this;\n    }\n\n    protected override updated(changed: Map<string, unknown>) {\n        if (changed.has('open')) {\n            const showing = this.content.matches(':popover-open');\n            if (this.open && !showing) {\n                this.content.showPopover();\n                this.reposition();\n                // on its anchor while open (scrolling ancestors in any shadow root, layout shifts); a finger scroll doesn't close it\n                this.untrack = trackAnchor(this.anchor ?? this, this.content, this.reposition);\n                this.addEventListener('keydown', this.onKeydown);\n                this.stopOutside = outsidePress(document, this.onPointerDown);\n            } else if (!this.open && showing) {\n                this.content.hidePopover();\n                this.stopTracking();\n            }\n            if (changed.get('open') !== undefined) {\n                this.dispatchEvent(new CustomEvent('ui-toggle', { detail: { open: this.open }, bubbles: true, composed: true }));\n            }\n        } else if (this.open && (changed.has('placement') || changed.has('caret') || changed.has('tabTip'))) {\n            this.reposition();\n        }\n        this.syncTrigger();\n        if (changed.has('open') || changed.has('openOnHover')) this.syncHoverMode();\n    }\n\n    /**\n     * aria-expanded on the trigger (`expanded` on a `<ui-button>`, whose own button carries it). No\n     * aria-controls: the box is in this shadow root, which an id in the trigger's tree can't point into.\n     */\n    private syncTrigger() {\n        const trigger = this.triggers[0] as (HTMLElement & { expanded?: boolean }) | undefined;\n        if (!trigger) return;\n        if ('expanded' in trigger) trigger.expanded = this.open;\n        else trigger.setAttribute('aria-expanded', this.open ? 'true' : 'false');\n    }\n\n    private untrack?: () => void;\n    private stopOutside?: () => void;\n\n    private stopTracking() {\n        this.untrack?.();\n        this.stopOutside?.();\n        this.untrack = this.stopOutside = undefined;\n        this.removeEventListener('keydown', this.onKeydown);\n    }\n\n    private readonly reposition = () => {\n        const anchor = this.anchor;\n        if (!anchor) return;\n        // Carbon popover-offset: 10px with a caret, flush otherwise (tab tip and caret-less)\n        if (this.caret && !this.tabTip) placeWithCaret(anchor, this.content, this.placement, 10);\n        else placeFloating(anchor, this.content, this.placement, 0);\n    };\n\n    /** `auto-close` asks first (`ui-request-close`); `open-on-hover` alone closes. */\n    private dismiss(reason: PopoverCloseReason) {\n        if (this.autoClose) this.requestClose(reason);\n        else this.open = false;\n    }\n\n    private requestClose(reason: PopoverCloseReason) {\n        if (!this.autoClose) return;\n        const ok = this.dispatchEvent(new CustomEvent('ui-request-close', { detail: { reason }, bubbles: true, composed: true, cancelable: true }));\n        if (ok) this.open = false;\n    }\n\n    /**\n     * Escape from inside the popover (trigger or content) closes it and returns focus to the trigger.\n     * Listening on the host, bubbling, lets a nested dropdown / date picker handle its own Escape first\n     * (it calls preventDefault) instead of every popover on the page swallowing the key.\n     */\n    private readonly onKeydown = (event: KeyboardEvent) => {\n        if (event.key !== 'Escape' || event.defaultPrevented || !this.open || !(this.autoClose || this.openOnHover)) return;\n        event.preventDefault();\n        const focused = deepActiveElement();\n        // across shadow roots: focus may sit inside a control in the content (a checkbox's own input)\n        let hadFocus = false;\n        for (let node: Node | null = focused; node && !hadFocus; node = node.parentNode ?? (node as ShadowRoot).host ?? null) hadFocus = node === this;\n        this.dismiss('escape');\n        // after the content has been hidden, which would otherwise drop focus to <body>\n        if (!this.open && hadFocus) this.updateComplete.then(() => this.refocusTrigger());\n    };\n\n    private readonly onPointerDown = (event: PointerEvent) => {\n        const path = event.composedPath();\n        if (path.includes(this) || path.includes(this.content)) return;\n        if (this.autoClose || this.openOnHover) this.dismiss('outside');\n    };\n\n    /** Focus back on the trigger after Escape: with `open-on-hover`, not a new keyboard focus that opens it again. */\n    private refocusTrigger() {\n        this.refocusing = true;\n        this.triggers[0]?.focus();\n        this.refocusing = false;\n    }\n\n    // open-on-hover (beyond Carbon): the listeners and timers here, the timings and pointer rules in core/hover-open\n\n    /** The trigger the hover listeners are on. */\n    private hoverTrigger?: HTMLElement;\n    private hoverTimer?: ReturnType<typeof setTimeout>;\n    private blurTimer?: ReturnType<typeof setTimeout>;\n    /** The mouse is on the trigger or the box. */\n    private hovered = false;\n    /** The pointer type of the last press on the trigger: its click toggles when it was a tap. */\n    private pressType = '';\n    private refocusing = false;\n    private pageEscape = false;\n\n    /** Hover listeners on the current trigger (none when the option is off or the element is gone); Escape on the page while open. */\n    private syncHoverMode() {\n        const on = this.openOnHover && this.isConnected;\n        const trigger = on ? this.triggers[0] : undefined;\n        if (trigger !== this.hoverTrigger) {\n            this.hoverTrigger?.removeEventListener('pointerenter', this.onTriggerEnter);\n            this.hoverTrigger?.removeEventListener('pointerleave', this.onHoverLeave);\n            this.hoverTrigger?.removeEventListener('focusin', this.onTriggerFocus);\n            this.hoverTrigger?.removeEventListener('focusout', this.onHoverBlur);\n            this.hoverTrigger?.removeEventListener('pointerdown', this.onTriggerPress);\n            this.hoverTrigger?.removeEventListener('click', this.onTriggerClick);\n            trigger?.addEventListener('pointerenter', this.onTriggerEnter);\n            trigger?.addEventListener('pointerleave', this.onHoverLeave);\n            trigger?.addEventListener('focusin', this.onTriggerFocus);\n            trigger?.addEventListener('focusout', this.onHoverBlur);\n            trigger?.addEventListener('pointerdown', this.onTriggerPress);\n            trigger?.addEventListener('click', this.onTriggerClick);\n            this.hoverTrigger = trigger;\n        }\n        if (!on) {\n            clearTimeout(this.hoverTimer);\n            clearTimeout(this.blurTimer);\n            this.hovered = false;\n        }\n        const listen = on && this.open;\n        if (listen === this.pageEscape) return;\n        if (listen) document.addEventListener('keydown', this.onPageEscape, true);\n        else document.removeEventListener('keydown', this.onPageEscape, true);\n        this.pageEscape = listen;\n    }\n\n    private readonly onTriggerSlotChange = () => {\n        this.syncTrigger();\n        this.syncHoverMode();\n    };\n\n    private hoverLater(open: boolean, ms: number) {\n        clearTimeout(this.hoverTimer);\n        this.hoverTimer = setTimeout(() => {\n            if (open) this.open = true;\n            else this.closeUnlessHeld();\n        }, ms);\n    }\n\n    /** Closes unless the mouse is on the trigger or the box, or focus holds it. */\n    private closeUnlessHeld() {\n        if (!this.hovered && !this.focusHolds()) this.open = false;\n    }\n\n    /** Focus in the box holds it open, and on the trigger by keyboard (a click or a tap there doesn't). */\n    private focusHolds() {\n        const focused = deepActiveElement();\n        if (!focused || !within(this, focused)) return false;\n        const trigger = this.triggers[0];\n        return !(trigger && within(trigger, focused)) || focused.matches(':focus-visible');\n    }\n\n    private readonly onTriggerEnter = (event: PointerEvent) => {\n        if (!hovers(event.pointerType)) return;\n        this.hovered = true;\n        this.hoverLater(true, HOVER_OPEN_DELAY);\n    };\n\n    private readonly onContentEnter = (event: PointerEvent) => {\n        if (!this.openOnHover || !hovers(event.pointerType)) return;\n        this.hovered = true;\n        clearTimeout(this.hoverTimer);\n    };\n\n    private readonly onHoverLeave = (event: PointerEvent) => {\n        if (!this.openOnHover || !hovers(event.pointerType)) return;\n        this.hovered = false;\n        this.hoverLater(false, HOVER_CLOSE_DELAY);\n    };\n\n    /** Keyboard focus only, as the tooltip: a click or a tap has its own rule. */\n    private readonly onTriggerFocus = (event: FocusEvent) => {\n        if (this.refocusing || !(event.composedPath()[0] as Element).matches(':focus-visible')) return;\n        clearTimeout(this.hoverTimer);\n        this.open = true;\n    };\n\n    /** Focus left the trigger or the box: a tick later it has landed (between shadow parts relatedTarget can be null). */\n    private readonly onHoverBlur = () => {\n        if (!this.openOnHover) return;\n        clearTimeout(this.blurTimer);\n        this.blurTimer = setTimeout(() => this.closeUnlessHeld(), 0);\n    };\n\n    private readonly onTriggerPress = (event: PointerEvent) => {\n        this.pressType = event.pointerType;\n    };\n\n    private readonly onTriggerClick = () => {\n        const tapped = taps(this.pressType);\n        this.pressType = '';\n        if (tapped) this.open = !this.open;\n    };\n\n    /** Escape from elsewhere on the page (the mouse showed it, focus is not inside): closes this box only, as the tooltip. */\n    private readonly onPageEscape = (event: KeyboardEvent) => {\n        if (event.key !== 'Escape' || !this.open || event.composedPath().includes(this)) return;\n        event.preventDefault();\n        event.stopPropagation();\n        this.dismiss('escape');\n    };\n\n    override render() {\n        return html`\n            <slot name=\"trigger\" @slotchange=${this.onTriggerSlotChange}></slot>\n            <div\n                class=\"bubble\"\n                part=\"content\"\n                id=${this.contentId}\n                popover=\"manual\"\n                role=\"group\"\n                aria-label=${this.label || nothing}\n                @pointerenter=${this.onContentEnter}\n                @pointerleave=${this.onHoverLeave}\n                @focusout=${this.onHoverBlur}\n            >\n                <slot></slot>\n                <span class=\"caret\" part=\"caret\" aria-hidden=\"true\"></span>\n            </div>\n        `;\n    }\n}\n\nexport type PopoverCloseReason = 'escape' | 'outside';\n\nexport interface UiPopoverEventMap extends HTMLElementEventMap {\n    'ui-toggle': CustomEvent<OpenDetail>;\n    'ui-request-close': CustomEvent<CloseDetail<PopoverCloseReason>>;\n}\n\n/** Typed listeners for UiPopover's events (declaration merging with the class). */\nexport interface UiPopover {\n    addEventListener<K extends keyof UiPopoverEventMap>(type: K, listener: (this: UiPopover, event: UiPopoverEventMap[K]) => unknown, options?: boolean | AddEventListenerOptions): void;\n    addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n    removeEventListener<K extends keyof UiPopoverEventMap>(type: K, listener: (this: UiPopover, event: UiPopoverEventMap[K]) => unknown, options?: boolean | EventListenerOptions): void;\n    removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare global {\n    interface HTMLElementTagNameMap {\n        'ui-popover': UiPopover;\n    }\n}\n"
    }
  ]
}
