nivo icon indicating copy to clipboard operation
nivo copied to clipboard

Custom Tooltip cuts off.

Open scio-cypher opened this issue 1 year ago • 10 comments

First of all, thanks for creating this library. Its awesome!

I think its already mentioned in #1358 that while hovering on left or right then the tooltip gets cut. In #631 it was supposed to be fixed but no change is visible.

However one work around was provided by @luiz-chagaz in #1358 that wrapping my custom tooltip with TooltipWrapper makes it better. But after wrapping my tooltip, it doesn't even shows up now.

Can you please fix this or give some better workaround.

Case 1: Tooltip gets cut: Image

Code:

const renderTooltip = ({ datum }) => {
    return (
        <div style={{ background: 'white', padding: '9px 12px', border: '1px solid #ccc', borderRadius: '4px', boxShadow: '0 2px 4px rgba(0,0,0,0.1)' }}>
            <strong>{datum.label}</strong>: {datum.value}
        </div>
    );
}

<ResponsivePie
    data={pieChartData}
    margin={{ top: 5, right: 0, bottom: 5, left: 0 }}
    innerRadius={0.6}
    padAngle={0.2}
    cornerRadius={1}
    activeOuterRadiusOffset={5}
    arcLabelsComponent={({ datum, label, style }) => 
        <animated.g transform={style.transform} className="cursor-pointer pointer-events-none">
            <text textAnchor="middle" dominantBaseline="central" className="font-medium text-sm">
                {label}
            </text>
        </animated.g>
    }
    colors={({ data }) => (selectedId === null || data.id === selectedId) ? data?.color : getLightGreyShade()}
    enableArcLinkLabels={false}
    onMouseEnter={(slice, event) => {
        event.target.style.cursor = 'pointer';
    }}
    arcLabelsSkipAngle={6}
    activeId={selectedId}
    onClick={handleClick}
    layers={['arcs', 'arcLabels', 'arcLinkLabels', 'legends', CenteredMetric]}
    tooltip={renderTooltip}
/>

Case 2:

Image not providing as tooltip is not visible so it'd look like I'm not even hovering on it.

Code:

const renderTooltip = ({ datum }) => {
    return (
        <TooltipWrapper anchor="left" position={[0, 0]}>
            <div style={{ background: 'white', padding: '9px 12px', border: '1px solid #ccc', borderRadius: '4px', boxShadow: '0 2px 4px rgba(0,0,0,0.1)' }}>
                <strong>{datum.label}</strong>: {datum.value}
            </div>
        </TooltipWrapper>
    );
}

<ResponsivePie
    data={pieChartData}
    margin={{ top: 5, right: 0, bottom: 5, left: 0 }}
    innerRadius={0.6}
    padAngle={0.2}
    cornerRadius={1}
    activeOuterRadiusOffset={5}
    arcLabelsComponent={({ datum, label, style }) => 
        <animated.g transform={style.transform} className="cursor-pointer pointer-events-none">
            <text textAnchor="middle" dominantBaseline="central" className="font-medium text-sm">
                {label}
            </text>
        </animated.g>
    }
    colors={({ data }) => (selectedId === null || data.id === selectedId) ? data?.color : getLightGreyShade()}
    enableArcLinkLabels={false}
    onMouseEnter={(slice, event) => {
        event.target.style.cursor = 'pointer';
    }}
    arcLabelsSkipAngle={6}
    activeId={selectedId}
    onClick={handleClick}
    layers={['arcs', 'arcLabels', 'arcLinkLabels', 'legends', CenteredMetric]}
    tooltip={renderTooltip}
/>

Thank you in advance! Appreciate it.

scio-cypher avatar Sep 12 '24 11:09 scio-cypher

But after wrapping my tooltip, it doesn't even shows up now.

I have the same issue here, a fix would be great...

harrynorthover avatar Oct 16 '24 15:10 harrynorthover

I got over that issue using createPortal function in React.

const CustomTooltip = ({ data, position }) => {
    const tooltipRef = useRef(null); // Reference to the tooltip element
    const [tooltipWidth, setTooltipWidth] = useState(0);

    useEffect(() => {
        if (tooltipRef.current) {
          const rect = tooltipRef.current.getBoundingClientRect();
          setTooltipWidth(rect.width); // Dynamically set the width of the tooltip
        }
    }, [data]); // Recalculate when data changes (i.e., when a new tooltip appears)
    
    return createPortal(
        <div
            ref={tooltipRef}
            style={{ position: 'absolute', top: position.y - 60, left: position.x - (tooltipWidth/2) }}
            className={`${tooltipConfigs.pieConstantClassnames} ${tooltipConfigs.colors.defaults.bgColorClassName} ${tooltipConfigs.colors.defaults.textColorClassName}`}
        >
            <div
                className="absolute font-normal -translate-x-1/2 top-full left-1/2 w-0 h-0 border-l-[6px] border-solid border-l-transparent border-r-[6px] border-r-transparent border-t-[6px] border-t-[#002E64]"
                style={{ filter: 'drop-shadow(0 1px 1px rgba(0,0,0,0.1))' }}
            />
            <strong>{data.label}:</strong> {data.value}
        </div>,
        document.body // Renders the tooltip outside the scrollable container
    );
};

@harrynorthover try this

scio-cypher avatar Oct 22 '24 10:10 scio-cypher

Thanks @scio-cypher - where does the position param come from here?

harrynorthover avatar Oct 23 '24 15:10 harrynorthover

@harrynorthover You have to maintain state variables. Have a look at this example.

const PieChart = () => {
    const [tooltipData, setTooltipData] = useState(null);
    const [tooltipPosition, setTooltipPosition] = useState({ x: 0, y: 0 });
    return (
        <div className={"w-full"}>
            <ResponsivePie
                data={pieChartData}
                margin={{ top: 5, right: 0, bottom: 5, left: 0 }}
                innerRadius={0.6}
                padAngle={0.2}
                cornerRadius={1}
                activeOuterRadiusOffset={5}
                arcLabelsComponent={({ datum, label, style }) => 
                    <animated.g transform={style.transform} className="cursor-pointer pointer-events-none">
                        <text textAnchor="middle" dominantBaseline="central" className="font-medium text-sm">
                            {label}
                        </text>
                    </animated.g>
                }
                enableArcLinkLabels={false}
                arcLabelsSkipAngle={14}
                layers={['arcs', 'arcLabels', 'arcLinkLabels', 'legends']}
                tooltip={({ datum }) => {
                    setTooltipData(datum);
                    return null; // Prevent the default tooltip rendering
                }}
                onMouseMove={(sliceData, event) => {
                    setTooltipPosition({ x: event.clientX, y: event.clientY });
                }}
                onMouseLeave={() => setTooltipData(null)}
            />
            {tooltipData && (
                <CustomTooltip data={tooltipData} position={tooltipPosition} />
            )}
        </div>
    )
}

scio-cypher avatar Oct 23 '24 15:10 scio-cypher

Same issue here. @scio-cypher you should use a ref for the mouse position and not a state.

const tooltipPosRef = useRef({x:0, y:0});

and in your graph:

onMouseMove={(sliceData, event) => {
     tooltipPosRef.current.x = event.clientX;
     tooltipPosRef.current.y = event.clientY;
}}

ligoo avatar Dec 17 '24 20:12 ligoo

Same issue. Would be a good idea to pass a tooltipAnchor to the chart as prop.

In addition to your workarounds, ResponsiveBar does not even have onMouseMove. Instead, position should be taken from the tooltip datum. Sad.

zhikin2207 avatar Feb 26 '25 03:02 zhikin2207

A quick fix for now. Create a copy of nivo BarItem, but pass left as an anchor for tooltip actions. In the chart itself use barComponent={CustomBarItem}. Hope this issue will be fixed soon.

import { createElement, MouseEvent, useCallback, useMemo } from 'react'
import { animated, to } from '@react-spring/web'
import { useTheme } from '@nivo/core'
import { useTooltip } from '@nivo/tooltip'
import { BarDatum, BarItemProps } from '@nivo/bar'

export const CustomBarItem = <RawDatum extends BarDatum>({
  bar: { data, ...bar },

  style: {
    borderColor,
    color,
    height,
    labelColor,
    labelOpacity,
    labelX,
    labelY,
    transform,
    width,
    textAnchor,
  },

  borderRadius,
  borderWidth,

  label,
  shouldRenderLabel,

  isInteractive,
  onClick,
  onMouseEnter,
  onMouseLeave,

  tooltip,

  isFocusable,
  ariaLabel,
  ariaLabelledBy,
  ariaDescribedBy,
  ariaDisabled,
  ariaHidden,
}: BarItemProps<RawDatum>) => {
  const theme = useTheme()
  const { showTooltipFromEvent, showTooltipAt, hideTooltip } = useTooltip()

  const renderTooltip = useMemo(
    () => () => createElement(tooltip, { ...bar, ...data }),
    [tooltip, bar, data]
  )

  const handleClick = useCallback(
    (event: MouseEvent<SVGRectElement>) => {
      onClick?.({ color: bar.color, ...data }, event)
    },
    [bar, data, onClick]
  )
  const handleTooltip = useCallback(
    (event: MouseEvent<SVGRectElement>) => showTooltipFromEvent(renderTooltip(), event, 'left'),
    [showTooltipFromEvent, renderTooltip]
  )
  const handleMouseEnter = useCallback(
    (event: MouseEvent<SVGRectElement>) => {
      onMouseEnter?.(data, event)
      showTooltipFromEvent(renderTooltip(), event, 'left')
    },
    [data, onMouseEnter, showTooltipFromEvent, renderTooltip]
  )
  const handleMouseLeave = useCallback(
    (event: MouseEvent<SVGRectElement>) => {
      onMouseLeave?.(data, event)
      hideTooltip()
    },
    [data, hideTooltip, onMouseLeave]
  )

  // extra handlers to allow keyboard navigation
  const handleFocus = useCallback(() => {
    showTooltipAt(renderTooltip(), [bar.absX + bar.width / 2, bar.absY], 'left')
  }, [showTooltipAt, renderTooltip, bar])
  const handleBlur = useCallback(() => {
    hideTooltip()
  }, [hideTooltip])

  return (
    <animated.g transform={transform}>
      <animated.rect
        width={to(width, value => Math.max(value, 0))}
        height={to(height, value => Math.max(value, 0))}
        rx={borderRadius}
        ry={borderRadius}
        fill={data.fill ?? color}
        strokeWidth={borderWidth}
        stroke={borderColor}
        focusable={isFocusable}
        tabIndex={isFocusable ? 0 : undefined}
        aria-label={ariaLabel ? ariaLabel(data) : undefined}
        aria-labelledby={ariaLabelledBy ? ariaLabelledBy(data) : undefined}
        aria-describedby={ariaDescribedBy ? ariaDescribedBy(data) : undefined}
        aria-disabled={ariaDisabled ? ariaDisabled(data) : undefined}
        aria-hidden={ariaHidden ? ariaHidden(data) : undefined}
        onMouseEnter={isInteractive ? handleMouseEnter : undefined}
        onMouseMove={isInteractive ? handleTooltip : undefined}
        onMouseLeave={isInteractive ? handleMouseLeave : undefined}
        onClick={isInteractive ? handleClick : undefined}
        onFocus={isInteractive && isFocusable ? handleFocus : undefined}
        onBlur={isInteractive && isFocusable ? handleBlur : undefined}
      />
      {shouldRenderLabel && (
        <animated.text
          x={labelX}
          y={labelY}
          textAnchor={textAnchor}
          dominantBaseline="central"
          fillOpacity={labelOpacity}
          style={{
            ...theme.labels.text,
            pointerEvents: 'none',
            fill: labelColor,
          }}
        >
          {label}
        </animated.text>
      )}
    </animated.g>
  )
}

zhikin2207 avatar Feb 26 '25 05:02 zhikin2207

The fix in https://github.com/plouc/nivo/pull/631 only works for left and right anchors, but the default is top for the bar chart, this should probably become an option, and the tooltips should optionally be rendered in a portal.

plouc avatar Apr 28 '25 23:04 plouc

This issue has been automatically marked as stale. If this issue is still affecting you, please leave any comment (for example, "bump"), and we'll keep it open. We are sorry that we haven't been able to prioritize it yet. If you have any new additional information, please include it with your comment!

stale[bot] avatar Jul 29 '25 01:07 stale[bot]

bump

reallyely avatar Aug 11 '25 12:08 reallyely

This issue has been automatically marked as stale. If this issue is still affecting you, please leave any comment (for example, "bump"), and we'll keep it open. We are sorry that we haven't been able to prioritize it yet. If you have any new additional information, please include it with your comment!

stale[bot] avatar Dec 17 '25 23:12 stale[bot]