All files / src/components/display Tooltip.tsx

97.26% Statements 71/73
86.66% Branches 26/30
100% Functions 12/12
97.26% Lines 71/73

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201                                                                    68x     68x                                   1966x 1966x 1966x 1966x 1966x 1966x   1966x   1966x 146x     146x 146x 146x 146x 146x   86x 86x 86x   51x 51x 51x   5x 5x 5x   4x 4x 4x   146x     1966x   205x 55x   205x 146x 146x 146x           1966x 97x   1966x 108x     1966x 84x 3x 3x   84x       1966x 1157x 1029x   128x 30x 7x     128x 128x 128x 128x 118x 118x 118x         1966x 959x 800x           1966x 1966x             1966x 1966x 1966x 1966x 1966x         1966x           1966x                       1966x                            
import {
  cloneElement,
  isValidElement,
  useCallback,
  useEffect,
  useId,
  useRef,
  useState,
  type JSX,
  type ReactElement,
  type ReactNode,
} from "react";
import { createPortal } from "react-dom";
import { type TooltipBuiltinProps, type TooltipPlacement } from "@grackle-ai/common";
import styles from "./Tooltip.module.scss";
 
// `text`/`placement`/`delayMs` now live in the built-in's zod schema
// (@grackle-ai/common); re-export TooltipPlacement so the package barrel keeps
// exposing it.
export type { TooltipPlacement };
 
/** Props for the {@link Tooltip} component. */
export interface TooltipProps extends TooltipBuiltinProps {
  /** Whether the wrapper is inline (`span`) or block (`div`). Defaults to `true`. */
  inline?: boolean;
  /** The trigger element to wrap. */
  children: ReactNode;
  /** Additional CSS class for the wrapper element. */
  className?: string;
  /** Test ID for the tooltip content element. */
  "data-testid"?: string;
}
 
/** Default delay in milliseconds before the tooltip appears. */
const DEFAULT_DELAY_MS: number = 300;
 
/** Gap in pixels between the tooltip and the trigger element. */
const TOOLTIP_GAP_PX: number = 6;
 
/**
 * Lightweight tooltip wrapper that shows text on hover or keyboard focus.
 *
 * Wraps a single child element with a hover/focus-triggered tooltip.
 * Renders the tooltip bubble via a portal to `document.body` so it escapes
 * all stacking contexts, `overflow: hidden`, and `backdrop-filter` traps.
 */
export function Tooltip({
  text,
  placement = "top",
  delayMs = DEFAULT_DELAY_MS,
  inline = true,
  children,
  className,
  "data-testid": testId,
}: TooltipProps): JSX.Element {
  const [visible, setVisible] = useState(false);
  const [coords, setCoords] = useState<{ top: number; left: number }>({ top: 0, left: 0 });
  const wrapperRef = useRef<HTMLElement>(null);
  const tooltipRef = useRef<HTMLDivElement>(null);
  const timerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
  const tooltipId = useId();
 
  const canPortal = typeof document !== "undefined";
 
  const computePosition = useCallback((): void => {
    Iif (!wrapperRef.current || !tooltipRef.current) {
      return;
    }
    const rect = wrapperRef.current.getBoundingClientRect();
    const tipRect = tooltipRef.current.getBoundingClientRect();
    let top = 0;
    let left = 0;
    switch (placement) {
      case "top":
        top = rect.top - tipRect.height - TOOLTIP_GAP_PX;
        left = rect.left + rect.width / 2 - tipRect.width / 2;
        break;
      case "bottom":
        top = rect.bottom + TOOLTIP_GAP_PX;
        left = rect.left + rect.width / 2 - tipRect.width / 2;
        break;
      case "left":
        top = rect.top + rect.height / 2 - tipRect.height / 2;
        left = rect.left - tipRect.width - TOOLTIP_GAP_PX;
        break;
      case "right":
        top = rect.top + rect.height / 2 - tipRect.height / 2;
        left = rect.right + TOOLTIP_GAP_PX;
        break;
    }
    setCoords({ top, left });
  }, [placement]);
 
  const showWithDelay = useCallback(
    (delay: number): void => {
      if (timerRef.current !== undefined) {
        clearTimeout(timerRef.current);
      }
      timerRef.current = setTimeout(() => {
        computePosition();
        setVisible(true);
        timerRef.current = undefined;
      }, delay);
    },
    [computePosition],
  );
 
  const showHover = useCallback((): void => {
    showWithDelay(delayMs);
  }, [delayMs, showWithDelay]);
  const showFocus = useCallback((): void => {
    showWithDelay(0);
  }, [showWithDelay]);
 
  const hide = useCallback((): void => {
    if (timerRef.current !== undefined) {
      clearTimeout(timerRef.current);
      timerRef.current = undefined;
    }
    setVisible(false);
  }, []);
 
  // Dismiss on Escape key; reposition on scroll/resize while visible.
  useEffect(() => {
    if (!visible) {
      return;
    }
    const handleKeyDown = (event: KeyboardEvent): void => {
      if (event.key === "Escape") {
        hide();
      }
    };
    document.addEventListener("keydown", handleKeyDown);
    window.addEventListener("scroll", computePosition, true);
    window.addEventListener("resize", computePosition);
    return () => {
      document.removeEventListener("keydown", handleKeyDown);
      window.removeEventListener("scroll", computePosition, true);
      window.removeEventListener("resize", computePosition);
    };
  }, [visible, hide, computePosition]);
 
  // Cleanup timer on unmount
  useEffect(() => {
    return () => {
      Iif (timerRef.current !== undefined) {
        clearTimeout(timerRef.current);
      }
    };
  }, []);
 
  const Tag = inline ? "span" : "div";
  const wrapperClass = [inline ? styles.wrapper : styles.wrapperBlock, className]
    .filter(Boolean)
    .join(" ");
 
  // Inject aria-describedby onto the child element when it is a single
  // ReactElement so screen readers announce the tooltip from the focused node.
  // Merges with any existing aria-describedby value on the child.
  let renderedChildren: React.ReactNode = children;
  if (isValidElement(children)) {
    const child = children as ReactElement<{ "aria-describedby"?: string }>;
    const existing = child.props["aria-describedby"];
    const mergedDescribedBy = visible
      ? existing
        ? `${existing} ${tooltipId}`
        : tooltipId
      : existing;
    renderedChildren = cloneElement(child, {
      "aria-describedby": mergedDescribedBy,
    });
  }
 
  const tooltipElement = (
    <div
      ref={tooltipRef}
      id={tooltipId}
      role="tooltip"
      className={`${styles.tooltip} ${styles[placement]} ${visible ? styles.visible : ""}`}
      style={{ top: coords.top, left: coords.left }}
      data-testid={testId ?? "tooltip"}
    >
      {text}
    </div>
  );
 
  return (
    <Tag
      ref={wrapperRef as React.Ref<HTMLSpanElement & HTMLDivElement>}
      className={wrapperClass}
      onMouseEnter={showHover}
      onMouseLeave={hide}
      onFocus={showFocus}
      onBlur={hide}
    >
      {renderedChildren}
      {canPortal ? createPortal(tooltipElement, document.body) : null}
    </Tag>
  );
}