{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "tooltip",
  "title": "Tooltip",
  "description": "A short label that appears beside its trigger on hover and keyboard focus, for an icon button's purpose or a control's shortcut.",
  "dependencies": [
    "@base-ui/react@^1.8.0"
  ],
  "registryDependencies": [
    "@ouro/lib-dev",
    "@ouro/lib-env",
    "@ouro/lib-floating",
    "@ouro/lib-last-input",
    "@ouro/lib-ouro-provider",
    "@ouro/lib-portal-container",
    "@ouro/lib-refs",
    "@ouro/lib-server-element",
    "@ouro/lib-use-dev-messages"
  ],
  "files": [
    {
      "path": "registry/ouro/components/ouro/tooltip/tooltip.tsx",
      "content": "\"use client\";\n\nimport { mergeProps } from \"@base-ui/react/merge-props\";\nimport { Tooltip as BaseTooltip } from \"@base-ui/react/tooltip\";\nimport { cloneElement, useCallback, useContext, useEffect, useLayoutEffect, useRef, useState, type JSX, type ReactElement, type ReactNode, type Ref } from \"react\";\nimport { devWarn } from \"@/registry/ouro/lib/ouro/dev\";\nimport {\n  floatingAlign,\n  floatingMotionClass,\n  floatingPlacementWarnings,\n  floatingPortalClass,\n  floatingSide,\n  type FloatingAlign,\n  type FloatingSide,\n} from \"@/registry/ouro/lib/ouro/floating\";\nimport { lastInput } from \"@/registry/ouro/lib/ouro/last-input\";\nimport { useMergedRef } from \"@/registry/ouro/lib/ouro/refs\";\nimport { useDevWarnings } from \"@/registry/ouro/lib/ouro/use-dev-messages\";\nimport { PortalScope, TooltipsGrouped, TooltipsHidden, usePortalContainer } from \"@/registry/ouro/lib/ouro/portal-container\";\nimport { serverElement } from \"@/registry/ouro/lib/ouro/server-element\";\n\nexport type { FloatingAlign as TooltipAlign, FloatingSide as TooltipSide } from \"@/registry/ouro/lib/ouro/floating\";\n\n/** Props for {@link Tooltip}. */\nexport interface TooltipProps {\n  /**\n   * A short label for the trigger, a few words: \"Add to cookbook\". It shows on hover and\n   * keyboard focus, never on touch, and screen readers don't read it, so it must never\n   * hold anything the user needs.\n   * @claim \"It shows on hover and keyboard\" registry/ouro/components/ouro/tooltip/tooltip.test.tsx verify:testExists(registry/ouro/components/ouro/tooltip/tooltip.test.tsx::Tooltip > shows on keyboard focus and hides on Escape)\n   * @claim \"It shows on hover and keyboard\" registry/ouro/components/ouro/tooltip/tooltip.test.tsx verify:testExists(registry/ouro/components/ouro/tooltip/tooltip.test.tsx::Tooltip > shows its content above the trigger on hover, and hides it when the pointer leaves)\n   * @claim \"It shows on hover and keyboard\" registry/ouro/components/ouro/tooltip/tooltip.test.tsx verify:testExists(registry/ouro/components/ouro/tooltip/tooltip.test.tsx::Tooltip > never opens after a touch on the trigger, even when the touch focuses it)\n   */\n  content: ReactNode;\n  /**\n   * The trigger: one element that can take focus, usually a Button. It needs a name of\n   * its own; give an icon-only button `aria-label`.\n   */\n  children: ReactElement;\n  /**\n   * The side of the trigger the tooltip sits on; it flips when there is no room. @default \"top\"\n   *\n   * @claim \"it flips when there is no room\" https://base-ui.com/react/components/tooltip verify:urlOk(https://base-ui.com/react/components/tooltip)\n   */\n  side?: FloatingSide | (string & { 'Use \"top\", \"bottom\", \"left\" or \"right\"': never }) | undefined;\n  /** How the tooltip lines up with the trigger along that side. @default \"center\" */\n  align?: FloatingAlign | (string & { 'Use \"start\", \"center\" or \"end\": left is \"start\", right is \"end\"': never }) | undefined;\n\n  /** Not a prop. The text is `content`: `<Tooltip content=\"Add to cookbook\">`. */\n  title?: { 'Use <Tooltip content=\"...\">': never };\n  /** Not a prop. Ouro UI sets the delay, and `OuroProvider` groups tooltips so neighbours open instantly. */\n  delayDuration?: { \"Ouro UI sets the delay; wrap the app in <OuroProvider> to group tooltips\": never };\n  /** Not a prop. Ouro UI sets the delay, and `OuroProvider` groups tooltips so neighbours open instantly. */\n  delay?: { \"Ouro UI sets the delay; wrap the app in <OuroProvider> to group tooltips\": never };\n  /** Not a prop. The child is the trigger: `<Tooltip content=\"…\"><Button>…</Button></Tooltip>`. */\n  asChild?: { 'The child is the trigger: <Tooltip content=\"...\"><Button>...</Button></Tooltip>': never };\n  /** Not a prop. Ouro UI splits placement into `side` and `align`: `<Tooltip side=\"bottom\" align=\"start\">`. */\n  placement?: { 'Use side=\"bottom\" align=\"start\"': never };\n}\n\n/** Content longer than this is more than a label. */\nconst LABEL_LENGTH = 80;\n\nconst popupClass =\n  floatingMotionClass +\n  \" box-border max-w-xs rounded-ouro-md bg-foreground px-2 py-1 text-xs leading-4 text-balance text-background [--ouro-floating-duration:var(--ouro-duration-fast)] data-instant:duration-0\";\n\n// Base UI's delay before a tooltip opens under a resting pointer, and how long after one closes a neighbour inside\n// OuroProvider still opens at once.\nconst OPEN_DELAY = 600;\nconst GROUP_TIMEOUT = 400;\n// Long enough to cross the gap from the trigger onto the tooltip, which keeps it open, as Base UI's tooltips allow.\nconst CLOSE_DELAY = 100;\n\n// The page's tooltips: how many show, and when the last one went, so a neighbour opens at once inside OuroProvider.\n// Stryker disable next-line ObjectLiteral: equivalent; read once at import, before mutants switch, and each test's tooltips leave the count where they found it.\nconst shown = { count: 0, closedAt: Number.NEGATIVE_INFINITY };\n\n/**\n * A link or control inside the content, which no one can reach: the tooltip closes when the pointer leaves the trigger for it.\n *\n * @claim \"A link or control inside the\" registry/ouro/components/ouro/tooltip/tooltip.test.tsx verify:testExists(registry/ouro/components/ouro/tooltip/tooltip.test.tsx::Tooltip dev messages > warns when the content holds a link or a control, once it shows)\n */\nconst INTERACTIVE = 'a[href], button, input, select, textarea, [tabindex]:not([tabindex=\"-1\"])';\n\n/** The dev message for content that holds essential information. Development only. */\nfunction essential(detail: string): readonly [string, string] {\n  return [\n    `${detail}; a tooltip never opens on touch, so phone users never see it`,\n    'move essential information out of the tooltip, into the page or a <Popover title=\"…\">',\n  ];\n}\n\n// Base UI's Menu and Popover triggers set aria-haspopup and aria-expanded while their popup is open. A disclosure (an\n// accordion's toggle) sets aria-expanded alone, and an expanded one holds nothing a tooltip would cover.\nfunction popupOpen(expanded: unknown, haspopup: unknown): boolean {\n  return (expanded === true || expanded === \"true\") && haspopup !== undefined && haspopup !== null && haspopup !== false && haspopup !== \"false\";\n}\n\n/**\n * A short label that appears beside its trigger on hover and keyboard focus, for an\n * icon button's purpose or a control's shortcut. It never opens on touch, and screen\n * readers don't read it, so it only repeats or adds to what the page already says.\n * Inside `OuroProvider`, tooltips share one delay: once one shows, its neighbours open\n * instantly. A press on the trigger closes it, and it stays closed while the trigger's menu or popover is open.\n *\n * Use `Popover` instead for anything the user needs or can act on (it opens on tap and\n * holds controls), `HoverCard` for a preview of a link, and plain text on the page for\n * essential information.\n *\n * It stacks above the page at `--ouro-layer`, a z-index of 50 by default (from\n * ouro-base.css), like Dialog and Sheet.\n *\n * @group Overlays\n * @see https://ui.ouroboros.bot/docs/tooltip\n *\n * On a button that opens a Popover, Dialog or Menu, put the Tooltip inside that\n * component's `trigger`, never around the component: the Tooltip passes the trigger\n * props it receives on to its child.\n *\n * @example\n * <Tooltip content=\"Add to cookbook\">\n *   <Button aria-label=\"Save\" variant=\"plain\"><BookmarkIcon /></Button>\n * </Tooltip>\n * <Popover\n *   title=\"Share recipe\"\n *   trigger={<Tooltip content=\"Share recipe\"><Button aria-label=\"Share\"><ShareIcon /></Button></Tooltip>}\n * >\n *   <TextField label=\"Link\" defaultValue={url} readOnly />\n * </Popover>\n * @claim \"It stacks above the page at\" registry/ouro/components/ouro/tooltip/tooltip.test.tsx verify:testExists(registry/ouro/components/ouro/tooltip/tooltip.test.tsx::Tooltip > portals at the --ouro-layer level, as its own stacking context)\n * @claim \"It stacks above the page at\" registry/ouro/theme/ouro-base.css verify:fileLine(registry/ouro/theme/ouro-base.css, /^\\s+--ouro-layer:\\s50;/)\n * @claim \"It never opens on touch, and\" registry/ouro/components/ouro/tooltip/tooltip.test.tsx verify:testExists(registry/ouro/components/ouro/tooltip/tooltip.test.tsx::Tooltip > never opens after a touch on the trigger, even when the touch focuses it)\n * @claim \"It never opens on touch, and\" registry/ouro/components/ouro/tooltip/tooltip.test.tsx verify:testExists(registry/ouro/components/ouro/tooltip/tooltip.test.tsx::Tooltip > opens on mouse hover after a touch elsewhere, as on a laptop with a touchscreen)\n * @claim \"A press on the trigger closes it\" registry/ouro/components/ouro/tooltip/tooltip.test.tsx verify:testExists(registry/ouro/components/ouro/tooltip/tooltip.test.tsx::Tooltip > closes on Enter when the press opens something and focus stays on the trigger)\n * @claim \"it stays closed while the trigger's menu or popover is open\" registry/ouro/components/ouro/tooltip/tooltip.test.tsx verify:testExists(registry/ouro/components/ouro/tooltip/tooltip.test.tsx::Tooltip > closes on a click, and stays closed while its trigger's menu is open)\n * @claim \"it stays closed while the trigger's menu or popover is open\" registry/ouro/components/ouro/tooltip/tooltip.test.tsx verify:testExists(registry/ouro/components/ouro/tooltip/tooltip.test.tsx::Tooltip > closes on a click, and stays closed while its trigger's popover is open)\n */\nexport function Tooltip(props: TooltipProps): JSX.Element {\n  const {\n    content,\n    children,\n    side: sideProp,\n    align: alignProp,\n    // Guard props (hint types), dropped here so they never reach the DOM.\n    title,\n    delayDuration,\n    delay,\n    asChild,\n    placement,\n    // Props and a ref from a parent trigger, such as Popover's `trigger`, go on to the child.\n    ref,\n    ...forwarded\n  } = props as TooltipProps & { ref?: Ref<HTMLButtonElement> };\n\n  const side = floatingSide(sideProp, \"top\");\n  const align = floatingAlign(alignProp);\n  const key = useRef({});\n  const triggerRef = useRef<HTMLButtonElement>(null);\n  // The child's own ref, a parent trigger's (Popover's), and the tooltip's own.\n  const child = serverElement(children);\n  const mergedRef = useMergedRef((child.props as { ref?: Ref<HTMLButtonElement> }).ref, useMergedRef(ref, triggerRef));\n\n  useDevWarnings(\n    \"Tooltip\",\n    process.env.NODE_ENV !== \"production\"\n      ? () => {\n          const timing = (name: string) =>\n            [\n              `${name} is not a prop; Ouro UI sets the delay, and OuroProvider groups tooltips`,\n              \"<OuroProvider><App /></OuroProvider>\",\n            ] as const;\n          return [\n            ...floatingPlacementWarnings(\"<Tooltip\", sideProp, \"top\", alignProp, placement),\n            title !== undefined && [\"title is not a prop; the text is content\", '<Tooltip content=\"…\">'],\n            delayDuration !== undefined && timing(\"delayDuration\"),\n            delay !== undefined && timing(\"delay\"),\n            asChild !== undefined && [\n              \"asChild is not a prop; the child is the trigger\",\n              '<Tooltip content=\"…\"><Button>…</Button></Tooltip>',\n            ],\n            typeof content === \"string\" &&\n              content.length > LABEL_LENGTH &&\n              essential(`content is ${content.length} characters, more than a label`),\n          ];\n        }\n      : /* istanbul ignore next @preserve -- production only */ undefined,\n  );\n\n  // A trigger with no name of its own is unnamed for screen readers: the tooltip is not one.\n  useEffect(() => {\n    /* istanbul ignore else @preserve -- the else path exists only in production bundles */\n    if (process.env.NODE_ENV !== \"production\") {\n      const element = triggerRef.current;\n      if (!element) {\n        devWarn(\n          \"Tooltip\",\n          \"the trigger never received the tooltip's ref, so the tooltip cannot open; the child must pass its props and ref to an element, and Popover and Dialog do not\",\n          'put the Tooltip inside the trigger: trigger={<Tooltip content=\"…\"><Button …/></Tooltip>}',\n          key.current,\n        );\n        return;\n      }\n      const named =\n        element.textContent!.trim() !== \"\" ||\n        element.hasAttribute(\"aria-label\") ||\n        element.hasAttribute(\"aria-labelledby\");\n      if (!named) {\n        devWarn(\n          \"Tooltip\",\n          \"the trigger has no accessible name, and a tooltip is not one\",\n          `<Button aria-label=\"${typeof content === \"string\" ? content : \"…\"}\">`,\n          key.current,\n        );\n      }\n    }\n  });\n\n  // Links and controls in the content show up only once it renders.\n  const checkContent = useCallback((element: HTMLElement | null) => {\n    /* istanbul ignore else @preserve -- the else path exists only in production bundles */\n    if (process.env.NODE_ENV !== \"production\") {\n      if (element?.querySelector(INTERACTIVE)) {\n        const [problem, fix] = essential(\"content holds a link or control, which no one can reach\");\n        devWarn(\"Tooltip\", problem, fix, key.current);\n      }\n    }\n  }, []);\n\n  // The tooltip mounts only once someone may want it: on the trigger's first hover or keyboard focus. Until then the\n  // trigger is the child itself with a few handlers, so a row of many (a message's reactions) mounts no tooltips. The\n  // child is never wrapped or drawn again as it arms, so focus and the pointer stay on it.\n  const grouped = useContext(TooltipsGrouped);\n  const [armed, setArmed] = useState(false);\n  const [open, setOpen] = useState<false | \"delay\" | \"focus\" | \"now\">(false);\n  const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);\n  const show = (how: \"delay\" | \"focus\" | \"now\") => {\n    // Never after a touch: a tap that focuses the trigger would otherwise show it, and a phone has no way to hover it away.\n    // Nor while the trigger's own menu or popover is open: the person is using that, so the tooltip waits until it closes.\n    const element = triggerRef.current;\n    if (lastInput() !== \"touch\" && !popupOpen(element?.getAttribute(\"aria-expanded\"), element?.getAttribute(\"aria-haspopup\"))) setOpen(how);\n  };\n  const after = (delay: number, act: () => void) => {\n    clearTimeout(timer.current);\n    timer.current = setTimeout(act, delay);\n  };\n  const close = () => {\n    clearTimeout(timer.current);\n    setOpen(false);\n  };\n  useEffect(() => {\n    if (!open) return;\n    shown.count += 1;\n    return () => {\n      shown.count -= 1;\n      shown.closedAt = performance.now();\n    };\n  }, [open]);\n  // A pending open must not fire after its trigger has unmounted.\n  // Stryker disable next-line ArrayDeclaration: equivalent; any constant dependency list runs this cleanup once, at unmount.\n  useEffect(() => () => clearTimeout(timer.current), []);\n\n  // Closed as the container it is in hides, such as a toolbar that fades out. A layout effect, so\n  // the close is asked in the same commit that hides the container, not a frame later.\n  const hidden = useContext(TooltipsHidden);\n  useLayoutEffect(() => {\n    // Stryker disable next-line ConditionalExpression: equivalent; the effect also runs at mount and as the container shows again, when the tooltip is already closed.\n    // eslint-disable-next-line react-hooks/set-state-in-effect\n    if (hidden) close();\n  }, [hidden]);\n\n  // A popup the trigger opens while the tooltip shows (not by a press, which already closed it) closes the tooltip. The\n  // trigger's props come from a parent's `trigger` (Popover's or Menu's) or the child itself, the child's winning.\n  const childExpanded = (child.props as Record<string, unknown>)[\"aria-expanded\"] ?? (forwarded as Record<string, unknown>)[\"aria-expanded\"];\n  const childHaspopup = (child.props as Record<string, unknown>)[\"aria-haspopup\"] ?? (forwarded as Record<string, unknown>)[\"aria-haspopup\"];\n  const expanded = popupOpen(childExpanded, childHaspopup);\n  // Closing as the popup shuts finds nothing to close: the guard keeps a tooltip shut while its trigger's popup is open.\n  useLayoutEffect(() => {\n    // eslint-disable-next-line react-hooks/set-state-in-effect\n    close();\n  }, [expanded]);\n\n  const portal = usePortalContainer(\"Tooltip\");\n  const trigger = cloneElement(\n    child,\n    // The child takes the merged ref and handlers, none of which run during render. A parent trigger's\n    // props come first, so the child's own (a toolbar control's tabIndex) win, as Base UI's render does.\n    // eslint-disable-next-line react-hooks/refs\n    mergeProps(forwarded as object, child.props as object, {\n      ref: mergedRef,\n      // Only while open: a closed tooltip leaves a parent's data-popup-open (its menu's, say) as it is.\n      // Stryker disable next-line StringLiteral: read by the attribute alone, as Base UI's open trigger is.\n      ...(open ? { \"data-popup-open\": \"\" } : {}),\n      // Marks the trigger as Base UI's own tooltip trigger did, so a nested trigger and tests still find it.\n      // Stryker disable next-line StringLiteral: read by the attribute alone.\n      \"data-base-ui-tooltip-trigger\": \"\",\n      onPointerEnter: (event: { pointerType: string; timeStamp: number }) => {\n        if (event.pointerType === \"touch\") return;\n        setArmed(true);\n        // Inside OuroProvider a neighbour opens at once while one shows, or a moment after it went.\n        if (grouped && (shown.count > 0 || event.timeStamp - shown.closedAt < GROUP_TIMEOUT)) show(\"delay\");\n        else after(OPEN_DELAY, () => show(\"now\"));\n      },\n      onPointerLeave: () => after(CLOSE_DELAY, () => setOpen(false)),\n      onFocus: (event: { currentTarget: Element }) => {\n        if (!event.currentTarget.matches(\":focus-visible\")) return;\n        setArmed(true);\n        clearTimeout(timer.current);\n        show(\"focus\");\n      },\n      onBlur: close,\n      // Escape on the trigger closes an open tooltip and goes no further, so a popover or rail around it stays: the\n      // tooltip takes the first Escape, as Base UI's does.\n      onKeyDown: (event: { key: string; preventDefault: () => void; stopPropagation: () => void }) => {\n        if (event.key !== \"Escape\" || !open) return;\n        close();\n        event.preventDefault();\n        event.stopPropagation();\n      },\n      // A press closes it, and keeps a pending one from opening. A click closes it too: Enter or Space on a trigger that\n      // opens something without moving focus off it would otherwise leave the tooltip over what it opened.\n      onPointerDown: close,\n      onClick: close,\n    }) as Record<string, unknown>,\n  );\n  if (!armed) return trigger;\n  return (\n    <>\n      {trigger}\n      <BaseTooltip.Root\n        open={open !== false}\n        // Base UI asks only to close a tooltip it holds no trigger for: on Escape or a press outside it.\n        onOpenChange={close}\n      >\n        <BaseTooltip.Portal {...portal} data-ouro=\"tooltip-portal\" className={floatingPortalClass}>\n          <PortalScope>\n            <BaseTooltip.Positioner anchor={triggerRef} side={side} align={align} sideOffset={6} collisionPadding={8} data-ouro=\"tooltip-positioner\">\n              <BaseTooltip.Popup\n                ref={checkContent}\n                data-ouro=\"tooltip\"\n                // Opened by keyboard focus, or at once beside one already shown: no entrance, as Base UI does.\n                data-instant={open === \"focus\" || open === \"delay\" ? open : undefined}\n                // The pointer may cross from the trigger onto the tooltip and stay.\n                onPointerEnter={() => clearTimeout(timer.current)}\n                onPointerLeave={() => after(CLOSE_DELAY, () => setOpen(false))}\n                className={popupClass}\n              >\n                {content}\n              </BaseTooltip.Popup>\n            </BaseTooltip.Positioner>\n          </PortalScope>\n        </BaseTooltip.Portal>\n      </BaseTooltip.Root>\n    </>\n  );\n}\n",
      "type": "registry:ui",
      "target": "@components/ouro/tooltip/tooltip.tsx"
    }
  ],
  "docs": "A short label that appears beside its trigger on hover and keyboard focus, for an icon button's purpose or a control's shortcut. Import: import { Tooltip } from \"@/components/ouro/tooltip/tooltip\", with @/components replaced by your components alias (aliases.components in components.json, such as ~/components). Also installed: the helpers it imports in lib/ouro. Needs ouro-base in your stylesheet: add that item once per app, from the same place as this one, if you have not. Docs: https://ui.ouroboros.bot/docs/tooltip.md Ouro UI v1.3.257.",
  "type": "registry:ui"
}