diff --git a/packages/polaris-viz/src/components/StackedAreaChart/Chart.tsx b/packages/polaris-viz/src/components/StackedAreaChart/Chart.tsx index 0cf69b7dd8..d40e801dd5 100644 --- a/packages/polaris-viz/src/components/StackedAreaChart/Chart.tsx +++ b/packages/polaris-viz/src/components/StackedAreaChart/Chart.tsx @@ -62,6 +62,7 @@ import {useStackedData} from './hooks'; import {StackedAreas, Points} from './components'; import {useStackedChartTooltipContent} from './hooks/useStackedChartTooltipContent'; import {yAxisMinMax} from './utilities/yAxisMinMax'; +import {getAlteredStackedAreaChartPosition} from './utilities/getAlteredStackedAreaChartPosition'; import styles from './Chart.scss'; const TOOLTIP_POSITION: TooltipPositionOffset = { @@ -382,6 +383,7 @@ export function Chart({ focusElementDataType={DataType.Point} getMarkup={getTooltipMarkup} getPosition={getTooltipPosition} + getAlteredPosition={getAlteredStackedAreaChartPosition} id={tooltipId} margin={ChartMargin} onIndexChange={(index) => setActivePointIndex(index)} diff --git a/packages/polaris-viz/src/components/StackedAreaChart/utilities/getAlteredStackedAreaChartPosition.ts b/packages/polaris-viz/src/components/StackedAreaChart/utilities/getAlteredStackedAreaChartPosition.ts new file mode 100644 index 0000000000..b01023770a --- /dev/null +++ b/packages/polaris-viz/src/components/StackedAreaChart/utilities/getAlteredStackedAreaChartPosition.ts @@ -0,0 +1,54 @@ +import type {Dimensions} from '@shopify/polaris-viz-core'; + +import type {TooltipPositionOffset} from '../../TooltipWrapper'; +import type {Margin} from '../../../types'; + +// The space between the cursor and the tooltip +const TOOLTIP_MARGIN = 20; + +export interface AlteredPositionProps { + bandwidth: number; + chartBounds: {x: number; y: number; width: number; height: number}; + currentX: number; + currentY: number; + isPerformanceImpacted: boolean; + margin: Margin; + position: TooltipPositionOffset; + tooltipDimensions: Dimensions; +} + +export interface AlteredPositionReturn { + x: number; + y: number; +} + +export type AlteredPosition = ( + props: AlteredPositionProps, +) => AlteredPositionReturn; + +export function getAlteredStackedAreaChartPosition({ + currentX, + currentY, + chartBounds, + margin, + tooltipDimensions, +}: AlteredPositionProps): AlteredPositionReturn { + const x = Math.min( + Math.max(currentX, TOOLTIP_MARGIN), + chartBounds.width - tooltipDimensions.width - TOOLTIP_MARGIN, + ); + + // Y POSITIONING + // If y is below the chart, adjust the tooltip position to the bottom of the chart + // + + const y = + currentY >= chartBounds.y + chartBounds.height + ? chartBounds.height - + tooltipDimensions.height - + TOOLTIP_MARGIN - + margin.Bottom + : currentY; + + return {x, y}; +}