All files / src/utilities SVGTooltipText.tsx

61.11% Statements 66/108
46.15% Branches 24/52
39.13% Functions 9/23
56.7% Lines 55/97

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 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 30631x 31x 31x                                                                                                                                                 31x 31x     31x             71x         71x       71x   71x         71x     31x 143x 143x 143x                           143x   143x                                       31x 71x     31x 72x 29x       31x 41x 1x     41x     71x       71x       71x 143x 71x     72x     71x                 71x                             71x 1x   1x     1x   1x 1x                                             71x                                     71x               71x       71x       71x           71x           71x                     71x 100x   100x 100x 12x     100x 12x     31x  
import * as React from 'react';
import { ITooltipHost, ITooltipProps, Tooltip, TooltipDelay } from '@fluentui/react/lib/Tooltip';
import { Async, KeyCodes, getId, portalContainsElement } from '../Utilities';
 
interface ISVGTooltipTextProps {
  /**
   * Number of milliseconds to delay closing the tooltip, so that the user has time to hover over
   * the tooltip and interact with it. Hovering over the tooltip will count as hovering over the
   * host, so that the tooltip will stay open if the user is actively interacting with it.
   */
  closeDelay?: number;
 
  /**
   * Content to display in the Tooltip.
   */
  content?: string;
 
  /**
   * Length of delay before showing the tooltip on hover.
   * @defaultvalue TooltipDelay.medium
   */
  delay?: TooltipDelay;
 
  /**
   * Additional properties to pass through for Tooltip.
   */
  tooltipProps?: ITooltipProps;
 
  /**
   * Additional properties to pass through for SVG <text>.
   */
  textProps?: React.SVGAttributes<SVGTextElement>;
 
  /**
   * Max width of text
   */
  maxWidth?: number;
 
  /**
   * Max height of text
   */
  maxHeight?: number;
 
  /**
   * Pass false to make prevent the tooptip from receiving focus through keyboard
   * Eg: In Pie Chart, the focus should only land on the arcs and not on the text to
   * avoid repitition of the same datapoint
   * @defaultvalue true
   */
  shouldReceiveFocus?: boolean;
 
  /**
   * Pass true to show tooltip directly
   * Eg: In Pie Chart, the tooltip is shown when the arc is focussed, so the prop is set to true,
   * to directly show the tooltip from this component
   * @defaultvalue false
   */
  isTooltipVisibleProp?: boolean;
 
  /**
   * Function to wrap text within specified width and height
   * and return a boolean value indicating whether the text overflowed
   */
  wrapContent?: (content: string, id: string, maxWidth: number, maxHeight?: number) => boolean;
}
 
interface ISVGTooltipTextState {
  isTooltipVisible: boolean;
  isOverflowing: boolean;
}
 
/**
 * Component to render an SVG text element with an optional tooltip.
 * The tooltip appears on hovering and focusing the element when its content overflows.
 */
export class SVGTooltipText
  extends React.Component<ISVGTooltipTextProps, ISVGTooltipTextState>
  implements ITooltipHost
{
  public static defaultProps = {
    delay: TooltipDelay.medium,
  };
 
  private static _currentVisibleTooltip: ITooltipHost | undefined;
 
  /** The element that gets the hover events */
  private _tooltipHost = React.createRef<SVGTextElement>();
 
  private _async: Async;
  private _dismissTimerId: number;
  private _openTimerId: number;
  private _tooltipHostId = getId('tooltip-host');
  private _ignoreNextFocusEvent: boolean;
 
  constructor(props: ISVGTooltipTextProps) {
    super(props);
 
    this.state = {
      isTooltipVisible: false,
      isOverflowing: false,
    };
 
    this._async = new Async(this);
  }
 
  public render(): React.ReactNode {
    const { content, tooltipProps, textProps, shouldReceiveFocus = true } = this.props;
    const { isTooltipVisible } = this.state;
    const tooltipRenderProps: ITooltipProps = {
      content,
      targetElement: this._getTargetElement(),
      calloutProps: {
        onDismiss: this._hideTooltip,
        onMouseEnter: this._onTooltipMouseEnter,
        onMouseLeave: this._onTooltipMouseLeave,
      },
      onMouseEnter: this._onTooltipMouseEnter,
      onMouseLeave: this._onTooltipMouseLeave,
      ...tooltipProps,
    };
 
    const showTooltip =
      (!!this.props.isTooltipVisibleProp && this.state.isOverflowing && !!content) || (isTooltipVisible && !!content);
 
    return (
      <>
        <text
          {...textProps}
          id={this._tooltipHostId}
          ref={this._tooltipHost}
          onFocusCapture={this._onTooltipFocus}
          onBlurCapture={this._onTooltipBlur}
          onMouseEnter={this._onTooltipMouseEnter}
          onMouseLeave={this._onTooltipMouseLeave}
          onKeyDown={this._onTooltipKeyDown}
          data-is-focusable={shouldReceiveFocus && this.state.isOverflowing}
        >
          {content}
        </text>
        {showTooltip && <Tooltip {...tooltipRenderProps} />}
      </>
    );
  }
 
  public componentDidMount(): void {
    this._wrapContent();
  }
 
  public componentDidUpdate(prevProps: Readonly<ISVGTooltipTextProps>): void {
    if (this.props.maxWidth !== prevProps.maxWidth || this.props.maxHeight !== prevProps.maxHeight) {
      this._wrapContent();
    }
  }
 
  public componentWillUnmount(): void {
    if (SVGTooltipText._currentVisibleTooltip && SVGTooltipText._currentVisibleTooltip === this) {
      SVGTooltipText._currentVisibleTooltip = undefined;
    }
 
    this._async.dispose();
  }
 
  public show = (): void => {
    this._toggleTooltip(true);
  };
 
  public dismiss = (): void => {
    this._hideTooltip();
  };
 
  private _getTargetElement = (): HTMLElement | undefined => {
    if (!this._tooltipHost.current) {
      return undefined;
    }
 
    return this._tooltipHost.current as unknown as HTMLElement;
  };
 
  private _onTooltipFocus = (ev: React.FocusEvent<SVGElement>) => {
    Iif (this._ignoreNextFocusEvent) {
      this._ignoreNextFocusEvent = false;
      return;
    }
 
    this._onTooltipMouseEnter(ev);
  };
 
  private _onTooltipBlur = (ev: React.FocusEvent<SVGElement>) => {
    // The focused element gets a blur event when the document loses focus
    // (e.g. switching tabs in the browser), but we don't want to show the
    // tooltip again when the document gets focus back. Handle this case by
    // checking if the blurred element is still the document's activeElement,
    // and ignoring when it next gets focus back.
    // See https://github.com/microsoft/fluentui/issues/13541
    this._ignoreNextFocusEvent = document?.activeElement === ev.target;
 
    this._dismissTimerId = this._async.setTimeout(() => {
      this._hideTooltip();
    }, 0);
  };
 
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  private _onTooltipMouseEnter = (ev: any): void => {
    const { delay } = this.props;
 
    Iif (SVGTooltipText._currentVisibleTooltip && SVGTooltipText._currentVisibleTooltip !== this) {
      SVGTooltipText._currentVisibleTooltip.dismiss();
    }
    SVGTooltipText._currentVisibleTooltip = this;
 
    if (!this.state.isOverflowing) {
      return;
    }
 
    Iif (ev.target && portalContainsElement(ev.target as HTMLElement, this._getTargetElement())) {
      // Do not show tooltip when target is inside a portal relative to TooltipHost.
      return;
    }
 
    this._clearDismissTimer();
    this._clearOpenTimer();
 
    if (delay !== TooltipDelay.zero) {
      const delayTime = this._getDelayTime(delay!); // non-null assertion because we set it in `defaultProps`
 
      this._openTimerId = this._async.setTimeout(() => {
        this._toggleTooltip(true);
      }, delayTime);
    } else {
      this._toggleTooltip(true);
    }
  };
 
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  private _onTooltipMouseLeave = (ev: any): void => {
    const { closeDelay } = this.props;
 
    this._clearDismissTimer();
    this._clearOpenTimer();
 
    if (closeDelay) {
      this._dismissTimerId = this._async.setTimeout(() => {
        this._toggleTooltip(false);
      }, closeDelay);
    } else {
      this._toggleTooltip(false);
    }
 
    Iif (SVGTooltipText._currentVisibleTooltip === this) {
      SVGTooltipText._currentVisibleTooltip = undefined;
    }
  };
 
  private _onTooltipKeyDown = (ev: React.KeyboardEvent<SVGElement>): void => {
    // eslint-disable-next-line deprecation/deprecation
    Iif ((ev.which === KeyCodes.escape || ev.ctrlKey) && this.state.isTooltipVisible) {
      this._hideTooltip();
      ev.stopPropagation();
    }
  };
 
  private _clearDismissTimer = (): void => {
    this._async.clearTimeout(this._dismissTimerId);
  };
 
  private _clearOpenTimer = (): void => {
    this._async.clearTimeout(this._openTimerId);
  };
 
  private _hideTooltip = (): void => {
    this._clearOpenTimer();
    this._clearDismissTimer();
    this._toggleTooltip(false);
  };
 
  private _toggleTooltip = (isTooltipVisible: boolean): void => {
    Iif (this.state.isTooltipVisible !== isTooltipVisible) {
      this.setState({ isTooltipVisible });
    }
  };
 
  private _getDelayTime = (delay: TooltipDelay): number => {
    switch (delay) {
      case TooltipDelay.medium:
        return 300;
      case TooltipDelay.long:
        return 500;
      default:
        return 0;
    }
  };
 
  private _wrapContent = () => {
    const { content, wrapContent, maxWidth = Number.POSITIVE_INFINITY, maxHeight } = this.props;
 
    let isOverflowing = false;
    if (content && wrapContent && wrapContent(content, this._tooltipHostId, maxWidth, maxHeight)) {
      isOverflowing = true;
    }
 
    if (this.state.isOverflowing !== isOverflowing) {
      this.setState({ isOverflowing });
    }
  };
}