{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "tooltip",
  "type": "registry:ui",
  "title": "<ui-tooltip>",
  "description": "Carbon-style tooltip: short, plain-text help for the wrapped control. 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-popup",
    "@kanok-ui/shared-align",
    "@kanok-ui/shared-element",
    "@kanok-ui/shared-field",
    "@kanok-ui/shared-position",
    "@kanok-ui/tokens"
  ],
  "files": [
    {
      "path": "src/primitives/tooltip/tooltip.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/tooltip/tooltip.ts",
      "content": "import { html, css, type ReactiveElement } from 'lit';\nimport { customElement, property, query, queryAssignedElements } from 'lit/decorators.js';\nimport { uid } from '../shared/field.ts';\nimport { caretStyles, placeWithCaret, type Placement } from '../shared/position.ts';\nimport { WithAlign } from '../shared/align.ts';\nimport { UiElement } from '../shared/element.ts';\nimport { trackAnchor } from '../../core/popup.ts';\n\nexport type TooltipPlacement = Placement;\n\nconst SHOW_DELAY = 100;\nconst HIDE_DELAY = 300; // Carbon leaveDelayMs\n\n/** Elements (like ui-button) that render their own accessible name/description. */\ninterface DescribableElement extends HTMLElement {\n    label?: string;\n    description?: string;\n}\n\n/**\n * A custom-element trigger without its own `label` / `description` property focuses something in its\n * shadow root; ARIA on the host would not reach it, so the element that takes focus is wired instead.\n */\nasync function wireTarget(trigger: DescribableElement, key: 'label' | 'description') {\n    let target = trigger;\n    while (!(key in target) && target.shadowRoot) {\n        await (target as Partial<ReactiveElement>).updateComplete;\n        const inner = innerFocusable(target.shadowRoot);\n        if (!inner) break;\n        target = inner;\n    }\n    return target;\n}\n\n/** The first element in a shadow root that takes focus: a native control or a host that delegates focus. */\nfunction innerFocusable(root: ShadowRoot): HTMLElement | null {\n    for (const el of root.querySelectorAll<HTMLElement>('*')) {\n        if (el.matches('button, a[href], input, select, textarea, [tabindex]') || el.shadowRoot?.delegatesFocus) return el;\n    }\n    return null;\n}\n\n/**\n * Carbon-style tooltip: short, plain-text help for the wrapped control.\n *\n * - Opens on hover (after a short delay) and on keyboard focus; hides on blur.\n * - WCAG 1.4.13: the pointer can move onto the tooltip, Esc dismisses it.\n * - Hides when the trigger is activated (click / Enter / Space, Carbon `closeOnActivation`), so it doesn't cover the result.\n * - `placement`: top | bottom | left | right, optionally `-start` / `-end` for triggers near an edge.\n * - Rendered in the top layer (Popover API), so overflow:hidden parents can't clip it.\n * - The text becomes the trigger's accessible description, or with `as-label`\n *   its accessible name (for icon-only buttons). `small` gives the icon tooltip's look\n *   while the text still describes (a trigger named by its own content).\n *\n * Never put interactive content in a tooltip — use a modal or toggletip instead.\n *\n * @slot - The trigger (one focusable element, e.g. `<ui-button>`)\n * @csspart bubble - The tooltip bubble\n * @csspart caret - The arrow pointing at the trigger\n * @attr align - Carbon's name for `placement` (same values)\n * @cssprop --ui-tooltip-radius - Corner radius of the bubble (default `--ui-radius-xs`)\n */\n@customElement('ui-tooltip')\nexport class UiTooltip extends WithAlign(UiElement) {\n    static override readonly styles = [caretStyles, css`\n        :host {\n            display: inline-block;\n        }\n\n        /* Carbon tooltip: high-contrast popover, 16px padding, body-01, 12×6 caret, 288px max */\n        .bubble {\n            --_caret-w: 12px;\n            --_caret-h: 6px;\n\n            position: absolute; /* document coordinates in the top layer: scrolls with the page, see position.ts */\n            inset: auto;\n            box-sizing: border-box;\n            margin: 0;\n            /* its natural width up to 288px wherever it sits: an absolute box near the viewport edge would shrink to the room left */\n            width: max-content;\n            max-width: 288px;\n            padding: var(--ui-space-md);\n            border: none;\n            border-radius: var(--ui-tooltip-radius, var(--ui-radius-xs));\n            background-color: var(--ui-inverse-surface-1);\n            color: var(--ui-inverse-ink);\n            font: var(--ui-font-body-sm);\n            line-height: 20px; /* body-01 */\n            letter-spacing: var(--ui-tracking-body);\n            overflow-wrap: break-word;\n            overflow: visible;\n        }\n\n        /* Carbon icon tooltip (the label of an icon-only button): 2px block padding, body-compact-01, 8×4 caret */\n        :host([as-label]) .bubble,\n        :host([small]) .bubble {\n            --_caret-w: 8px;\n            --_caret-h: 4px;\n\n            padding: 2px var(--ui-space-md);\n            line-height: 18px;\n        }\n\n        /* no fade: Carbon's tooltip 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() text = '';\n\n    @property({ reflect: true }) placement: TooltipPlacement = 'top';\n\n    /** Use the text as the trigger's accessible name instead of its description. */\n    @property({ type: Boolean, attribute: 'as-label' }) asLabel = false;\n\n    /** The icon tooltip's look (as `as-label`: 8px off, 2px / 16px padding, 8×4 caret) without naming the trigger. */\n    @property({ type: Boolean, reflect: true }) small = false;\n\n    /** Whether the bubble is showing. Hover / focus manage it; set it yourself together with `pinned`. */\n    @property({ type: Boolean, reflect: true }) open = false;\n\n    /**\n     * Keep the bubble open regardless of hover, focus, clicks and Escape — for a confirmation such\n     * as \"Copied!\" (Carbon copy button). While pinned, only `open` closes it.\n     */\n    @property({ type: Boolean }) pinned = false;\n\n    /**\n     * The element the bubble points at, listens to and names / describes, instead of the slotted\n     * trigger — for a focusable host that renders its tooltip in its own shadow root (an icon-only\n     * content switcher item).\n     */\n    @property({ attribute: false }) anchor: HTMLElement | null = null;\n\n    @query('.bubble') private readonly bubble!: HTMLElement;\n\n    @queryAssignedElements() private readonly assigned!: HTMLElement[];\n\n    private readonly bubbleId = uid('ui-tooltip');\n    private srText?: HTMLSpanElement;\n    private timer?: number;\n\n    /** Where hover, focus and activation are listened for: the anchor, else this host (around the trigger). */\n    private listening?: HTMLElement;\n\n    override connectedCallback() {\n        super.connectedCallback();\n        this.listen(this.anchor ?? this);\n    }\n\n    override disconnectedCallback() {\n        super.disconnectedCallback();\n        this.listen(undefined);\n        // even a pinned tooltip (copy feedback) must not leave page-level listeners behind\n        clearTimeout(this.timer);\n        document.removeEventListener('keydown', this.onKeydown, true);\n        this.untrack?.();\n        this.untrack = undefined;\n        this.open = false;\n    }\n\n    private listen(target: HTMLElement | undefined) {\n        const old = this.listening;\n        if (old === target) return;\n        old?.removeEventListener('pointerenter', this.onPointerEnter);\n        old?.removeEventListener('pointerleave', this.scheduleHide);\n        old?.removeEventListener('focusin', this.onFocusIn);\n        old?.removeEventListener('focusout', this.hide);\n        old?.removeEventListener('click', this.hide);\n        old?.removeEventListener('keydown', this.onActivate);\n        target?.addEventListener('pointerenter', this.onPointerEnter);\n        target?.addEventListener('pointerleave', this.scheduleHide);\n        target?.addEventListener('focusin', this.onFocusIn);\n        target?.addEventListener('focusout', this.hide);\n        target?.addEventListener('click', this.hide);\n        target?.addEventListener('keydown', this.onActivate);\n        this.listening = target;\n    }\n\n    private get trigger(): DescribableElement | undefined {\n        return this.anchor ?? this.assigned[0];\n    }\n\n    protected override updated(changed: Map<string, unknown>) {\n        if (changed.has('anchor') && this.isConnected) this.listen(this.anchor ?? this);\n        if (changed.has('text') || changed.has('asLabel') || changed.has('anchor')) void this.wireAccessibility();\n        if (changed.has('open')) this.toggleBubble();\n    }\n\n    /** Give the trigger its name/description in its own tree so the reference resolves. */\n    private async wireAccessibility() {\n        const trigger = this.trigger;\n        if (!trigger) return;\n        const key = this.asLabel ? 'label' : 'description';\n        const target = await wireTarget(trigger, key);\n        if (key in target) {\n            target[key] = this.text;\n            return;\n        }\n        if (this.asLabel) {\n            target.setAttribute('aria-label', this.text);\n            return;\n        }\n        if (this.anchor) {\n            // the anchor sits outside this tooltip's tree, so neither an id nor an element reference reaches a span here\n            target.setAttribute('aria-description', this.text);\n            return;\n        }\n        // A hidden span next to the trigger, in the light tree, carries the description.\n        this.srText ??= Object.assign(document.createElement('span'), { id: this.bubbleId, hidden: true });\n        this.srText.textContent = this.text;\n        if (!this.srText.isConnected) this.append(this.srText);\n        if (target !== trigger) {\n            // an id can't point out of a shadow root; an element reference to an ancestor tree can\n            if ('ariaDescribedByElements' in Element.prototype) {\n                const current = target.ariaDescribedByElements ?? [];\n                if (!current.includes(this.srText)) target.ariaDescribedByElements = [...current, this.srText];\n            } else target.setAttribute('aria-description', this.text);\n            return;\n        }\n        // add to the trigger's own descriptions rather than replacing them\n        const ids = new Set((trigger.getAttribute('aria-describedby') ?? '').split(/\\s+/).filter(Boolean));\n        ids.add(this.bubbleId);\n        trigger.setAttribute('aria-describedby', [...ids].join(' '));\n    }\n\n    private readonly onPointerEnter = () => {\n        clearTimeout(this.timer);\n        this.timer = globalThis.setTimeout(() => (this.open = true), SHOW_DELAY);\n    };\n\n    private readonly scheduleHide = () => {\n        if (this.pinned) return;\n        clearTimeout(this.timer);\n        this.timer = globalThis.setTimeout(() => (this.open = false), HIDE_DELAY);\n    };\n\n    private readonly onFocusIn = (event: FocusEvent) => {\n        // Only keyboard focus — a mouse click already had its hover tooltip.\n        const target = event.composedPath()[0] as Element;\n        if (target.matches(':focus-visible')) {\n            clearTimeout(this.timer);\n            this.open = true;\n        }\n    };\n\n    private readonly hide = () => {\n        if (this.pinned) return;\n        clearTimeout(this.timer);\n        this.open = false;\n    };\n\n    /** Enter / Space activate the trigger (a native button clicks too, a custom tab doesn't). */\n    private readonly onActivate = (event: KeyboardEvent) => {\n        if (event.key === 'Enter' || event.key === ' ') this.hide();\n    };\n\n    private readonly onKeydown = (event: KeyboardEvent) => {\n        if (event.key !== 'Escape' || !this.open) return;\n        // Dismiss the tooltip only; don't let the same Esc close a surrounding modal.\n        event.preventDefault();\n        event.stopPropagation();\n        this.hide();\n    };\n\n    private readonly reposition = () => this.position();\n\n    private untrack?: () => void;\n\n    private toggleBubble() {\n        const bubble = this.bubble;\n        if (this.open && this.text) {\n            if (!bubble.matches(':popover-open')) bubble.showPopover();\n            this.position();\n            document.addEventListener('keydown', this.onKeydown, true);\n            // on its trigger while open (scrolling ancestors in any shadow root, layout shifts)\n            const trigger = this.trigger;\n            if (trigger) this.untrack ??= trackAnchor(trigger, bubble, this.reposition);\n        } else {\n            if (bubble.matches(':popover-open')) bubble.hidePopover();\n            document.removeEventListener('keydown', this.onKeydown, true);\n            this.untrack?.();\n            this.untrack = undefined;\n        }\n    }\n\n    private position() {\n        const trigger = this.trigger;\n        // Carbon popover-offset: 12px for the text tooltip, 8px for the icon tooltip\n        if (trigger) placeWithCaret(trigger, this.bubble, this.placement, this.asLabel || this.small ? 8 : 12);\n    }\n\n    /** Focus the slotted trigger (delegatesFocus does not reach slotted light DOM). */\n    override focus(options?: FocusOptions) {\n        this.trigger?.focus(options);\n    }\n\n    override render() {\n        return html`\n            <slot @slotchange=${() => this.wireAccessibility()}></slot>\n            <div\n                class=\"bubble\"\n                part=\"bubble\"\n                role=\"tooltip\"\n                popover=\"manual\"\n                aria-hidden=\"true\"\n                @pointerenter=${() => clearTimeout(this.timer)}\n                @pointerleave=${this.scheduleHide}\n            >\n                ${this.text}\n                <span class=\"caret\" part=\"caret\" aria-hidden=\"true\"></span>\n            </div>\n        `;\n    }\n}\n\ndeclare global {\n    interface HTMLElementTagNameMap {\n        'ui-tooltip': UiTooltip;\n    }\n}\n"
    }
  ]
}
