Tooltip.tsx 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. // Hover/focus label bubble (figma tooltip pill: dark plate, white text).
  2. // TODO: interaction is a placeholder (horizontal overflow clamps and a
  3. // vertical collision flips the bubble to the other side, but there is no
  4. // arrow) — visuals and behavior get a proper pass later.
  5. // The anchor is the child element itself (cloneElement, no wrapper node), so
  6. // attaching a tooltip never changes the anchor's layout context. The bubble is
  7. // position:fixed and coordinates come from the anchor's rect at show time, so
  8. // it escapes ancestor overflow clipping (the sidebar rail clips its column)
  9. // without a portal.
  10. import { cloneElement, useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'
  11. import type { FocusEventHandler, MouseEventHandler, MutableRefObject, ReactElement, Ref } from 'react'
  12. import css from './Tooltip.module.css'
  13. /** Bubble placement relative to the anchor. */
  14. export type TooltipSide = 'right' | 'bottom' | 'top'
  15. /** Props Tooltip injects into its anchor child; the child's own handlers are chained ahead of the tooltip's. */
  16. interface AnchorProps {
  17. ref?: Ref<HTMLElement> | undefined
  18. onMouseEnter?: MouseEventHandler | undefined
  19. onMouseLeave?: MouseEventHandler | undefined
  20. onFocus?: FocusEventHandler | undefined
  21. onBlur?: FocusEventHandler | undefined
  22. }
  23. type TooltipLabel = string | (() => string)
  24. /**
  25. * Attach a hover/focus tooltip to an anchor element.
  26. * @param props.label - bubble text, or a resolver evaluated only while the bubble is visible.
  27. * @param props.side - placement relative to the anchor (default 'right').
  28. * @param props.delayMs - hover delay in milliseconds; keyboard focus remains immediate.
  29. * @param props.disabled - suppress the bubble while true; the anchor renders identically so
  30. * toggling never remounts it (which would cut its CSS transitions).
  31. * @param props.maxWidth - bubble width cap in pixels, for labels long enough that the default
  32. * half-viewport cap would render a slab wider than the surface the anchor sits on.
  33. * @param props.children - a single anchor element; its own ref (callback or object) is forwarded alongside the tooltip's.
  34. * @returns the cloned anchor plus a fixed-position bubble while hovered/focused.
  35. */
  36. export function Tooltip({ label, side = 'right', delayMs = 0, disabled = false, maxWidth, children }: { label: TooltipLabel; side?: TooltipSide; delayMs?: number; disabled?: boolean; maxWidth?: number; children: ReactElement<AnchorProps> }) {
  37. const anchor = useRef<HTMLElement | null>(null)
  38. // React 18 keeps the element's ref outside props; forward it so wrapping an
  39. // anchor in Tooltip never silently severs the owner's ref.
  40. const childRef = (children as ReactElement<AnchorProps> & { ref?: Ref<HTMLElement> }).ref
  41. const mergedRef = useCallback((el: HTMLElement | null) => {
  42. anchor.current = el
  43. if (typeof childRef === 'function') childRef(el)
  44. else if (childRef != null) (childRef as MutableRefObject<HTMLElement | null>).current = el
  45. }, [childRef])
  46. // The anchor's edges rather than final coordinates: a vertical flip has to
  47. // re-derive the bubble's own top from the opposite edge.
  48. const [pos, setPos] = useState<{ x: number; top: number; bottom: number } | null>(null)
  49. // Where the bubble actually sits, which is the requested side until the
  50. // viewport refuses it.
  51. const [placement, setPlacement] = useState<TooltipSide>(side)
  52. const bubble = useRef<HTMLSpanElement | null>(null)
  53. const resolvedLabel = pos === null
  54. ? null
  55. : typeof label === 'function' ? label() : label
  56. const y = pos === null
  57. ? 0
  58. : placement === 'right'
  59. ? pos.top + (pos.bottom - pos.top) / 2
  60. : placement === 'top' ? pos.top - 8 : pos.bottom + 8
  61. const EDGE_MARGIN = 12
  62. // Viewport fit: fixed positioning knows nothing about edges, so a centered
  63. // bubble near the right edge would clip and a long label under an anchor low
  64. // on the page would run off the bottom. Horizontally the bubble slides back
  65. // inside; vertically it flips to the opposite side, which is the only move
  66. // that does not cover the anchor being read. Each measurement resets the base
  67. // position first, so a shorter label or a larger viewport releases a previous
  68. // adjustment without another render.
  69. useLayoutEffect(() => {
  70. if (pos === null) return
  71. const fit = () => {
  72. const el = bubble.current
  73. /* v8 ignore next -- pos is set only while the bubble is mounted. */
  74. if (el === null) return
  75. el.style.left = `${pos.x}px`
  76. const r = el.getBoundingClientRect()
  77. let dx = 0
  78. if (r.right > window.innerWidth - EDGE_MARGIN) dx = window.innerWidth - EDGE_MARGIN - r.right
  79. if (r.left + dx < EDGE_MARGIN) dx = EDGE_MARGIN - r.left
  80. el.style.left = `${pos.x + dx}px`
  81. if (side === 'right') return
  82. // Flip only into a side that genuinely fits, so an anchor with room on
  83. // neither side keeps the requested placement instead of oscillating.
  84. const fitsBelow = pos.bottom + 8 + r.height <= window.innerHeight - EDGE_MARGIN
  85. const fitsAbove = pos.top - 8 - r.height >= EDGE_MARGIN
  86. if (placement === 'bottom' && !fitsBelow && fitsAbove) setPlacement('top')
  87. if (placement === 'top' && !fitsAbove && fitsBelow) setPlacement('bottom')
  88. }
  89. fit()
  90. window.addEventListener('resize', fit)
  91. return () => { window.removeEventListener('resize', fit) }
  92. }, [placement, pos, resolvedLabel, side])
  93. const showTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
  94. // Hover and focus are independent triggers: the bubble hides only after
  95. // BOTH clear (hovering away from a focused anchor must not drop it).
  96. const triggers = useRef({ hover: false, focus: false })
  97. // Disabling mid-hover (e.g. clicking a rail control expands the sidebar)
  98. // must drop an already-visible bubble: no mouseleave fires.
  99. const cancelShow = useCallback(() => {
  100. if (showTimer.current === null) return
  101. clearTimeout(showTimer.current)
  102. showTimer.current = null
  103. }, [])
  104. useEffect(() => {
  105. if (disabled) {
  106. cancelShow()
  107. triggers.current = { hover: false, focus: false }
  108. setPos(null)
  109. }
  110. return cancelShow
  111. }, [cancelShow, disabled])
  112. const show = () => {
  113. if (disabled) return
  114. const el = anchor.current
  115. /* v8 ignore next -- the ref is attached by event time: events fire on the cloned anchor. */
  116. if (el === null) return
  117. const r = el.getBoundingClientRect()
  118. // Every show starts from the requested side; the fit pass flips it only
  119. // where this anchor's position demands it.
  120. setPlacement(side)
  121. setPos({ x: side === 'right' ? r.right + 10 : r.left + r.width / 2, top: r.top, bottom: r.bottom })
  122. }
  123. const showAfterHoverDelay = () => {
  124. cancelShow()
  125. if (delayMs <= 0) {
  126. show()
  127. return
  128. }
  129. showTimer.current = setTimeout(() => {
  130. showTimer.current = null
  131. show()
  132. }, delayMs)
  133. }
  134. const hide = () => {
  135. cancelShow()
  136. if (!triggers.current.hover && !triggers.current.focus) setPos(null)
  137. }
  138. return (
  139. <>
  140. {cloneElement(children, {
  141. ref: mergedRef,
  142. onMouseEnter: (e) => { children.props.onMouseEnter?.(e); triggers.current.hover = true; showAfterHoverDelay() },
  143. onMouseLeave: (e) => { children.props.onMouseLeave?.(e); triggers.current.hover = false; cancelShow(); setPos(null) },
  144. onFocus: (e) => { children.props.onFocus?.(e); triggers.current.focus = true; cancelShow(); show() },
  145. onBlur: (e) => { children.props.onBlur?.(e); triggers.current.focus = false; hide() },
  146. })}
  147. {pos !== null && (
  148. <span
  149. ref={bubble}
  150. className={css.bubble}
  151. data-side={placement}
  152. style={{ left: pos.x, top: y, ...maxWidth === undefined ? {} : { maxWidth } }}
  153. role="tooltip"
  154. >
  155. {resolvedLabel}
  156. </span>
  157. )}
  158. </>
  159. )
  160. }