import { cloneElement, isValidElement, useCallback, type ComponentProps, type ReactNode, type Ref, } from "react"; import { cn } from "@/components/lib/utils.js"; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, } from "@/components/ui/tooltip.js"; import { isAppleKeyboardPlatform } from "@/lib/keyboardShortcuts.js"; interface ControlHintTooltipProps { children: ReactNode; title: ReactNode; description?: string; shortcut?: string; standalone?: boolean; open?: boolean; onOpenChange?: (open: boolean) => void; side?: ComponentProps["side"]; align?: ComponentProps["align"]; sideOffset?: ComponentProps["sideOffset"]; className?: string; triggerClassName?: string; triggerRef?: Ref; } type TriggerChildProps = { className?: string; ref?: Ref; }; const shortcutKbdBaseClassName = "rounded-md h-4 inline-flex items-center bg-tooltip-tag px-1.5 text-ui-xs font-medium text-tooltip-tag-foreground"; function setRef(ref: Ref | undefined, value: T | null) { if (!ref) { return; } if (typeof ref === "function") { ref(value); return; } ref.current = value; } export function ControlHintTooltip({ children, title, description, shortcut, standalone = false, open, onOpenChange, side = "top", align = "center", sideOffset = 2, className, triggerClassName, triggerRef, }: ControlHintTooltipProps) { const useAppleShortcutFont = isAppleKeyboardPlatform(); const shortcutFontClassName = useAppleShortcutFont ? "tracking-normal" : "font-mono"; const shortcutFontStyle = useAppleShortcutFont ? { fontFamily: '-apple-system, BlinkMacSystemFont, "SF Pro Text", "SF Pro Display", "Helvetica Neue", sans-serif', } : undefined; const isTriggerElement = isValidElement(children); const childRef = isTriggerElement ? children.props.ref : undefined; // Radix Tooltip/Dropdown/Popper 的 asChild trigger 会在 ref 变化时同步 setState。 // 这里必须稳定 callback ref 身份,否则每次 render 都会触发 ref detach/attach 并形成更新循环。 const composedTriggerRef = useCallback( (value: HTMLElement | null) => { setRef(childRef, value); setRef(triggerRef, value); }, [childRef, triggerRef], ); const trigger = isTriggerElement ? ( cloneElement(children, { // 以前额外包一层 span,Radix Tooltip/Select/Popover 多层 asChild 组合时, // 事件和 ref 会落到不同 DOM 上,触发 SlotClone 渲染栈错误。这里直接合到真实触发器。 className: cn("shrink-0", children.props.className, triggerClassName), ref: composedTriggerRef, }) ) : ( } className={cn("inline-flex shrink-0", triggerClassName)} > {children} ); // 大会话会为每条消息动作渲染大量 ControlHintTooltip,逐个创建 Provider // 会把 Radix 上下文树放大到消息数量级;共享 Provider 统一放在 Root。 const tooltip = ( {trigger} {description ? (
{title} {shortcut ? ( {shortcut} ) : null}
) : ( // 无描述的提示过去同时受 max-w-xs 和 nowrap 约束,长中英文文案会越界裁剪。 // 短提示继续按内容宽度展示,超过视口安全宽度时允许自然换行;显式换行用于结构化提示。 {title} )} {description ? ( {description} ) : null} {!description && shortcut ? ( {shortcut} ) : null}
); // 少数组件需要支持脱离 Root 的 SSR/单测渲染;由封装按需补 Provider, // 避免业务层重新组合 Tooltip primitives,同时不让列表中的常规提示重复创建上下文。 return standalone ? {tooltip} : tooltip; }