File size: 9,887 Bytes
1e92f2d | 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 | import * as React from 'react';
import { CSSProperties, ReactElement, ReactNode, useEffect } from 'react';
import { createPortal } from 'react-dom';
import {
DefaultTooltipContent,
NameType,
Payload,
Props as DefaultTooltipContentProps,
ValueType,
} from './DefaultTooltipContent';
import { TooltipBoundingBox } from './TooltipBoundingBox';
import { Global } from '../util/Global';
import { getUniqPayload, UniqueOption } from '../util/payload/getUniqPayload';
import { AllowInDimension, AnimationDuration, AnimationTiming, ChartCoordinate, Coordinate } from '../util/types';
import { useViewBox } from '../context/chartLayoutContext';
import { useAccessibilityLayer } from '../context/accessibilityContext';
import { useElementOffset } from '../util/useElementOffset';
import { Cursor, CursorDefinition } from './Cursor';
import {
selectActiveCoordinate,
selectActiveLabel,
selectIsTooltipActive,
selectTooltipPayload,
} from '../state/selectors/selectors';
import { useTooltipPortal } from '../context/tooltipPortalContext';
import { TooltipTrigger } from '../chart/types';
import { useAppDispatch, useAppSelector } from '../state/hooks';
import { setTooltipSettingsState, TooltipIndex, TooltipPayload } from '../state/tooltipSlice';
import { AxisId } from '../state/cartesianAxisSlice';
import { useTooltipChartSynchronisation } from '../synchronisation/useChartSynchronisation';
import { useTooltipEventType } from '../state/selectors/selectTooltipEventType';
import { resolveDefaultProps } from '../util/resolveDefaultProps';
export type ContentType<TValue extends ValueType, TName extends NameType> =
| ReactElement
| ((props: TooltipContentProps<TValue, TName>) => ReactNode);
function defaultUniqBy<TValue extends ValueType, TName extends NameType>(entry: Payload<TValue, TName>) {
return entry.dataKey;
}
export type TooltipContentProps<TValue extends ValueType, TName extends NameType> = TooltipProps<TValue, TName> & {
label?: string | number;
payload: any[];
coordinate: ChartCoordinate;
active: boolean;
accessibilityLayer: boolean;
};
function renderContent<TValue extends ValueType, TName extends NameType>(
content: ContentType<TValue, TName>,
props: TooltipContentProps<TValue, TName>,
): ReactNode {
if (React.isValidElement(content)) {
return React.cloneElement(content, props);
}
if (typeof content === 'function') {
return React.createElement(content as any, props);
}
return <DefaultTooltipContent {...props} />;
}
type PropertiesReadFromContext = 'viewBox' | 'active' | 'payload' | 'coordinate' | 'label' | 'accessibilityLayer';
export type TooltipProps<TValue extends ValueType, TName extends NameType> = Omit<
DefaultTooltipContentProps<TValue, TName>,
PropertiesReadFromContext
> & {
/**
* If true, then Tooltip is always displayed, once an activeIndex is set by mouse over, or programmatically.
* If false, then Tooltip is never displayed.
* If active is undefined, Recharts will control when the Tooltip displays. This includes mouse and keyboard controls.
*/
active?: boolean;
/**
* If true, then Tooltip will information about hidden series (defaults to false).
* Interacting with the hide property of Area, Bar, Line, Scatter.
*
* default: false
*/
includeHidden?: boolean | undefined;
allowEscapeViewBox?: AllowInDimension;
animationDuration?: AnimationDuration;
animationEasing?: AnimationTiming;
content?: ContentType<TValue, TName>;
cursor?: CursorDefinition;
filterNull?: boolean;
defaultIndex?: number | TooltipIndex;
isAnimationActive?: boolean;
offset?: number;
payloadUniqBy?: UniqueOption<Payload<TValue, TName>>;
/**
* If portal is defined, then Tooltip will use this element as a target
* for rendering using React Portal: https://react.dev/reference/react-dom/createPortal
*
* If this is undefined then Tooltip renders inside the recharts-wrapper element.
*/
portal?: HTMLElement | null;
position?: Partial<Coordinate>;
reverseDirection?: AllowInDimension;
/**
* If true, tooltip will appear on top of all bars on an axis tick.
* If false, tooltip will appear on individual bars.
* Currently only supported in BarChart and RadialBarChart.
* If undefined then defaults to true.
*/
shared?: boolean;
/**
* If `hover` then the Tooltip shows on mouse enter and hides on mouse leave.
*
* If `click` then the Tooltip shows after clicking and stays active.
*
* Default `hover`
*/
trigger?: TooltipTrigger;
useTranslate3d?: boolean;
wrapperStyle?: CSSProperties;
/**
* Tooltip always attaches itself to the "Tooltip" axis. Which axis is it? Depends on the layout:
* - horizontal layout -> X axis
* - vertical layout -> Y axis
* - radial layout -> radial axis
* - centric layout -> angle axis
*
* Tooltip will use the default axis for the layout, unless you specify an axisId.
*/
axisId?: AxisId;
};
const emptyPayload: TooltipPayload = [];
const defaultTooltipProps = {
allowEscapeViewBox: { x: false, y: false },
animationDuration: 400,
animationEasing: 'ease',
axisId: 0,
contentStyle: {},
cursor: true,
filterNull: true,
isAnimationActive: !Global.isSsr,
itemSorter: 'name',
itemStyle: {},
labelStyle: {},
offset: 10,
reverseDirection: { x: false, y: false },
separator: ' : ',
trigger: 'hover',
useTranslate3d: false,
wrapperStyle: {},
} as const satisfies Partial<TooltipProps<any, any>>;
export function Tooltip<TValue extends ValueType, TName extends NameType>(outsideProps: TooltipProps<TValue, TName>) {
const props = resolveDefaultProps(outsideProps, defaultTooltipProps);
const {
active: activeFromProps,
allowEscapeViewBox,
animationDuration,
animationEasing,
content,
filterNull,
isAnimationActive,
offset,
payloadUniqBy,
position,
reverseDirection,
useTranslate3d,
wrapperStyle,
cursor,
shared,
trigger,
defaultIndex,
portal: portalFromProps,
axisId,
} = props;
const dispatch = useAppDispatch();
const defaultIndexAsString: string | null | undefined =
typeof defaultIndex === 'number' ? String(defaultIndex) : defaultIndex;
useEffect(() => {
dispatch(
setTooltipSettingsState({
shared,
trigger,
axisId,
active: activeFromProps,
defaultIndex: defaultIndexAsString,
}),
);
}, [dispatch, shared, trigger, axisId, activeFromProps, defaultIndexAsString]);
const viewBox = useViewBox();
const accessibilityLayer = useAccessibilityLayer();
const tooltipEventType = useTooltipEventType(shared);
const { activeIndex, isActive } = useAppSelector(state =>
selectIsTooltipActive(state, tooltipEventType, trigger, defaultIndexAsString),
);
const payloadFromRedux = useAppSelector(state =>
selectTooltipPayload(state, tooltipEventType, trigger, defaultIndexAsString),
);
const labelFromRedux = useAppSelector(state =>
selectActiveLabel(state, tooltipEventType, trigger, defaultIndexAsString),
);
const coordinate = useAppSelector(state =>
selectActiveCoordinate(state, tooltipEventType, trigger, defaultIndexAsString),
);
const payload: TooltipPayload = payloadFromRedux;
const tooltipPortalFromContext = useTooltipPortal();
/*
* The user can set `active=true` on the Tooltip in which case the Tooltip will stay always active,
* or `active=false` in which case the Tooltip never shows.
*
* If the `active` prop is not defined then it will show and hide based on mouse or keyboard activity.
*/
const finalIsActive = activeFromProps ?? isActive;
const [lastBoundingBox, updateBoundingBox] = useElementOffset([payload, finalIsActive]);
const finalLabel = tooltipEventType === 'axis' ? labelFromRedux : undefined;
useTooltipChartSynchronisation(tooltipEventType, trigger, coordinate, finalLabel, activeIndex, finalIsActive);
const tooltipPortal = portalFromProps ?? tooltipPortalFromContext;
if (tooltipPortal == null) {
return null;
}
let finalPayload: TooltipPayload = payload ?? emptyPayload;
if (!finalIsActive) {
finalPayload = emptyPayload;
}
if (filterNull && finalPayload.length) {
finalPayload = getUniqPayload(
payload.filter(entry => entry.value != null && (entry.hide !== true || props.includeHidden)),
payloadUniqBy,
defaultUniqBy,
);
}
const hasPayload = finalPayload.length > 0;
const tooltipElement = (
<TooltipBoundingBox
allowEscapeViewBox={allowEscapeViewBox}
animationDuration={animationDuration}
animationEasing={animationEasing}
isAnimationActive={isAnimationActive}
active={finalIsActive}
coordinate={coordinate}
hasPayload={hasPayload}
offset={offset}
position={position}
reverseDirection={reverseDirection}
useTranslate3d={useTranslate3d}
viewBox={viewBox}
wrapperStyle={wrapperStyle}
lastBoundingBox={lastBoundingBox}
innerRef={updateBoundingBox}
hasPortalFromProps={Boolean(portalFromProps)}
>
{renderContent(content, {
...props,
// @ts-expect-error renderContent method expects the payload to be mutable, TODO make it immutable
payload: finalPayload,
label: finalLabel,
active: finalIsActive,
coordinate,
accessibilityLayer,
})}
</TooltipBoundingBox>
);
return (
<>
{/* Tooltip the HTML element renders through a React portal so that it escapes clipping, and it renders on top of everything else */}
{createPortal(tooltipElement, tooltipPortal)}
{finalIsActive && (
<Cursor
cursor={cursor}
tooltipEventType={tooltipEventType}
coordinate={coordinate}
payload={payload}
index={activeIndex}
/>
)}
</>
);
}
|