Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(quill-charts): remove memos that guard nothing (#125334)

Sam Penningtona7ab6861de89
diff --git a/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsx b/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsx
index 264f26d7d343..2f76b5087805 100644
--- a/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsx
+++ b/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsx
@@ -4,9 +4,8 @@ import { ChartLegend } from '../../components/Legend/ChartLegend'
import { useChartLegend } from '../../components/Legend/useChartLegend'
import { bandCenter, type BarChartPrivate, groupedBarCenter } from '../../core/bar-layout'
import { Chart } from '../../core/Chart'
-import { applyChartDefaults } from '../../core/chart-config'
+import { applyChartDefaults, PERCENT_TICK_FORMATTER } from '../../core/chart-config'
import { ChartErrorBoundary } from '../../core/ChartErrorBoundary'
-import { useLatest } from '../../core/hooks/useLatest'
import {
buildSegmentResolveValue,
buildStackedBottomValue,
@@ -88,7 +87,7 @@ function BarChartInner<Meta = unknown>({
children,
}: Omit<BarChartProps<Meta>, 'onError'>): React.ReactElement {
const theme = useResolvedChartTheme(themeProp)
- const config = useMemo(() => applyChartDefaults(rawConfig), [rawConfig])
+ const config = applyChartDefaults(rawConfig)
const {
yScaleType = 'linear',
showGrid = false,
@@ -100,7 +99,6 @@ function BarChartInner<Meta = unknown>({
yAxes: configYAxes,
} = config ?? {}
const { x: xAxisLine, y: yAxisLine } = resolveAxisLines(showAxisLines)
- const axisLines = useMemo(() => ({ x: xAxisLine, y: yAxisLine }), [xAxisLine, yAxisLine])
const {
track: trackConfig = false,
shadow: barShadow,
@@ -125,13 +123,7 @@ function BarChartInner<Meta = unknown>({
const resolvedMinBandSize = minBandSize ?? (isHorizontal ? HORIZONTAL_MIN_BAND_SIZE_DEFAULT : 0)
const wrapperMinHeight = useMemo(
- () =>
- computeWrapperMinHeight({
- isHorizontal,
- fitToHeight,
- resolvedMinBandSize,
- labels,
- }),
+ () => computeWrapperMinHeight({ isHorizontal, fitToHeight, resolvedMinBandSize, labels }),
[isHorizontal, fitToHeight, resolvedMinBandSize, labels]
)
@@ -155,16 +147,11 @@ function BarChartInner<Meta = unknown>({
[barLayout, visibleSeries]
)
- const chartConfig = useMemo<BarChartConfig>(() => {
- const base = { ...config, isPercent: barLayout === 'percent' }
- if (barLayout !== 'percent' || config?.yTickFormatter) {
- return base
- }
- return {
- ...base,
- yTickFormatter: (v: number) => `${Math.round(v * 100)}%`,
- }
- }, [config, barLayout])
+ const chartConfig: BarChartConfig = {
+ ...config,
+ isPercent: barLayout === 'percent',
+ yTickFormatter: config?.yTickFormatter ?? (barLayout === 'percent' ? PERCENT_TICK_FORMATTER : undefined),
+ }
const createScales: CreateScalesFn = useCallback(
(coloredSeries: ResolvedSeries[], scaleLabels: string[], dimensions: ChartDimensions): ChartScales => {
@@ -292,7 +279,7 @@ function BarChartInner<Meta = unknown>({
barLayout,
isHorizontal,
showGrid,
- axisLines,
+ axisLines: { x: xAxisLine, y: yAxisLine },
xTickFormatter,
stackedData,
topStackedKeyByAxis,
@@ -306,7 +293,8 @@ function BarChartInner<Meta = unknown>({
}),
[
showGrid,
- axisLines,
+ xAxisLine,
+ yAxisLine,
stackedData,
barLayout,
isHorizontal,
@@ -375,65 +363,56 @@ function BarChartInner<Meta = unknown>({
// Show each series's own segment value (resolveValue) but anchor the tooltip/value labels
// at the stacked top (resolvePositionValue) so a stacked bar doesn't read as a running total.
- const resolveValue = useMemo(() => buildSegmentResolveValue(stackedData), [stackedData])
- const resolvePositionValue = useMemo(() => buildStackedPositionValue(stackedData), [stackedData])
- const resolveBottomValue = useMemo(() => buildStackedBottomValue(stackedData), [stackedData])
-
- const seriesRef = useLatest(visibleSeries)
- const labelsRef = useLatest(labels)
+ const resolveValue = buildSegmentResolveValue(stackedData)
+ const resolvePositionValue = buildStackedPositionValue(stackedData)
+ const resolveBottomValue = buildStackedBottomValue(stackedData)
// Bars sharing a band slot — rewrite the click payload to the series actually under the
// cursor so drop-off fillers and per-breakdown segments route correctly.
- const wrapClickData = useCallback(
- (clickData: PointClickData<Meta>, scales: ChartScales): PointClickData<Meta> => {
- const d3Scales = (scales._private as BarChartPrivate | undefined)?.__barChart
- if (!d3Scales) {
- return clickData
- }
- return (
- resolveClickedBarSeries({
- clickData,
- scales: d3Scales,
- barLayout,
- isHorizontal,
- stackedData,
- topStackedKeyByAxis,
- series: seriesRef.current,
- labels: labelsRef.current,
- }) ?? clickData
- )
- },
- [barLayout, isHorizontal, stackedData, topStackedKeyByAxis, seriesRef, labelsRef]
- )
+ const wrapClickData = (clickData: PointClickData<Meta>, scales: ChartScales): PointClickData<Meta> => {
+ const d3Scales = (scales._private as BarChartPrivate | undefined)?.__barChart
+ if (!d3Scales) {
+ return clickData
+ }
+ return (
+ resolveClickedBarSeries({
+ clickData,
+ scales: d3Scales,
+ barLayout,
+ isHorizontal,
+ stackedData,
+ topStackedKeyByAxis,
+ series: visibleSeries,
+ labels,
+ }) ?? clickData
+ )
+ }
// A capped track's blank volume gap (funnel compare) is inert: veto the hover there so the tooltip,
// pointer cursor, highlight, and click are all suppressed. Only wired when a series declares a
// `trackData` ceiling — with or without a drawn track (stacked funnel bars cap their interactive
// extent without one).
- const seriesHasTrackCeiling = useMemo(() => visibleSeries.some((s) => Array.isArray(s.trackData)), [visibleSeries])
+ const seriesHasTrackCeiling = visibleSeries.some((s) => Array.isArray(s.trackData))
- const resolveHoverIndex = useCallback(
- (index: number, cursor: { x: number; y: number }, scales: ChartScales): number => {
- const d3Scales = (scales._private as BarChartPrivate | undefined)?.__barChart
- if (!d3Scales) {
- return index
- }
- return cursorInInertTrackGap({
- series: seriesRef.current,
- label: labelsRef.current[index],
- dataIndex: index,
- scales: d3Scales,
- layout: barLayout,
- isHorizontal,
- stackedData,
- topStackedKeyByAxis,
- cursor,
- })
- ? -1
- : index
- },
- [barLayout, isHorizontal, stackedData, topStackedKeyByAxis, seriesRef, labelsRef]
- )
+ const resolveHoverIndex = (index: number, cursor: { x: number; y: number }, scales: ChartScales): number => {
+ const d3Scales = (scales._private as BarChartPrivate | undefined)?.__barChart
+ if (!d3Scales) {
+ return index
+ }
+ return cursorInInertTrackGap({
+ series: visibleSeries,
+ label: labels[index],
+ dataIndex: index,
+ scales: d3Scales,
+ layout: barLayout,
+ isHorizontal,
+ stackedData,
+ topStackedKeyByAxis,
+ cursor,
+ })
+ ? -1
+ : index
+ }
const chart = (
<Chart
diff --git a/packages/quill/packages/charts/src/charts/BarList/BarList.tsx b/packages/quill/packages/charts/src/charts/BarList/BarList.tsx
index 898bbf0d9666..2c61d4565f75 100644
--- a/packages/quill/packages/charts/src/charts/BarList/BarList.tsx
+++ b/packages/quill/packages/charts/src/charts/BarList/BarList.tsx
@@ -98,30 +98,19 @@ function BarListInner<Meta = unknown>({
[rows]
)
- const stackedConfig = useMemo<StackedBarListConfig>(
- () => ({
- labelPosition,
- rowHeight: config?.rowHeight,
- barHeight: config?.barHeight,
- barCornerRadius: config?.barCornerRadius,
- valueDomain: { min: 0, max: domainMax > 0 ? domainMax : 1 },
- tooltip: {
- enabled: config?.tooltip?.enabled,
- valueFormatter,
- labelFormatter: (key) => rows.find((row) => row.series.key === key)?.series.label ?? key,
- },
- }),
- [
- labelPosition,
- config?.rowHeight,
- config?.barHeight,
- config?.barCornerRadius,
- config?.tooltip?.enabled,
- domainMax,
+ const valueDomain = useMemo(() => ({ min: 0, max: domainMax > 0 ? domainMax : 1 }), [domainMax])
+ const stackedConfig: StackedBarListConfig = {
+ labelPosition,
+ rowHeight: config?.rowHeight,
+ barHeight: config?.barHeight,
+ barCornerRadius: config?.barCornerRadius,
+ valueDomain,
+ tooltip: {
+ enabled: config?.tooltip?.enabled,
valueFormatter,
- rows,
- ]
- )
+ labelFormatter: (key) => rows.find((row) => row.series.key === key)?.series.label ?? key,
+ },
+ }
if (rows.length === 0) {
return null
diff --git a/packages/quill/packages/charts/src/charts/BarList/StackedBarList.tsx b/packages/quill/packages/charts/src/charts/BarList/StackedBarList.tsx
index b727ac0edae9..859ec749d440 100644
--- a/packages/quill/packages/charts/src/charts/BarList/StackedBarList.tsx
+++ b/packages/quill/packages/charts/src/charts/BarList/StackedBarList.tsx
@@ -102,32 +102,29 @@ function StackedBarListInner<Meta = unknown>({
const plotTop = labelPosition === 'top' ? Math.max(0, TOP_LABEL_LINE_HEIGHT + TOP_LABEL_GAP - barOffsetInRow) : 0
// Stacked, because grouped insets each bar in its band and `barHeight` would no longer be exact.
- const barConfig = useMemo<BarChartConfig>(
- () => ({
- barLayout: 'stacked',
- axisOrientation: 'horizontal',
- hideXAxis: true,
- hideYAxis: true,
- showGrid: false,
- showAxisLines: false,
- showTickMarks: false,
- showCrosshair: false,
- margins: { top: plotTop, right: 0, bottom: 0, left: 0 },
- barCornerRadius,
- bars: {
- track: 'solid',
- // Makes each band `rowHeight` tall so it lines up with its label and value cells.
- bandPadding: Math.max(0, 1 - barHeight / rowHeight),
- minBandSize: 0,
- minBarSize: MIN_BAR_SIZE,
- roundStackEnds: true,
- valueDomain: resolvedValueDomain,
- },
- // Shows the tooltip over the track too, not only over the bar.
- tooltip: { ...tooltipConfig, enabled: tooltipConfig?.enabled !== false, hitArea: 'band' },
- }),
- [barCornerRadius, barHeight, rowHeight, plotTop, resolvedValueDomain, tooltipConfig]
- )
+ const barConfig: BarChartConfig = {
+ barLayout: 'stacked',
+ axisOrientation: 'horizontal',
+ hideXAxis: true,
+ hideYAxis: true,
+ showGrid: false,
+ showAxisLines: false,
+ showTickMarks: false,
+ showCrosshair: false,
+ margins: { top: plotTop, right: 0, bottom: 0, left: 0 },
+ barCornerRadius,
+ bars: {
+ track: 'solid',
+ // Makes each band `rowHeight` tall so it lines up with its label and value cells.
+ bandPadding: Math.max(0, 1 - barHeight / rowHeight),
+ minBandSize: 0,
+ minBarSize: MIN_BAR_SIZE,
+ roundStackEnds: true,
+ valueDomain: resolvedValueDomain,
+ },
+ // Shows the tooltip over the track too, not only over the bar.
+ tooltip: { ...tooltipConfig, enabled: tooltipConfig?.enabled !== false, hitArea: 'band' },
+ }
const chart =
labels.length > 0 ? (
diff --git a/packages/quill/packages/charts/src/charts/BoxPlot/BoxPlot.tsx b/packages/quill/packages/charts/src/charts/BoxPlot/BoxPlot.tsx
index c9c4367be719..f9e611b1fb6a 100644
--- a/packages/quill/packages/charts/src/charts/BoxPlot/BoxPlot.tsx
+++ b/packages/quill/packages/charts/src/charts/BoxPlot/BoxPlot.tsx
@@ -142,7 +142,6 @@ function BoxPlotInner<Meta = unknown>({
} = config ?? {}
const horizontal = axisOrientation === 'horizontal'
const { x: xAxisLine, y: yAxisLine } = resolveAxisLines(showAxisLines)
- const axisLines = useMemo(() => ({ x: xAxisLine, y: yAxisLine }), [xAxisLine, yAxisLine])
const adaptedSeries = useMemo<Series<BoxPlotAdaptedMeta<Meta>>[]>(
() =>
@@ -269,7 +268,7 @@ function BoxPlotInner<Meta = unknown>({
labels: drawLabels,
}
- const axisLineStyle = axisLines.x || axisLines.y
+ const axisLineStyle = xAxisLine || yAxisLine
if (showGrid) {
drawGrid(baseDrawCtx, {
gridColor: theme.gridColor,
@@ -310,12 +309,22 @@ function BoxPlotInner<Meta = unknown>({
if (axisLineStyle) {
drawAxes(baseDrawCtx, {
axisColor: resolveAxisLineColor(theme),
- xLine: axisLines.x,
- yLine: axisLines.y,
+ xLine: xAxisLine,
+ yLine: yAxisLine,
})
}
},
- [showGrid, axisLines, meanRadius, whiskerCapRatio, boxStrokeWidth, boxCornerRadius, axisOrientation, horizontal]
+ [
+ showGrid,
+ xAxisLine,
+ yAxisLine,
+ meanRadius,
+ whiskerCapRatio,
+ boxStrokeWidth,
+ boxCornerRadius,
+ axisOrientation,
+ horizontal,
+ ]
)
const drawHover = useCallback(
@@ -377,49 +386,43 @@ function BoxPlotInner<Meta = unknown>({
[series, horizontal, boxCornerRadius]
)
- const renderTooltip = useCallback(
- (ctx: TooltipContext<BoxPlotAdaptedMeta<Meta>>) => (
- <BoxPlotTooltip<Meta>
- ctx={ctx}
- userTooltip={tooltip}
- grouped={grouped}
- valueFormatter={config?.tooltip?.valueFormatter}
- />
- ),
- [tooltip, grouped, config?.tooltip?.valueFormatter]
+ const renderTooltip = (ctx: TooltipContext<BoxPlotAdaptedMeta<Meta>>): React.ReactNode => (
+ <BoxPlotTooltip<Meta>
+ ctx={ctx}
+ userTooltip={tooltip}
+ grouped={grouped}
+ valueFormatter={config?.tooltip?.valueFormatter}
+ />
)
- const onPointClick = useCallback(
- (data: PointClickData<BoxPlotAdaptedMeta<Meta>>): void => {
- if (!onBoxClick) {
- return
- }
- const primaryDatums = data.series.meta?.datums
- const datum = primaryDatums?.[data.dataIndex]
- const primarySeries = seriesByKey.get(data.series.key)
- if (!datum || !primarySeries) {
- return
- }
- const crossSeriesData: BoxPlotClickData<Meta>['crossSeriesData'] = []
- for (const entry of data.crossSeriesData) {
- const ds = entry.series.meta?.datums?.[data.dataIndex]
- const origin = seriesByKey.get(entry.series.key)
- if (!ds || !origin) {
- continue
- }
- crossSeriesData.push({ series: origin, datum: ds })
+ const onPointClick = (data: PointClickData<BoxPlotAdaptedMeta<Meta>>): void => {
+ if (!onBoxClick) {
+ return
+ }
+ const primaryDatums = data.series.meta?.datums
+ const datum = primaryDatums?.[data.dataIndex]
+ const primarySeries = seriesByKey.get(data.series.key)
+ if (!datum || !primarySeries) {
+ return
+ }
+ const crossSeriesData: BoxPlotClickData<Meta>['crossSeriesData'] = []
+ for (const entry of data.crossSeriesData) {
+ const ds = entry.series.meta?.datums?.[data.dataIndex]
+ const origin = seriesByKey.get(entry.series.key)
+ if (!ds || !origin) {
+ continue
}
- onBoxClick({
- series: primarySeries,
- seriesIndex: data.seriesIndex,
- dataIndex: data.dataIndex,
- label: data.label,
- datum,
- crossSeriesData,
- })
- },
- [onBoxClick, seriesByKey]
- )
+ crossSeriesData.push({ series: origin, datum: ds })
+ }
+ onBoxClick({
+ series: primarySeries,
+ seriesIndex: data.seriesIndex,
+ dataIndex: data.dataIndex,
+ label: data.label,
+ datum,
+ crossSeriesData,
+ })
+ }
return (
<ChartLegend {...legendProps} legendDataAttr="hog-chart-box-plot-legend">
diff --git a/packages/quill/packages/charts/src/charts/ComboChart/ComboChart.tsx b/packages/quill/packages/charts/src/charts/ComboChart/ComboChart.tsx
index cc3a0d75c438..b52be4288938 100644
--- a/packages/quill/packages/charts/src/charts/ComboChart/ComboChart.tsx
+++ b/packages/quill/packages/charts/src/charts/ComboChart/ComboChart.tsx
@@ -23,7 +23,7 @@ import {
type DrawContext,
} from '../../core/canvas-renderer'
import { Chart } from '../../core/Chart'
-import { applyChartDefaults } from '../../core/chart-config'
+import { applyChartDefaults, PERCENT_TICK_FORMATTER } from '../../core/chart-config'
import { ChartErrorBoundary } from '../../core/ChartErrorBoundary'
import { barColorAt } from '../../core/color-utils'
import { type ComboChartPrivate, createComboScales, partitionByType, resolveSeriesType } from '../../core/combo-scales'
@@ -94,7 +94,7 @@ function ComboChartInner<Meta = unknown>({
children,
}: Omit<ComboChartProps<Meta>, 'onError'>): React.ReactElement {
const theme = useResolvedChartTheme(themeProp)
- const config = useMemo(() => applyChartDefaults(rawConfig), [rawConfig])
+ const config = applyChartDefaults(rawConfig)
const {
yScaleType = 'linear',
showGrid = false,
@@ -112,7 +112,6 @@ function ComboChartInner<Meta = unknown>({
} = config ?? {}
const smooth = curve === 'monotone'
const { x: xAxisLine, y: yAxisLine } = resolveAxisLines(showAxisLines)
- const axisLines = useMemo(() => ({ x: xAxisLine, y: yAxisLine }), [xAxisLine, yAxisLine])
const seriesTypeOf = useCallback(
(s: Pick<Series, 'type'>): SeriesType => resolveSeriesType(s, defaultSeriesType),
@@ -222,7 +221,7 @@ function ComboChartInner<Meta = unknown>({
// Grid sits behind the data; the L-axis is drawn after the series (below) so neither bars
// nor lines paint over the baseline where they meet the axis.
- const axisLineStyle = axisLines.x || axisLines.y
+ const axisLineStyle = xAxisLine || yAxisLine
if (showGrid) {
// In the axis-line style only the value-axis grid guides reading; category lines
// through the band gaps are noise (line charts never draw them either).
@@ -279,16 +278,16 @@ function ComboChartInner<Meta = unknown>({
smooth,
// Rest baseline-hugging strokes on the axis line, and trim the first point's
// stroke at the y-axis, instead of straddling either axis line.
- yFloor: axisLines.x ? dimensions.plotTop + dimensions.plotHeight - LINE_STROKE_WIDTH / 2 : undefined,
- clipLeftEdge: axisLines.y,
+ yFloor: xAxisLine ? dimensions.plotTop + dimensions.plotHeight - LINE_STROKE_WIDTH / 2 : undefined,
+ clipLeftEdge: yAxisLine,
})
if (axisLineStyle) {
const hasRightAxis = Object.values(comboScales.yAxes).some((axis) => axis.position === 'right')
drawAxes(baseDrawCtx, {
axisColor: resolveAxisLineColor(theme),
- xLine: axisLines.x,
- yLine: axisLines.y,
+ xLine: xAxisLine,
+ yLine: yAxisLine,
rightAxis: hasRightAxis,
})
}
@@ -296,7 +295,8 @@ function ComboChartInner<Meta = unknown>({
[
seriesTypeOf,
showGrid,
- axisLines,
+ xAxisLine,
+ yAxisLine,
xTickFormatter,
barLayout,
barStackedData,
@@ -399,22 +399,17 @@ function ComboChartInner<Meta = unknown>({
// Bar segments report their own value; lines report raw. buildSegmentResolveValue's fallback
// handles non-bar series automatically (they aren't in barStackedData), so the bar-only stack
// still yields correct line values.
- const resolveValue = useMemo(() => buildSegmentResolveValue(barStackedData), [barStackedData])
- const resolvePositionValue = useMemo(() => buildStackedPositionValue(barStackedData), [barStackedData])
- const resolveBottomValue = useMemo(() => buildStackedBottomValue(barStackedData), [barStackedData])
+ const resolveValue = buildSegmentResolveValue(barStackedData)
+ const resolvePositionValue = buildStackedPositionValue(barStackedData)
+ const resolveBottomValue = buildStackedBottomValue(barStackedData)
// Mirrors BarChart: flag the axis context as percent (drives ValueLabels' 0-1 fraction
// handling) and default the y-tick formatter to a percentage unless the caller overrides it.
- const chartConfig = useMemo<ComboChartConfig>(() => {
- const base = { ...config, isPercent: barLayout === 'percent' }
- if (barLayout !== 'percent' || config?.yTickFormatter) {
- return base
- }
- return {
- ...base,
- yTickFormatter: (v: number) => `${Math.round(v * 100)}%`,
- }
- }, [config, barLayout])
+ const chartConfig: ComboChartConfig = {
+ ...config,
+ isPercent: barLayout === 'percent',
+ yTickFormatter: config?.yTickFormatter ?? (barLayout === 'percent' ? PERCENT_TICK_FORMATTER : undefined),
+ }
return (
<Chart
diff --git a/packages/quill/packages/charts/src/charts/FunnelChart/FunnelChart.tsx b/packages/quill/packages/charts/src/charts/FunnelChart/FunnelChart.tsx
index 4da4b6e1630f..b487d01a7f10 100644
--- a/packages/quill/packages/charts/src/charts/FunnelChart/FunnelChart.tsx
+++ b/packages/quill/packages/charts/src/charts/FunnelChart/FunnelChart.tsx
@@ -235,60 +235,38 @@ export function FunnelChart<Meta = unknown>({
const bandLabels = useMemo(() => steps.map((_, stepIndex) => `${stepIndex + 1}`), [steps])
const stepLabelFromBand = useCallback((band: string): string => steps[Number(band) - 1] ?? band, [steps])
- const barConfig = useMemo<BarChartConfig>(
- () => ({
- barLayout: 'grouped',
- showGrid,
- animateHover,
- margins,
- hideXAxis: hideStepLabels || hasStepFooter,
- hideYAxis: hideValueAxis,
- maxCategoryLabelWidth,
- xTickFormatter: stepLabelFromBand,
- yTickFormatter: formatPercentTick,
- barCornerRadius,
- legend,
- tooltip: {
- placement: 'top',
- valueFormatter: formatPercent,
- labelFormatter: stepLabelFromBand,
- ...tooltipConfig,
- },
- bars: {
- track: true,
- shadow: FUNNEL_BAR_SHADOW,
- bandPadding: bandPadding ?? FUNNEL_BAND_PADDING,
- minBarSize: minBarSize ?? FUNNEL_MIN_BAR_SIZE,
- minBarSizeScope: 'hover',
- maxBandRange,
- },
- }),
- [
- showGrid,
- animateHover,
- margins,
- hideStepLabels,
- hasStepFooter,
- hideValueAxis,
- maxCategoryLabelWidth,
- stepLabelFromBand,
- legend,
- tooltipConfig,
- barCornerRadius,
- bandPadding,
- minBarSize,
+ const barConfig: BarChartConfig = {
+ barLayout: 'grouped',
+ showGrid,
+ animateHover,
+ margins,
+ hideXAxis: hideStepLabels || hasStepFooter,
+ hideYAxis: hideValueAxis,
+ maxCategoryLabelWidth,
+ xTickFormatter: stepLabelFromBand,
+ yTickFormatter: formatPercentTick,
+ barCornerRadius,
+ legend,
+ tooltip: {
+ placement: 'top',
+ valueFormatter: formatPercent,
+ labelFormatter: stepLabelFromBand,
+ ...tooltipConfig,
+ },
+ bars: {
+ track: true,
+ shadow: FUNNEL_BAR_SHADOW,
+ bandPadding: bandPadding ?? FUNNEL_BAND_PADDING,
+ minBarSize: minBarSize ?? FUNNEL_MIN_BAR_SIZE,
+ minBarSizeScope: 'hover',
maxBandRange,
- ]
- )
+ },
+ }
- const handlePointClick = useMemo(
- () =>
- onStepClick
- ? (data: PointClickData<Meta>): void =>
- onStepClick({ ...data, stepIndex: data.dataIndex, converted: !data.inTrackArea })
- : undefined,
- [onStepClick]
- )
+ const handlePointClick = onStepClick
+ ? (data: PointClickData<Meta>): void =>
+ onStepClick({ ...data, stepIndex: data.dataIndex, converted: !data.inTrackArea })
+ : undefined
const [bands, setBands] = useState<StepBand[] | null>(null)
diff --git a/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.tsx b/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.tsx
index b75c988d3d8b..b238fbaa1bd9 100644
--- a/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.tsx
+++ b/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.tsx
@@ -169,6 +169,88 @@ export interface HeatmapProps {
onError?: (error: Error, info: React.ErrorInfo) => void
}
+function drawStatic({ ctx, scales }: ChartDrawArgs): void {
+ const priv = (scales._private as HeatmapPrivate | undefined)?.__heatmap
+ if (!priv) {
+ return
+ }
+ const { layout, cells: drawCells, accent: drawAccent, maxValue: max, colorScale: scale } = priv
+ drawColumnHighlights(ctx, layout, priv.highlightedColumns, drawAccent)
+ // One ramp per accent in play, because parsing the accent per cell is the expensive part.
+ const ramps = new Map<string, (t: number) => string>()
+ const rampFor = (color: string): ((t: number) => string) => {
+ let ramp = ramps.get(color)
+ if (!ramp) {
+ ramp = createCellColorRamp(color)
+ ramps.set(color, ramp)
+ }
+ return ramp
+ }
+ // A 1px gutter keeps cells readable as discrete buckets; collapse it when cells are so
+ // small the gap would dominate the fill.
+ const gap = layout.colWidth > 3 && layout.rowHeight > 3 ? 1 : 0
+ for (let r = 0; r < layout.rows; r++) {
+ const row = drawCells[r]
+ if (!row) {
+ continue
+ }
+ for (let c = 0; c < layout.cols; c++) {
+ const style = priv.styles[r]?.[c]
+ const rect = cellRect(layout, c, r)
+ if (style?.outlined) {
+ drawOutlinedCell(ctx, rect, gap, drawAccent)
+ continue
+ }
+ const value = row[c]
+ if (!(value > 0) && !style?.filled) {
+ continue
+ }
+ ctx.fillStyle = rampFor(style?.color ?? drawAccent)(normalizeCount(value, max, scale))
+ ctx.fillRect(rect.x + gap / 2, rect.y + gap / 2, rect.width - gap, rect.height - gap)
+ }
+ }
+}
+
+function drawHover({ ctx, scales, hoverIndex, hoverPosition, hoverProgress }: ChartDrawArgs): boolean {
+ const priv = (scales._private as HeatmapPrivate | undefined)?.__heatmap
+ if (!priv || hoverIndex < 0 || !hoverPosition) {
+ return false
+ }
+ const row = rowAtY(priv.layout, hoverPosition.y)
+ if (row < 0) {
+ return false
+ }
+ const rect = cellRect(priv.layout, hoverIndex, row)
+ ctx.save()
+ ctx.globalAlpha = hoverProgress
+ ctx.strokeStyle = priv.accent
+ ctx.lineWidth = 1.5
+ ctx.strokeRect(rect.x + 0.75, rect.y + 0.75, rect.width - 1.5, rect.height - 1.5)
+ ctx.restore()
+ return true
+}
+
+// Each row's tooltip anchor spans its cell exactly (top edge → bottom edge), so
+// `findClosestSeriesKey`'s containment pass resolves the hovered cell.
+const resolvePositionValue: ResolveValueFn = (series) =>
+ ((series.meta as HeatmapRowMeta | undefined)?.rowIndex ?? 0) + 1
+const resolveBottomValue: ResolveValueFn = (series) => (series.meta as HeatmapRowMeta | undefined)?.rowIndex ?? 0
+
+// Rewrite clicks to the row under the cursor — the base chart's click payload carries the
+// first series at the column, which is meaningless for a grid.
+function wrapClickData(data: PointClickData<HeatmapRowMeta>, scales: ChartScales): PointClickData<HeatmapRowMeta> {
+ const priv = (scales._private as HeatmapPrivate | undefined)?.__heatmap
+ if (!priv || !data.cursor) {
+ return data
+ }
+ const row = rowAtY(priv.layout, data.cursor.y)
+ const match = data.crossSeriesData.find((entry) => entry.series.meta?.rowIndex === row)
+ if (row < 0 || !match) {
+ return data
+ }
+ return { ...data, series: match.series, seriesIndex: row, value: match.value }
+}
+
export function Heatmap({ onError, ...rest }: HeatmapProps): React.ReactElement {
return (
<ChartErrorBoundary onError={onError}>
@@ -288,148 +370,49 @@ function HeatmapInner({
[yLabels, grid, accent, maxValue, colorScale, styles, highlightedColumns]
)
- const drawStatic = useCallback(({ ctx, scales }: ChartDrawArgs) => {
+ // Map the core's label-range + y-pixel-span brush payload onto grid indices.
+ const handleAreaSelect = (data: AreaSelectData, scales: ChartScales): void => {
const priv = (scales._private as HeatmapPrivate | undefined)?.__heatmap
- if (!priv) {
+ if (!priv || !onBrush) {
return
}
- const { layout, cells: drawCells, accent: drawAccent, maxValue: max, colorScale: scale } = priv
- drawColumnHighlights(ctx, layout, priv.highlightedColumns, drawAccent)
- // One ramp per accent in play, because parsing the accent per cell is the expensive part.
- const ramps = new Map<string, (t: number) => string>()
- const rampFor = (color: string): ((t: number) => string) => {
- let ramp = ramps.get(color)
- if (!ramp) {
- ramp = createCellColorRamp(color)
- ramps.set(color, ramp)
- }
- return ramp
+ const { layout } = priv
+ if (layout.rows === 0) {
+ return
}
- // A 1px gutter keeps cells readable as discrete buckets; collapse it when cells are so
- // small the gap would dominate the fill.
- const gap = layout.colWidth > 3 && layout.rowHeight > 3 ? 1 : 0
- for (let r = 0; r < layout.rows; r++) {
- const row = drawCells[r]
- if (!row) {
- continue
- }
- for (let c = 0; c < layout.cols; c++) {
- const style = priv.styles[r]?.[c]
- const rect = cellRect(layout, c, r)
- if (style?.outlined) {
- drawOutlinedCell(ctx, rect, gap, drawAccent)
- continue
- }
- const value = row[c]
- if (!(value > 0) && !style?.filled) {
- continue
- }
- ctx.fillStyle = rampFor(style?.color ?? drawAccent)(normalizeCount(value, max, scale))
- ctx.fillRect(rect.x + gap / 2, rect.y + gap / 2, rect.width - gap, rect.height - gap)
- }
+ let startRow = 0
+ let endRow = layout.rows - 1
+ if (Math.abs(data.yPixel1 - data.yPixel0) >= FULL_HEIGHT_MIN_Y_DRAG_PX) {
+ // yPixel0 is the top of the drag → the higher row index (rows count bottom-up).
+ // Shrink the span half a pixel on each edge before snapping to rows: an edge landing
+ // exactly on a row boundary otherwise floors into the neighbouring row and reports a
+ // row the rect only touches. The FULL_HEIGHT_MIN_Y_DRAG_PX guard keeps the span far
+ // thicker than the nudge, so it can't invert.
+ const top = rowAtYClamped(layout, data.yPixel0 + BRUSH_EDGE_EPSILON_PX)
+ const bottom = rowAtYClamped(layout, data.yPixel1 - BRUSH_EDGE_EPSILON_PX)
+ startRow = Math.min(top, bottom)
+ endRow = Math.max(top, bottom)
}
- }, [])
-
- const drawHover = useCallback(
- ({ ctx, scales, hoverIndex, hoverPosition, hoverProgress }: ChartDrawArgs): boolean => {
- const priv = (scales._private as HeatmapPrivate | undefined)?.__heatmap
- if (!priv || hoverIndex < 0 || !hoverPosition) {
- return false
- }
- const row = rowAtY(priv.layout, hoverPosition.y)
- if (row < 0) {
- return false
- }
- const rect = cellRect(priv.layout, hoverIndex, row)
- ctx.save()
- ctx.globalAlpha = hoverProgress
- ctx.strokeStyle = priv.accent
- ctx.lineWidth = 1.5
- ctx.strokeRect(rect.x + 0.75, rect.y + 0.75, rect.width - 1.5, rect.height - 1.5)
- ctx.restore()
- return true
- },
- []
- )
-
- // Each row's tooltip anchor spans its cell exactly (top edge → bottom edge), so
- // `findClosestSeriesKey`'s containment pass resolves the hovered cell.
- const resolvePositionValue: ResolveValueFn = useCallback(
- (series) => ((series.meta as HeatmapRowMeta | undefined)?.rowIndex ?? 0) + 1,
- []
- )
- const resolveBottomValue: ResolveValueFn = useCallback(
- (series) => (series.meta as HeatmapRowMeta | undefined)?.rowIndex ?? 0,
- []
- )
-
- // Rewrite clicks to the row under the cursor — the base chart's click payload carries the
- // first series at the column, which is meaningless for a grid.
- const wrapClickData = useCallback(
- (data: PointClickData<HeatmapRowMeta>, scales: ChartScales): PointClickData<HeatmapRowMeta> => {
- const priv = (scales._private as HeatmapPrivate | undefined)?.__heatmap
- if (!priv || !data.cursor) {
- return data
- }
- const row = rowAtY(priv.layout, data.cursor.y)
- const match = data.crossSeriesData.find((entry) => entry.series.meta?.rowIndex === row)
- if (row < 0 || !match) {
- return data
- }
- return { ...data, series: match.series, seriesIndex: row, value: match.value }
- },
- []
- )
-
- // Map the core's label-range + y-pixel-span brush payload onto grid indices.
- const handleAreaSelect = useCallback(
- (data: AreaSelectData, scales: ChartScales): void => {
- const priv = (scales._private as HeatmapPrivate | undefined)?.__heatmap
- if (!priv || !onBrush) {
- return
- }
- const { layout } = priv
- if (layout.rows === 0) {
- return
- }
- let startRow = 0
- let endRow = layout.rows - 1
- if (Math.abs(data.yPixel1 - data.yPixel0) >= FULL_HEIGHT_MIN_Y_DRAG_PX) {
- // yPixel0 is the top of the drag → the higher row index (rows count bottom-up).
- // Shrink the span half a pixel on each edge before snapping to rows: an edge landing
- // exactly on a row boundary otherwise floors into the neighbouring row and reports a
- // row the rect only touches. The FULL_HEIGHT_MIN_Y_DRAG_PX guard keeps the span far
- // thicker than the nudge, so it can't invert.
- const top = rowAtYClamped(layout, data.yPixel0 + BRUSH_EDGE_EPSILON_PX)
- const bottom = rowAtYClamped(layout, data.yPixel1 - BRUSH_EDGE_EPSILON_PX)
- startRow = Math.min(top, bottom)
- endRow = Math.max(top, bottom)
- }
- onBrush({
- x: { startIndex: data.startIndex, endIndex: data.endIndex },
- y: { startIndex: startRow, endIndex: endRow },
- })
- },
- [onBrush]
- )
+ onBrush({
+ x: { startIndex: data.startIndex, endIndex: data.endIndex },
+ y: { startIndex: startRow, endIndex: endRow },
+ })
+ }
- const handlePointClick = useCallback(
- (data: PointClickData<HeatmapRowMeta>): void => {
- const rowIndex = data.series.meta?.rowIndex
- if (rowIndex == null || !onCellClick) {
- return
- }
- onCellClick({
- xIndex: data.dataIndex,
- yIndex: rowIndex,
- // `data.label` is the per-column key, not the display label — map back by index.
- xLabel: xLabels[data.dataIndex] ?? '',
- yLabel: yLabels[rowIndex] ?? '',
- value: data.value,
- })
- },
- [onCellClick, xLabels, yLabels]
- )
+ const handlePointClick = (data: PointClickData<HeatmapRowMeta>): void => {
+ const rowIndex = data.series.meta?.rowIndex
+ if (rowIndex == null || !onCellClick) {
+ return
+ }
+ onCellClick({
+ xIndex: data.dataIndex,
+ yIndex: rowIndex,
+ // `data.label` is the per-column key, not the display label — map back by index.
+ xLabel: xLabels[data.dataIndex] ?? '',
+ yLabel: yLabels[rowIndex] ?? '',
+ value: data.value,
+ })
+ }
const userXTickFormatter = config?.xTickFormatter
const xTickFormatter = useCallback(
@@ -443,62 +426,44 @@ function HeatmapInner({
const tooltipLabelFormatter = config?.tooltip?.labelFormatter
const tooltipValueFormatter = config?.tooltip?.valueFormatter
const captureTooltip = useTooltipCapture<HeatmapRowMeta>()
- const renderTooltip = useMemo(
- () =>
- (ctx: HeatmapTooltipContext): React.ReactNode => {
- // The base chart's `ctx.label` is the per-column key; restore the display label
- // before it reaches either the custom or default tooltip.
- const mapped = { ...ctx, label: resolveColumnLabel(ctx.label) }
- captureTooltip(mapped)
- if (tooltip) {
- return tooltip(mapped)
- }
- // Narrow to the single hovered cell — rows carry their cell's exact pixel range
- // (yPixel/yPixelBottom), so containment resolves it — and let DefaultTooltip
- // render that one row rather than maintaining a bespoke tooltip surface.
- const key = mapped.hoverPosition
- ? findClosestSeriesKey(mapped.seriesData, mapped.hoverPosition.y)
- : null
- const entry = mapped.seriesData.find((s) => s.series.key === key)
- if (!entry) {
- return null
- }
- return (
- <DefaultTooltip
- {...mapped}
- seriesData={[entry]}
- labelFormatter={tooltipLabelFormatter}
- valueFormatter={tooltipValueFormatter}
- />
- )
- },
- [tooltip, resolveColumnLabel, tooltipLabelFormatter, tooltipValueFormatter, captureTooltip]
- )
+ const renderTooltip = (ctx: HeatmapTooltipContext): React.ReactNode => {
+ // The base chart's `ctx.label` is the per-column key; restore the display label
+ // before it reaches either the custom or default tooltip.
+ const mapped = { ...ctx, label: resolveColumnLabel(ctx.label) }
+ captureTooltip(mapped)
+ if (tooltip) {
+ return tooltip(mapped)
+ }
+ // Narrow to the single hovered cell — rows carry their cell's exact pixel range
+ // (yPixel/yPixelBottom), so containment resolves it — and let DefaultTooltip
+ // render that one row rather than maintaining a bespoke tooltip surface.
+ const key = mapped.hoverPosition ? findClosestSeriesKey(mapped.seriesData, mapped.hoverPosition.y) : null
+ const entry = mapped.seriesData.find((s) => s.series.key === key)
+ if (!entry) {
+ return null
+ }
+ return (
+ <DefaultTooltip
+ {...mapped}
+ seriesData={[entry]}
+ labelFormatter={tooltipLabelFormatter}
+ valueFormatter={tooltipValueFormatter}
+ />
+ )
+ }
- const baseConfig = useMemo<ChartConfig>(
- () => ({
- xTickFormatter,
- yTickFormatter,
- xAxisLabel: config?.xAxisLabel,
- yAxisLabel: config?.yAxisLabel,
- hideXAxis: config?.hideXAxis,
- hideYAxis: config?.hideYAxis,
- margins: config?.margins,
- // 'cursor' placement: a follow-data anchor would pin the tooltip to the column top,
- // far from the hovered cell in a tall grid.
- tooltip: { enabled: config?.tooltip?.enabled, placement: 'cursor' },
- }),
- [
- xTickFormatter,
- yTickFormatter,
- config?.xAxisLabel,
- config?.yAxisLabel,
- config?.hideXAxis,
- config?.hideYAxis,
- config?.margins,
- config?.tooltip?.enabled,
- ]
- )
+ const baseConfig: ChartConfig = {
+ xTickFormatter,
+ yTickFormatter,
+ xAxisLabel: config?.xAxisLabel,
+ yAxisLabel: config?.yAxisLabel,
+ hideXAxis: config?.hideXAxis,
+ hideYAxis: config?.hideYAxis,
+ margins: config?.margins,
+ // 'cursor' placement: a follow-data anchor would pin the tooltip to the column top,
+ // far from the hovered cell in a tall grid.
+ tooltip: { enabled: config?.tooltip?.enabled, placement: 'cursor' },
+ }
return (
<Chart<HeatmapRowMeta>
diff --git a/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx b/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx
index f26e6d19bd4b..2f8791f15cce 100644
--- a/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx
+++ b/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx
@@ -12,7 +12,7 @@ import {
} from '../../core/canvas-renderer'
import type { DrawContext } from '../../core/canvas-renderer'
import { Chart } from '../../core/Chart'
-import { applyChartDefaults } from '../../core/chart-config'
+import { applyChartDefaults, PERCENT_TICK_FORMATTER } from '../../core/chart-config'
import { ChartErrorBoundary } from '../../core/ChartErrorBoundary'
import {
buildSegmentResolveValue,
@@ -89,7 +89,7 @@ function LineChartInner<Meta = unknown>({
children,
}: LineChartProps<Meta>): React.ReactElement {
const theme = useResolvedChartTheme(themeProp)
- const config = useMemo(() => applyChartDefaults(rawConfig), [rawConfig])
+ const config = applyChartDefaults(rawConfig)
const {
yScaleType = 'linear',
percentStackView = false,
@@ -105,14 +105,10 @@ function LineChartInner<Meta = unknown>({
const smooth = curve === 'monotone'
// Resolve to primitives so an inline `{ x, y }` config object can't churn the draw callbacks.
const { x: xAxisLine, y: yAxisLine } = resolveAxisLines(showAxisLines)
- const axisLines = useMemo(() => ({ x: xAxisLine, y: yAxisLine }), [xAxisLine, yAxisLine])
const { visibleSeries, legendProps } = useChartLegend(series, theme, config?.legend)
- const hasMultipleFilledSeries = useMemo(() => {
- const filledSeries = visibleSeries.filter((s) => s.fill && !s.fill.lowerData)
- return filledSeries.length >= 2
- }, [visibleSeries])
+ const hasMultipleFilledSeries = visibleSeries.filter((s) => s.fill && !s.fill.lowerData).length >= 2
const stackedData = useMemo((): Map<string, StackedBand> | undefined => {
if (percentStackView) {
@@ -127,16 +123,11 @@ function LineChartInner<Meta = unknown>({
return undefined
}, [percentStackView, hasMultipleFilledSeries, visibleSeries, labels])
- const chartConfig = useMemo(() => {
- const base = { ...config, isPercent: percentStackView }
- if (!percentStackView || config?.yTickFormatter) {
- return base
- }
- return {
- ...base,
- yTickFormatter: (v: number) => `${Math.round(v * 100)}%`,
- }
- }, [config, percentStackView])
+ const chartConfig = {
+ ...config,
+ isPercent: percentStackView,
+ yTickFormatter: config?.yTickFormatter ?? (percentStackView ? PERCENT_TICK_FORMATTER : undefined),
+ }
const createScales: CreateScalesFn = useCallback(
(coloredSeries: ResolvedSeries[], scaleLabels: string[], dimensions: ChartDimensions): ChartScales => {
@@ -202,7 +193,7 @@ function LineChartInner<Meta = unknown>({
// Grid sits behind the data; the L-axis is drawn after the series (below) so the line
// doesn't paint over the baseline where it meets the axis.
- const axisLineStyle = axisLines.x || axisLines.y
+ const axisLineStyle = xAxisLine || yAxisLine
if (showGrid) {
drawGrid(baseDrawCtx, {
gridColor: theme.gridColor,
@@ -227,8 +218,8 @@ function LineChartInner<Meta = unknown>({
smooth,
// Rest baseline-hugging strokes on the axis line, and trim the first point's
// stroke at the y-axis, instead of straddling either axis line.
- yFloor: axisLines.x ? dimensions.plotTop + dimensions.plotHeight - LINE_STROKE_WIDTH / 2 : undefined,
- clipLeftEdge: axisLines.y,
+ yFloor: xAxisLine ? dimensions.plotTop + dimensions.plotHeight - LINE_STROKE_WIDTH / 2 : undefined,
+ clipLeftEdge: yAxisLine,
connectNulls,
})
@@ -236,13 +227,13 @@ function LineChartInner<Meta = unknown>({
const hasRightAxis = Object.values(d3Scales.yAxes ?? {}).some((axis) => axis.position === 'right')
drawAxes(baseDrawCtx, {
axisColor: resolveAxisLineColor(theme),
- xLine: axisLines.x,
- yLine: axisLines.y,
+ xLine: xAxisLine,
+ yLine: yAxisLine,
rightAxis: hasRightAxis,
})
}
},
- [showGrid, axisLines, stackedData, smooth, connectNulls]
+ [showGrid, xAxisLine, yAxisLine, stackedData, smooth, connectNulls]
)
const drawHover = useCallback(
@@ -292,8 +283,8 @@ function LineChartInner<Meta = unknown>({
// Stacked/percent-stacked areas: display each series's own segment value (resolveValue)
// but anchor the tooltip/value labels at the stacked top (resolvePositionValue).
- const resolveValue = useMemo(() => buildSegmentResolveValue(stackedData), [stackedData])
- const resolvePositionValue = useMemo(() => buildStackedPositionValue(stackedData), [stackedData])
+ const resolveValue = buildSegmentResolveValue(stackedData)
+ const resolvePositionValue = buildStackedPositionValue(stackedData)
return (
<ChartLegend {...legendProps} legendDataAttr="hog-chart-line-legend">
diff --git a/packages/quill/packages/charts/src/charts/PieChart/PieChart.tsx b/packages/quill/packages/charts/src/charts/PieChart/PieChart.tsx
index 414046fa7379..aa650867ef82 100644
--- a/packages/quill/packages/charts/src/charts/PieChart/PieChart.tsx
+++ b/packages/quill/packages/charts/src/charts/PieChart/PieChart.tsx
@@ -1,4 +1,4 @@
-import React, { useCallback, useMemo, useRef } from 'react'
+import React, { useCallback, useRef } from 'react'
import { ChartLegend } from '../../components/Legend/ChartLegend'
import { useChartLegend } from '../../components/Legend/useChartLegend'
@@ -191,14 +191,6 @@ function PieChartInner<Meta = unknown>({
// drawHover for why it can't be read straight off hoverProgress.
const dimRef = useRef(0)
- const drawStatic = useCallback((args: ChartDrawArgs) => {
- const layout = getLayoutFromArgs<Meta>(args)
- if (!layout) {
- return
- }
- drawSlices(args.ctx, layout, { outerRadiusBoost: 0 })
- }, [])
-
const drawHover = useCallback(
(args: ChartDrawArgs): boolean => {
const layout = getLayoutFromArgs<Meta>(args)
@@ -240,24 +232,20 @@ function PieChartInner<Meta = unknown>({
[effectiveHoverGrowth]
)
- const renderTooltip = useMemo(
- () =>
- tooltip ??
- ((ctx: TooltipContext<Meta>): React.ReactNode => (
- <PieTooltip ctx={ctx} valueFormatter={valueFormatter} isPercent={isPercent} />
- )),
- [tooltip, valueFormatter, isPercent]
- )
-
return (
<ChartLegend {...legendProps} legendDataAttr="hog-chart-pie-legend">
<RadialChart<Meta>
series={visibleSeries}
theme={theme}
buildLayout={buildLayout}
- drawStatic={drawStatic}
+ drawStatic={drawPieStatic}
drawHover={drawHover}
- tooltip={renderTooltip}
+ tooltip={
+ tooltip ??
+ ((ctx: TooltipContext<Meta>): React.ReactNode => (
+ <PieTooltip ctx={ctx} valueFormatter={valueFormatter} isPercent={isPercent} />
+ ))
+ }
showTooltip={showTooltip}
onSliceClick={onSliceClick}
hitOuterSlack={effectiveHoverGrowth}
@@ -298,6 +286,14 @@ function getLayoutFromArgs<Meta>(args: ChartDrawArgs): PieLayout<Meta> | null {
return priv?.__radialChart?.layout ?? null
}
+function drawPieStatic(args: ChartDrawArgs): void {
+ const layout = getLayoutFromArgs(args)
+ if (!layout) {
+ return
+ }
+ drawSlices(args.ctx, layout, { outerRadiusBoost: 0 })
+}
+
interface DrawSlicesOptions {
outerRadiusBoost: number
}
diff --git a/packages/quill/packages/charts/src/charts/ProportionBar/ProportionBar.tsx b/packages/quill/packages/charts/src/charts/ProportionBar/ProportionBar.tsx
index fb25e9a2e4c9..50e37624ff3c 100644
--- a/packages/quill/packages/charts/src/charts/ProportionBar/ProportionBar.tsx
+++ b/packages/quill/packages/charts/src/charts/ProportionBar/ProportionBar.tsx
@@ -1,4 +1,4 @@
-import React, { useCallback, useMemo } from 'react'
+import React, { useMemo } from 'react'
import { ChartLegend } from '../../components/Legend/ChartLegend'
import { useChartLegend } from '../../components/Legend/useChartLegend'
@@ -88,18 +88,15 @@ function ProportionBarInner<Meta = unknown>({
tooltip: tooltipConfig,
} = config ?? {}
- const legendConfig = useMemo<ChartLegendConfig>(
- () => ({ show: true, position: 'bottom', align: 'start', ...legend }),
- [legend]
- )
+ const legendConfig: ChartLegendConfig = { show: true, position: 'bottom', align: 'start', ...legend }
const { visibleSeries, legendProps } = useChartLegend(series, theme, legendConfig)
const legendItems = useMemo(
() => proportionLegendItems(series, theme, valueFormatter, legendProps.hiddenKeys),
[series, theme, valueFormatter, legendProps.hiddenKeys]
)
- const colorByKey = useMemo(() => new Map(legendItems.map((item) => [item.key, item.color])), [legendItems])
+ const colorByKey = new Map(legendItems.map((item) => [item.key, item.color]))
// Tooltips and clicks hand back the consumer's own series, not the single-value copies the bar draws.
- const seriesByKey = useMemo(() => new Map(series.map((s) => [s.key, s])), [series])
+ const seriesByKey = new Map(series.map((s) => [s.key, s]))
// Only the fields the bar needs to draw and identify a part. Carrying the rest of `s` through
// (yAxisId, overlay, fill.lowerData, per-bar `bars` overrides) would let it change how the part
@@ -116,82 +113,67 @@ function ProportionBarInner<Meta = unknown>({
})),
[visibleSeries]
)
- const valueByKey = useMemo(() => new Map(barSeries.map((s) => [s.key, s.data[0]])), [barSeries])
- const visibleTotal = useMemo(
- () => barSeries.reduce((acc, s) => (s.visibility?.excluded ? acc : acc + s.data[0]), 0),
- [barSeries]
- )
+ const valueByKey = new Map(barSeries.map((s) => [s.key, s.data[0]]))
+ const visibleTotal = barSeries.reduce((acc, s) => (s.visibility?.excluded ? acc : acc + s.data[0]), 0)
// As on PieChart, a slice index counts only the drawn parts, so a hidden part does not shift it.
- const drawnKeys = useMemo(() => barSeries.filter((s) => !s.visibility?.excluded).map((s) => s.key), [barSeries])
- const fractionOf = useCallback(
- (value: number): number => (visibleTotal > 0 ? value / visibleTotal : 0),
- [visibleTotal]
- )
+ const drawnKeys = barSeries.filter((s) => !s.visibility?.excluded).map((s) => s.key)
+ const fractionOf = (value: number): number => (visibleTotal > 0 ? value / visibleTotal : 0)
// BarChart layers the library's default axes, grid and margins under any config, so opt out of
// each one to leave only the bar.
- const barConfig = useMemo<BarChartConfig>(
- () => ({
- barLayout: 'percent',
- axisOrientation: 'horizontal',
- hideXAxis: true,
- hideYAxis: true,
- showGrid: false,
- showAxisLines: false,
- showTickMarks: false,
- showCrosshair: false,
- margins: { top: 0, right: 0, bottom: 0, left: 0 },
- barCornerRadius,
- bars: { bandPadding: 0, minBandSize: 0, roundStackEnds: true },
- tooltip: { enabled: tooltipConfig?.enabled !== false },
- }),
- [barCornerRadius, tooltipConfig?.enabled]
- )
+ const barConfig: BarChartConfig = {
+ barLayout: 'percent',
+ axisOrientation: 'horizontal',
+ hideXAxis: true,
+ hideYAxis: true,
+ showGrid: false,
+ showAxisLines: false,
+ showTickMarks: false,
+ showCrosshair: false,
+ margins: { top: 0, right: 0, bottom: 0, left: 0 },
+ barCornerRadius,
+ bars: { bandPadding: 0, minBandSize: 0, roundStackEnds: true },
+ tooltip: { enabled: tooltipConfig?.enabled !== false },
+ }
// A percent layout hands the tooltip every segment as a 0..1 fraction. Narrow it to the hovered
// part with its raw value, which is the context a PieChart tooltip receives. Reads the value
// already computed for `barSeries` instead of rescanning the part's data on every hover.
const captureTooltip = useTooltipCapture<Meta>()
- const renderTooltip = useCallback(
- (ctx: TooltipContext<Meta>): React.ReactNode => {
- const entry = ctx.seriesData.find((d) => d.series.key === ctx.hoveredSeriesKey)
- if (!entry) {
- return null
- }
- const original = seriesByKey.get(entry.series.key) ?? entry.series
- const part = { ...original, color: colorByKey.get(original.key) ?? entry.color }
- const value = valueByKey.get(entry.series.key) ?? 0
- const partCtx = {
- ...ctx,
- label: part.label,
- dataIndex: series.indexOf(original),
- seriesData: [{ ...entry, series: part, value, fraction: fractionOf(value) }],
- }
- captureTooltip(partCtx)
- return tooltip ? tooltip(partCtx) : <PieTooltip ctx={partCtx} valueFormatter={valueFormatter} />
- },
- [tooltip, series, seriesByKey, colorByKey, valueByKey, fractionOf, valueFormatter, captureTooltip]
- )
+ const renderTooltip = (ctx: TooltipContext<Meta>): React.ReactNode => {
+ const entry = ctx.seriesData.find((d) => d.series.key === ctx.hoveredSeriesKey)
+ if (!entry) {
+ return null
+ }
+ const original = seriesByKey.get(entry.series.key) ?? entry.series
+ const part = { ...original, color: colorByKey.get(original.key) ?? entry.color }
+ const value = valueByKey.get(entry.series.key) ?? 0
+ const partCtx = {
+ ...ctx,
+ label: part.label,
+ dataIndex: series.indexOf(original),
+ seriesData: [{ ...entry, series: part, value, fraction: fractionOf(value) }],
+ }
+ captureTooltip(partCtx)
+ return tooltip ? tooltip(partCtx) : <PieTooltip ctx={partCtx} valueFormatter={valueFormatter} />
+ }
- const handlePointClick = useCallback(
- ({ series: clicked }: PointClickData<Meta>): void => {
- const part = seriesByKey.get(clicked.key)
- const sliceIndex = drawnKeys.indexOf(clicked.key)
- const value = valueByKey.get(clicked.key) ?? 0
- // A part with no visible width (value 0, or the whole bar empty) draws nothing. `PieChart`
- // draws no slice and fires no click for it, so match that here.
- if (!onSliceClick || !part || sliceIndex < 0 || visibleTotal <= 0 || value <= 0) {
- return
- }
- onSliceClick({
- sliceIndex,
- series: { ...part, color: colorByKey.get(part.key) ?? '' },
- value,
- fraction: fractionOf(value),
- })
- },
- [seriesByKey, drawnKeys, valueByKey, visibleTotal, onSliceClick, colorByKey, fractionOf]
- )
+ const handlePointClick = ({ series: clicked }: PointClickData<Meta>): void => {
+ const part = seriesByKey.get(clicked.key)
+ const sliceIndex = drawnKeys.indexOf(clicked.key)
+ const value = valueByKey.get(clicked.key) ?? 0
+ // A part with no visible width (value 0, or the whole bar empty) draws nothing. `PieChart`
+ // draws no slice and fires no click for it, so match that here.
+ if (!onSliceClick || !part || sliceIndex < 0 || visibleTotal <= 0 || value <= 0) {
+ return
+ }
+ onSliceClick({
+ sliceIndex,
+ series: { ...part, color: colorByKey.get(part.key) ?? '' },
+ value,
+ fraction: fractionOf(value),
+ })
+ }
// `ChartLegend` grows to fill a flex parent. Holding it in a box sized to its content keeps the
// legend right next to the bar, and lets the consumer place the pair, for example centered.
diff --git a/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.tsx b/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.tsx
index f496dffc50e3..8a56833288d0 100644
--- a/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.tsx
+++ b/packages/quill/packages/charts/src/charts/SankeyChart/SankeyChart.tsx
@@ -255,14 +255,11 @@ function SankeyChartInner<NodeMeta = unknown, LinkMeta = NodeMeta>({
hoverAnimationMs: HOVER_ANIMATION_MS,
})
- const renderTooltip = useMemo(
- () =>
- tooltip ??
- ((tooltipContext: SankeyTooltipContext<NodeMeta, LinkMeta>): React.ReactNode => (
- <PieTooltip ctx={tooltipContext} valueFormatter={valueFormatter} />
- )),
- [tooltip, valueFormatter]
- )
+ const renderTooltip =
+ tooltip ??
+ ((tooltipContext: SankeyTooltipContext<NodeMeta, LinkMeta>): React.ReactNode => (
+ <PieTooltip ctx={tooltipContext} valueFormatter={valueFormatter} />
+ ))
const canvasBounds = useCanvasBounds(canvasRef)
const layoutValue = useMemo<ChartLayoutContextValue | null>(() => {
diff --git a/packages/quill/packages/charts/src/charts/ScatterChart/ScatterChart.tsx b/packages/quill/packages/charts/src/charts/ScatterChart/ScatterChart.tsx
index b6f285067ff5..d85dbdd38d05 100644
--- a/packages/quill/packages/charts/src/charts/ScatterChart/ScatterChart.tsx
+++ b/packages/quill/packages/charts/src/charts/ScatterChart/ScatterChart.tsx
@@ -51,6 +51,31 @@ const EMPTY_AXIS_CONFIG: ScatterAxisConfig = {}
* module scope so it can't churn the base chart's margin and tick memos. */
const NO_CATEGORY_X_LABELS = (): null => null
+function drawHover({ ctx, scales, hoverIndex, hoverProgress, theme: drawTheme }: ChartDrawArgs): boolean {
+ const position = readScatterLayout(scales)?.positionByIndex[hoverIndex]
+ if (!position) {
+ return false
+ }
+ drawScatterHoverMarker(ctx, position, drawTheme.backgroundColor ?? '#ffffff', hoverProgress)
+ return true
+}
+
+// The base chart resolves by x alone, which can't tell points stacked at one x apart.
+function resolveHoverIndex(_index: number, cursor: { x: number; y: number }, scales: ChartScales): number {
+ const layout = readScatterLayout(scales)
+ if (!layout) {
+ return -1
+ }
+ return findNearestPointIndex(layout.positions, cursor.x, cursor.y, layout.maxRadius)
+}
+
+// A gap must stay NaN. The shared default coerces one to 0, anchoring the tooltip at whatever
+// pixel `0` maps to for every series with no point at this index.
+const resolveValue: ResolveValueFn = (s, dataIndex) => {
+ const value = s.data[dataIndex]
+ return typeof value === 'number' && isFinite(value) ? value : NaN
+}
+
export interface ScatterChartProps<Meta = unknown> {
series: ScatterSeries<Meta>[]
/** Defaults to the nearest `ChartThemeProvider`, then the quill CSS vars. */
@@ -189,104 +214,64 @@ function ScatterChartInner<Meta = unknown>({
[showGrid, showAxisLines, showTickMarks, fillOpacity, showBestFit, isPointHighlighted, points]
)
- const drawHover = useCallback(({ ctx, scales, hoverIndex, hoverProgress, theme: drawTheme }: ChartDrawArgs) => {
- const position = readScatterLayout(scales)?.positionByIndex[hoverIndex]
- if (!position) {
- return false
+ const resolvePoint = (dataIndex: number): ScatterPointDatum<Meta> | null => {
+ const point = points[dataIndex] as FlatScatterPoint<Meta> | undefined
+ if (!point) {
+ return null
}
- drawScatterHoverMarker(ctx, position, drawTheme.backgroundColor ?? '#ffffff', hoverProgress)
- return true
- }, [])
-
- // The base chart resolves by x alone, which can't tell points stacked at one x apart.
- const resolveHoverIndex = useCallback(
- (_index: number, cursor: { x: number; y: number }, scales: ChartScales): number => {
- const layout = readScatterLayout(scales)
- if (!layout) {
- return -1
- }
- return findNearestPointIndex(layout.positions, cursor.x, cursor.y, layout.maxRadius)
- },
- []
- )
-
- // A gap must stay NaN. The shared default coerces one to 0, anchoring the tooltip at whatever
- // pixel `0` maps to for every series with no point at this index.
- const resolveValue: ResolveValueFn = useCallback((s, dataIndex) => {
- const value = s.data[dataIndex]
- return typeof value === 'number' && isFinite(value) ? value : NaN
- }, [])
-
- const resolvePoint = useCallback(
- (dataIndex: number): ScatterPointDatum<Meta> | null => {
- const point = points[dataIndex] as FlatScatterPoint<Meta> | undefined
- if (!point) {
- return null
- }
- const { seriesIndex } = point
- return toPointDatum(point, series[seriesIndex], theme.colors[seriesIndex % theme.colors.length])
- },
- [points, series, theme.colors]
- )
+ const { seriesIndex } = point
+ return toPointDatum(point, series[seriesIndex], theme.colors[seriesIndex % theme.colors.length])
+ }
const tooltipConfig = config?.tooltip
const xAxisLabel = xAxis.label
const yAxisLabel = yAxis.label
- const renderTooltip = useCallback(
- (ctx: TooltipContext): React.ReactNode => {
- const point = resolvePoint(ctx.dataIndex)
- if (!point) {
- return null
- }
- if (tooltip) {
- return tooltip({ ...ctx, point })
- }
- return (
- <ScatterTooltip
- point={point}
- header={tooltipConfig?.labelFormatter?.(point)}
- xLabel={xAxisLabel}
- yLabel={yAxisLabel}
- xValue={tooltipConfig?.xFormatter?.(point.x, point) ?? xTickFormatter?.(point.x)}
- yValue={tooltipConfig?.yFormatter?.(point.y, point) ?? yTickFormatter?.(point.y)}
- />
- )
- },
- [resolvePoint, tooltip, tooltipConfig, xAxisLabel, yAxisLabel, xTickFormatter, yTickFormatter]
- )
+ const renderTooltip = (ctx: TooltipContext): React.ReactNode => {
+ const point = resolvePoint(ctx.dataIndex)
+ if (!point) {
+ return null
+ }
+ if (tooltip) {
+ return tooltip({ ...ctx, point })
+ }
+ return (
+ <ScatterTooltip
+ point={point}
+ header={tooltipConfig?.labelFormatter?.(point)}
+ xLabel={xAxisLabel}
+ yLabel={yAxisLabel}
+ xValue={tooltipConfig?.xFormatter?.(point.x, point) ?? xTickFormatter?.(point.x)}
+ yValue={tooltipConfig?.yFormatter?.(point.y, point) ?? yTickFormatter?.(point.y)}
+ />
+ )
+ }
- const handlePointClick = useCallback(
- (data: PointClickData): void => {
- const point = resolvePoint(data.dataIndex)
- if (point) {
- onPointClick?.(point)
- }
- },
- [onPointClick, resolvePoint]
- )
+ const handlePointClick = (data: PointClickData): void => {
+ const point = resolvePoint(data.dataIndex)
+ if (point) {
+ onPointClick?.(point)
+ }
+ }
// The core's label range means nothing on a continuous axis, so invert its raw pixels instead.
- const handleAreaSelect = useCallback(
- (data: AreaSelectData, scales: ChartScales): void => {
- const layout = readScatterLayout(scales)
- if (!layout || !onAreaSelect) {
- return
- }
- const { xScale, yScale } = layout
- onAreaSelect({
- x: sanitizeFixedDomain([
- xScale.invert(clampToRange(data.xPixel0, xScale)),
- xScale.invert(clampToRange(data.xPixel1, xScale)),
- ]),
- // The y pixel range runs top-to-bottom, so its low pixel inverts to the high value.
- y: sanitizeFixedDomain([
- yScale.invert(clampToRange(data.yPixel1, yScale)),
- yScale.invert(clampToRange(data.yPixel0, yScale)),
- ]),
- })
- },
- [onAreaSelect]
- )
+ const handleAreaSelect = (data: AreaSelectData, scales: ChartScales): void => {
+ const layout = readScatterLayout(scales)
+ if (!layout || !onAreaSelect) {
+ return
+ }
+ const { xScale, yScale } = layout
+ onAreaSelect({
+ x: sanitizeFixedDomain([
+ xScale.invert(clampToRange(data.xPixel0, xScale)),
+ xScale.invert(clampToRange(data.xPixel1, xScale)),
+ ]),
+ // The y pixel range runs top-to-bottom, so its low pixel inverts to the high value.
+ y: sanitizeFixedDomain([
+ yScale.invert(clampToRange(data.yPixel1, yScale)),
+ yScale.invert(clampToRange(data.yPixel0, yScale)),
+ ]),
+ })
+ }
// Otherwise the y gutter is sized from the adapter series, which stop short of a pinned domain.
const valueRangeSeries = useMemo<Series[] | undefined>(() => {
@@ -307,32 +292,18 @@ function ScatterChartInner<Meta = unknown>({
return applyMarginOverride(computed, margins)
}, [xAxis.hide, margins, points, xDomain, xTickFormatter])
- const baseConfig = useMemo<ChartConfig>(
- () => ({
- xTickFormatter: NO_CATEGORY_X_LABELS,
- yTickFormatter,
- xAxisLabel,
- yAxisLabel,
- hideXAxis: xAxis.hide,
- hideYAxis: yAxis.hide,
- margins: resolvedMargins,
- showTickMarks,
- showCrosshair,
- tooltip: { enabled: tooltipConfig?.enabled, placement: tooltipConfig?.placement ?? 'cursor' },
- }),
- [
- yTickFormatter,
- xAxisLabel,
- yAxisLabel,
- xAxis.hide,
- yAxis.hide,
- resolvedMargins,
- showTickMarks,
- showCrosshair,
- tooltipConfig?.enabled,
- tooltipConfig?.placement,
- ]
- )
+ const baseConfig: ChartConfig = {
+ xTickFormatter: NO_CATEGORY_X_LABELS,
+ yTickFormatter,
+ xAxisLabel,
+ yAxisLabel,
+ hideXAxis: xAxis.hide,
+ hideYAxis: yAxis.hide,
+ margins: resolvedMargins,
+ showTickMarks,
+ showCrosshair,
+ tooltip: { enabled: tooltipConfig?.enabled, placement: tooltipConfig?.placement ?? 'cursor' },
+ }
return (
<ChartLegend {...legendProps} legendDataAttr="hog-chart-scatter-legend">
diff --git a/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.tsx b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.tsx
index bc9960a0c071..cc06c9e4d36e 100644
--- a/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.tsx
+++ b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.tsx
@@ -1,4 +1,4 @@
-import React, { useCallback, useMemo } from 'react'
+import React, { useMemo } from 'react'
import { ChartLegend } from '../../components/Legend/ChartLegend'
import { useChartLegend } from '../../components/Legend/useChartLegend'
@@ -115,15 +115,6 @@ function SlopeChartInner<Meta = SlopeSeriesMeta>({
} = config ?? {}
const marginsOverride = useStableMargins(config?.margins)
- const showsStart = useCallback(
- (s: Series<Meta>): boolean => slopeLabelVisible(s, 'start', showStartLabels),
- [showStartLabels]
- )
- const showsEnd = useCallback(
- (s: Series<Meta>): boolean => slopeLabelVisible(s, 'end', showEndLabels),
- [showEndLabels]
- )
-
// Legend rows come from the full series (so toggled-off ones stay listed and restorable);
// `visibleSeries` carries the toggled-off entries as excluded for everything the chart draws.
const legendItems = useMemo(() => slopeLegendItems(series, theme, deltaFormatter), [series, theme, deltaFormatter])
@@ -136,8 +127,16 @@ function SlopeChartInner<Meta = SlopeSeriesMeta>({
// Reserve left/right gutters for the value/name labels, which sit in the margins beyond the plot.
const { margins, nameOffsetX } = useMemo(() => {
- const startWidth = maxLabelWidth(visibleSeries.filter(showsStart).map((s) => valueFormatter(slopeStart(s))))
- const endWidth = maxLabelWidth(visibleSeries.filter(showsEnd).map((s) => valueFormatter(slopeEnd(s))))
+ const startWidth = maxLabelWidth(
+ visibleSeries
+ .filter((s) => slopeLabelVisible(s, 'start', showStartLabels))
+ .map((s) => valueFormatter(slopeStart(s)))
+ )
+ const endWidth = maxLabelWidth(
+ visibleSeries
+ .filter((s) => slopeLabelVisible(s, 'end', showEndLabels))
+ .map((s) => valueFormatter(slopeEnd(s)))
+ )
const nameWidth = showSeriesLabels
? maxLabelWidth(
visibleSeries
@@ -168,63 +167,47 @@ function SlopeChartInner<Meta = SlopeSeriesMeta>({
margins: applyMarginOverride(base, marginsOverride),
nameOffsetX: offset,
}
- }, [visibleSeries, slopeLabels, showsStart, showsEnd, showSeriesLabels, valueFormatter, marginsOverride])
-
- // When the last point is the current incomplete period, dash only the *second half* of the
- // connector so it reads as "the end is provisional", not the whole comparison.
- const dashEnd = useMemo(
- () => visibleSeries.some((s) => (s.meta as SlopeSeriesMeta | undefined)?.incompleteEnd),
- [visibleSeries]
- )
+ }, [visibleSeries, slopeLabels, showStartLabels, showEndLabels, showSeriesLabels, valueFormatter, marginsOverride])
// A slope is a two-point line — collapse each series to its two points, with a dot at each. A
// dashed end splits the single segment at its midpoint (renderer-side, no phantom point).
- const slopeSeries = useMemo<Series<Meta>[]>(
- () =>
- visibleSeries.map((s) => ({
- ...s,
- data: [slopeStart(s), slopeEnd(s)],
- points: { ...s.points, radius: pointRadius },
- ...(dashEnd
- ? {
- stroke: {
- ...s.stroke,
- partial: {
- ...s.stroke?.partial,
- fromFraction: 0.5,
- },
+ const slopeSeries = useMemo<Series<Meta>[]>(() => {
+ // When the last point is the current incomplete period, dash only the *second half* of the
+ // connector so it reads as "the end is provisional", not the whole comparison.
+ const dashEnd = visibleSeries.some((s) => (s.meta as SlopeSeriesMeta | undefined)?.incompleteEnd)
+ return visibleSeries.map((s) => ({
+ ...s,
+ data: [slopeStart(s), slopeEnd(s)],
+ points: { ...s.points, radius: pointRadius },
+ ...(dashEnd
+ ? {
+ stroke: {
+ ...s.stroke,
+ partial: {
+ ...s.stroke?.partial,
+ fromFraction: 0.5,
},
- }
- : {}),
- })),
- [visibleSeries, pointRadius, dashEnd]
- )
+ },
+ }
+ : {}),
+ }))
+ }, [visibleSeries, pointRadius])
// SlopeChart owns the legend (wrapper below); strip it from the inner LineChart's config so the
// line chart's own built-in legend stays off and we don't render two.
- const lineConfig = useMemo<LineChartConfig>(
- () => ({
- ...config,
- legend: undefined,
- hideYAxis: config?.hideYAxis ?? true,
- showGrid: false,
- margins,
- valueDomain,
- }),
- [config, margins, valueDomain]
- )
+ const lineConfig: LineChartConfig = {
+ ...config,
+ legend: undefined,
+ hideYAxis: config?.hideYAxis ?? true,
+ showGrid: false,
+ margins,
+ valueDomain,
+ }
// A caller-supplied tooltip takes precedence; otherwise sort the default rows (see helper) and
// format values with the chart's valueFormatter so the tooltip matches the on-chart labels' units.
- const sortedTooltip = useCallback(
- (ctx: TooltipContext<Meta>): React.ReactNode => (
- <DefaultTooltip
- {...ctx}
- seriesData={sortSlopeTooltipRows(ctx.seriesData)}
- valueFormatter={valueFormatter}
- />
- ),
- [valueFormatter]
+ const sortedTooltip = (ctx: TooltipContext<Meta>): React.ReactNode => (
+ <DefaultTooltip {...ctx} seriesData={sortSlopeTooltipRows(ctx.seriesData)} valueFormatter={valueFormatter} />
)
return (
diff --git a/packages/quill/packages/charts/src/charts/Sparkline/Sparkline.tsx b/packages/quill/packages/charts/src/charts/Sparkline/Sparkline.tsx
index 3bb8c94b2ad3..e0a4e0aabd4c 100644
--- a/packages/quill/packages/charts/src/charts/Sparkline/Sparkline.tsx
+++ b/packages/quill/packages/charts/src/charts/Sparkline/Sparkline.tsx
@@ -99,36 +99,31 @@ function SparklineInner({
return [single]
}, [series, data, resolvedColor, type, fillOpacity, dashedFromIndex])
// Longest series, not just the first — a shorter/empty leading series must not truncate the labels.
- const pointCount = useMemo(() => Math.max(0, ...chartSeries.map(({ data }) => data.length)), [chartSeries])
+ const pointCount = Math.max(0, ...chartSeries.map(({ data }) => data.length))
const resolvedLabels = useMemo<string[]>(
() => labels ?? Array.from({ length: pointCount }, (_, i) => String(i)),
[labels, pointCount]
)
- const hasTooltip = tooltip != null
- const config = useMemo<LineChartConfig & BarChartConfig>(
- () => ({
- ...BASE_CONFIG,
- ...(type === 'bar'
- ? {
- barCornerRadius: 2,
- margins: BAR_MARGINS,
- showCrosshair: false,
- // Sparkline bars can be a pixel tall, or absent at a zero bucket.
- tooltip: { hitArea: 'band' as const },
- }
- : { showCrosshair: true, margins: LINE_MARGINS }),
- ...(hasTooltip ? {} : { tooltip: { enabled: false } }),
- ...(valueDomain ? { valueDomain } : {}),
- }),
- [type, hasTooltip, valueDomain]
- )
- const wrapperStyle = useMemo<React.CSSProperties | undefined>(() => (fill ? undefined : { height }), [fill, height])
+ const config: LineChartConfig & BarChartConfig = {
+ ...BASE_CONFIG,
+ ...(type === 'bar'
+ ? {
+ barCornerRadius: 2,
+ margins: BAR_MARGINS,
+ showCrosshair: false,
+ // Sparkline bars can be a pixel tall, or absent at a zero bucket.
+ tooltip: { hitArea: 'band' as const },
+ }
+ : { showCrosshair: true, margins: LINE_MARGINS }),
+ ...(tooltip != null ? {} : { tooltip: { enabled: false } }),
+ ...(valueDomain ? { valueDomain } : {}),
+ }
const watcher = onHoverIndexChange ? <HoverWatcher onHoverChange={onHoverIndexChange} /> : null
return (
<div
className={`relative flex flex-col ${fill ? 'flex-1 min-h-0' : ''} ${className ?? ''}`}
- style={wrapperStyle}
+ style={fill ? undefined : { height }}
data-attr={dataAttr}
>
{type === 'bar' ? (
diff --git a/packages/quill/packages/charts/src/components/Legend/useChartLegend.ts b/packages/quill/packages/charts/src/components/Legend/useChartLegend.ts
index ac8306a0bf73..d5ae1cdfac06 100644
--- a/packages/quill/packages/charts/src/components/Legend/useChartLegend.ts
+++ b/packages/quill/packages/charts/src/components/Legend/useChartLegend.ts
@@ -1,4 +1,4 @@
-import { useCallback, useMemo, useState, type ReactNode } from 'react'
+import { useMemo, useState, type ReactNode } from 'react'
import type { ChartLegendConfig, ChartTheme, Series } from '../../core/types'
import type { LegendItem, LegendItemClickModifiers } from './Legend'
@@ -83,67 +83,54 @@ export function useChartLegend<Meta>(
const hiddenKeys = controlledKeys ?? internalKeys
const onToggleSeries = config?.onToggleSeries
- const toggle = useCallback(
- (key: string) => {
- onToggleSeries?.(key, !hiddenKeys.includes(key))
- if (controlledKeys === undefined) {
- setInternalKeys((prev) => (prev.includes(key) ? prev.filter((k) => k !== key) : [...prev, key]))
- }
- },
- [controlledKeys, hiddenKeys, onToggleSeries]
- )
+ const toggle = (key: string): void => {
+ onToggleSeries?.(key, !hiddenKeys.includes(key))
+ if (controlledKeys === undefined) {
+ setInternalKeys((prev) => (prev.includes(key) ? prev.filter((k) => k !== key) : [...prev, key]))
+ }
+ }
const hiddenSet = useMemo(() => new Set(hiddenKeys), [hiddenKeys])
const visibleSeries = useMemo(() => applyHiddenSeries(series, hiddenSet), [series, hiddenSet])
- const derivedItems = useMemo(() => items ?? legendItemsFromSeries(series, theme), [items, series, theme])
+ const derivedItems = items ?? legendItemsFromSeries(series, theme)
const interactive = config?.interactive ?? true
// The rows the user can see, which is what "all" and "the others" mean to them — narrower than
// `series`, which also carries derived overlays (CI bands, trend lines) that get no legend row.
- const rowKeys = useMemo(() => derivedItems.map((item) => item.key), [derivedItems])
+ const rowKeys = derivedItems.map((item) => item.key)
// "The others" is a question about visibility, not about rows, and a consumer can store one
// visibility bit for several rows (see `visibilityGroupKey`). Resolve every row to its group
// once so isolating, `canIsolate`, and `isOnlyVisible` all agree on what a distinct series is.
const visibilityGroupKey = config?.visibilityGroupKey
- const groupByRow = useMemo(() => {
- const groups = new Map<string, string>()
- rowKeys.forEach((key) => groups.set(key, visibilityGroupKey?.(key) ?? key))
- return groups
- }, [rowKeys, visibilityGroupKey])
- const groupCount = useMemo(() => new Set(groupByRow.values()).size, [groupByRow])
+ const groupByRow = new Map(rowKeys.map((key) => [key, visibilityGroupKey?.(key) ?? key]))
+ const groupCount = new Set(groupByRow.values()).size
// Isolating and hiding-all replace the whole hidden set in one go, so a controlled legend needs
// `onSetHiddenSeries`: the per-series `onToggleSeries` can't express it as a single update.
const onSetHiddenSeries = config?.onSetHiddenSeries
- const setHidden = useCallback(
- (next: string[]) => {
- onSetHiddenSeries?.(next)
- if (controlledKeys === undefined) {
- setInternalKeys(next)
- }
- },
- [controlledKeys, onSetHiddenSeries]
- )
+ const setHidden = (next: string[]): void => {
+ onSetHiddenSeries?.(next)
+ if (controlledKeys === undefined) {
+ setInternalKeys(next)
+ }
+ }
const canSetBulk = controlledKeys === undefined || onSetHiddenSeries !== undefined
const canIsolate = interactive && canSetBulk && groupCount > 1
- const isolate = useCallback(
- (key: string) => {
- const group = groupByRow.get(key)
- const others = rowKeys.filter((k) => groupByRow.get(k) !== group)
- const alreadyIsolated = others.length > 0 && !hiddenSet.has(key) && others.every((k) => hiddenSet.has(k))
- setHidden(alreadyIsolated ? [] : others)
- },
- [rowKeys, groupByRow, hiddenSet, setHidden]
- )
+ const isolate = (key: string): void => {
+ const group = groupByRow.get(key)
+ const others = rowKeys.filter((k) => groupByRow.get(k) !== group)
+ const alreadyIsolated = others.length > 0 && !hiddenSet.has(key) && others.every((k) => hiddenSet.has(k))
+ setHidden(alreadyIsolated ? [] : others)
+ }
- const toggleAll = useCallback(() => {
+ const toggleAll = (): void => {
const allVisible = rowKeys.every((k) => !hiddenSet.has(k))
setHidden(allVisible ? [...rowKeys] : [])
- }, [rowKeys, hiddenSet, setHidden])
+ }
// Grafana's legend model: a plain click isolates (and clicking the isolated row restores all),
// ⌘/Ctrl-click builds a selection one series at a time. Picking one series out of twenty is the
@@ -151,25 +138,20 @@ export function useChartLegend<Meta>(
// A touch screen has no ⌘/Ctrl/Shift, so the additive gesture is unreachable and isolate-on-tap
// would strand the user on one series with no way to add a second. Tap toggles there instead, so
// taps build any subset the way the checkbox legend table does. Isolate stays on the row menu.
- const handleItemClick = useCallback(
- (key: string, { additive }: LegendItemClickModifiers) => {
- if (additive || !canIsolate || isCoarsePointer()) {
- toggle(key)
- return
- }
- isolate(key)
- },
- [canIsolate, toggle, isolate]
- )
+ const handleItemClick = (key: string, { additive }: LegendItemClickModifiers): void => {
+ if (additive || !canIsolate || isCoarsePointer()) {
+ toggle(key)
+ return
+ }
+ isolate(key)
+ }
const consumerRenderItem = config?.renderItem
- const renderItem = useMemo(() => {
- if (!consumerRenderItem) {
- return undefined
- }
+ let renderItem: ChartLegendRenderProps['renderItem']
+ if (consumerRenderItem) {
const visibleRows = rowKeys.filter((k) => !hiddenSet.has(k))
const visibleGroups = new Set(visibleRows.map((k) => groupByRow.get(k)))
- return (defaultNode: ReactNode, item: LegendItem): ReactNode =>
+ renderItem = (defaultNode, item) =>
consumerRenderItem(defaultNode, item, {
isHidden: hiddenSet.has(item.key),
isOnlyVisible: groupCount > 1 && visibleGroups.size === 1 && !hiddenSet.has(item.key),
@@ -179,7 +161,7 @@ export function useChartLegend<Meta>(
isolate: () => isolate(item.key),
toggleAll,
})
- }, [consumerRenderItem, rowKeys, groupByRow, groupCount, hiddenSet, canIsolate, toggle, isolate, toggleAll])
+ }
return {
visibleSeries,
diff --git a/packages/quill/packages/charts/src/components/MetricCard/MetricCard.tsx b/packages/quill/packages/charts/src/components/MetricCard/MetricCard.tsx
index a6cb9840efca..a6f2fbca28f2 100644
--- a/packages/quill/packages/charts/src/components/MetricCard/MetricCard.tsx
+++ b/packages/quill/packages/charts/src/components/MetricCard/MetricCard.tsx
@@ -1,4 +1,4 @@
-import React, { useMemo, useState } from 'react'
+import React, { useState } from 'react'
import { Sparkline } from '../../charts/Sparkline/Sparkline'
import { ChartErrorBoundary } from '../../core/ChartErrorBoundary'
@@ -132,7 +132,7 @@ function MetricCardInner({
const animationTarget = sparklineData && intentIndex >= 0 ? (sparklineData[intentIndex] ?? 0) : (restingValue ?? 0)
const animatedValue = useAnimatedNumber(animationTarget, animationMs)
- const baselineValue = useMemo(() => sparklineData?.find((v) => v !== 0 && Number.isFinite(v)), [sparklineData])
+ const baselineValue = sparklineData?.find((v) => v !== 0 && Number.isFinite(v))
if (restingValue == null) {
return null
diff --git a/packages/quill/packages/charts/src/core/Chart.tsx b/packages/quill/packages/charts/src/core/Chart.tsx
index d7a2f324b7ee..20c5f89e9725 100644
--- a/packages/quill/packages/charts/src/core/Chart.tsx
+++ b/packages/quill/packages/charts/src/core/Chart.tsx
@@ -379,18 +379,17 @@ export function Chart<Meta = unknown>({
hoverAnimationMs,
})
- const ariaLabel = useMemo(() => {
- const parts = [`Chart with ${countVisibleSeries(coloredSeries)} data series`]
- const cleanXAxisLabel = normalizeAxisLabel(xAxisLabel)
- const cleanYAxisLabel = normalizeAxisLabel(yAxisLabel)
- if (!hideXAxis && cleanXAxisLabel) {
- parts.push(`X-axis: ${cleanXAxisLabel}`)
- }
- if (!hideYAxis && cleanYAxisLabel) {
- parts.push(`Y-axis: ${cleanYAxisLabel}`)
- }
- return parts.join('. ')
- }, [coloredSeries, hideXAxis, hideYAxis, xAxisLabel, yAxisLabel])
+ const visibleSeriesCount = useMemo(() => countVisibleSeries(coloredSeries), [coloredSeries])
+ const ariaParts = [`Chart with ${visibleSeriesCount} data series`]
+ const cleanXAxisLabel = normalizeAxisLabel(xAxisLabel)
+ const cleanYAxisLabel = normalizeAxisLabel(yAxisLabel)
+ if (!hideXAxis && cleanXAxisLabel) {
+ ariaParts.push(`X-axis: ${cleanXAxisLabel}`)
+ }
+ if (!hideYAxis && cleanYAxisLabel) {
+ ariaParts.push(`Y-axis: ${cleanYAxisLabel}`)
+ }
+ const ariaLabel = ariaParts.join('. ')
const canvasBounds = useCanvasBounds(canvasRef)
@@ -398,10 +397,6 @@ export function Chart<Meta = unknown>({
// falling back to the value resolver when the chart doesn't stack.
const stablePositionValue = useStableResolveValue(resolvePositionValue ?? resolveValue)
- const axisValue = useMemo(
- () => ({ orientation: axisOrientation, xTickFormatter, isPercent }),
- [axisOrientation, xTickFormatter, isPercent]
- )
const axisColor = theme.axisColor ?? DEFAULT_AXIS_COLOR
const layoutValue = useMemo<ChartLayoutContextValue | null>(() => {
@@ -416,10 +411,22 @@ export function Chart<Meta = unknown>({
theme,
resolvePositionValue: stablePositionValue,
canvasBounds,
- axis: axisValue,
+ axis: { orientation: axisOrientation, xTickFormatter, isPercent },
yGutters,
}
- }, [scales, dimensions, labels, coloredSeries, theme, stablePositionValue, canvasBounds, axisValue, yGutters])
+ }, [
+ scales,
+ dimensions,
+ labels,
+ coloredSeries,
+ theme,
+ stablePositionValue,
+ canvasBounds,
+ axisOrientation,
+ xTickFormatter,
+ isPercent,
+ yGutters,
+ ])
const hoverValue = useMemo<ChartHoverContextValue>(() => ({ hoverIndex }), [hoverIndex])
diff --git a/packages/quill/packages/charts/src/core/RadialChart.tsx b/packages/quill/packages/charts/src/core/RadialChart.tsx
index c1a3acf2d884..d94af08a1875 100644
--- a/packages/quill/packages/charts/src/core/RadialChart.tsx
+++ b/packages/quill/packages/charts/src/core/RadialChart.tsx
@@ -78,10 +78,7 @@ export function RadialChart<Meta = unknown>({
// Wrap DefaultTooltip in a JSX render function so its hooks run inside its own component
// tree — calling it as a plain function would violate rules-of-hooks.
- const renderTooltip = useMemo<(ctx: TooltipContext<Meta>) => React.ReactNode>(
- () => renderTooltipProp ?? ((ctx: TooltipContext<Meta>) => <DefaultTooltip {...ctx} />),
- [renderTooltipProp]
- )
+ const renderTooltip = renderTooltipProp ?? ((ctx: TooltipContext<Meta>) => <DefaultTooltip {...ctx} />)
const coloredSeries = useColoredSeries<Meta>(series, theme)
@@ -130,7 +127,8 @@ export function RadialChart<Meta = unknown>({
hoverAnimationMs,
})
- const ariaLabel = useMemo(() => `Pie chart with ${countVisibleSeries(coloredSeries)} slices`, [coloredSeries])
+ const visibleSeriesCount = useMemo(() => countVisibleSeries(coloredSeries), [coloredSeries])
+ const ariaLabel = `Pie chart with ${visibleSeriesCount} slices`
const canvasBounds = useCanvasBounds(canvasRef)
diff --git a/packages/quill/packages/charts/src/core/chart-config.ts b/packages/quill/packages/charts/src/core/chart-config.ts
index fa1060e31022..d1f6de323c7b 100644
--- a/packages/quill/packages/charts/src/core/chart-config.ts
+++ b/packages/quill/packages/charts/src/core/chart-config.ts
@@ -16,6 +16,9 @@ export const DEFAULT_CHART_CONFIG = {
tooltip: { placement: 'cursor' },
} as const satisfies ChartConfig & { barCornerRadius: number }
+/** Default y-tick formatter for percent layouts, whose values are 0..1 fractions. */
+export const PERCENT_TICK_FORMATTER = (v: number): string => `${Math.round(v * 100)}%`
+
function definedFields(config: object): Record<string, unknown> {
return Object.fromEntries(Object.entries(config).filter(([, value]) => value !== undefined))
}
diff --git a/packages/quill/packages/charts/src/overlays/AxisLabels.tsx b/packages/quill/packages/charts/src/overlays/AxisLabels.tsx
index 4b26022fd164..e3523113cf2b 100644
--- a/packages/quill/packages/charts/src/overlays/AxisLabels.tsx
+++ b/packages/quill/packages/charts/src/overlays/AxisLabels.tsx
@@ -1,4 +1,4 @@
-import React, { useMemo } from 'react'
+import React from 'react'
import { useChartLayout } from '../core/chart-context'
import { TICK_GAP } from '../core/y-axis-gutters'
@@ -299,23 +299,16 @@ export const AxisLabels = React.memo(function AxisLabels({
maxCategoryLabelWidth = 0,
}: AxisLabelsProps): React.ReactElement | null {
const { scales, dimensions, labels, yGutters } = useChartLayout()
- const yTicks = scales.yTicks()
-
- const visibleXLabels = useMemo(
- () =>
- hideXAxis || orientation === 'horizontal'
- ? []
- : computeVisibleXLabels(labels, scales.x, xTickFormatter, maxCategoryLabelWidth, xTickLabelRotation),
- [hideXAxis, labels, scales.x, xTickFormatter, xTickLabelRotation, orientation, maxCategoryLabelWidth]
- )
- // Mirror the vertical branch's memoization so an unrelated prop change (e.g. axisColor)
- // doesn't re-run the per-tick `ctx.measureText` measurements in `dropOverlappingLabels`.
- const visibleValueTicks = useMemo(
- () =>
- hideXAxis || orientation !== 'horizontal' ? [] : computeVisibleValueTicks(yTicks, scales.y, yTickFormatter),
- [hideXAxis, orientation, yTicks, scales.y, yTickFormatter]
- )
+ const visibleXLabels =
+ hideXAxis || orientation === 'horizontal'
+ ? []
+ : computeVisibleXLabels(labels, scales.x, xTickFormatter, maxCategoryLabelWidth, xTickLabelRotation)
+
+ const visibleValueTicks =
+ hideXAxis || orientation !== 'horizontal'
+ ? []
+ : computeVisibleValueTicks(scales.yTicks(), scales.y, yTickFormatter)
if (orientation === 'horizontal') {
// In horizontal mode `scales.y` holds value→x-pixel and the label→y-pixel function lives
diff --git a/packages/quill/packages/charts/src/overlays/ReferenceLine.tsx b/packages/quill/packages/charts/src/overlays/ReferenceLine.tsx
index 8b4cdbfb5b11..290fed704cd7 100644
--- a/packages/quill/packages/charts/src/overlays/ReferenceLine.tsx
+++ b/packages/quill/packages/charts/src/overlays/ReferenceLine.tsx
@@ -1,5 +1,5 @@
/* eslint-disable react/forbid-dom-props -- dynamic pixel positions from d3 scales */
-import React, { useMemo, useState } from 'react'
+import React, { useState } from 'react'
import { useChartLayout } from '../core/chart-context'
import { TOOLTIP_FALLBACK_BG, TOOLTIP_FALLBACK_COLOR } from './TooltipSurface'
@@ -102,11 +102,7 @@ export function ReferenceLines({ lines }: { lines: ReferenceLineProps[] }): Reac
export function ReferenceLine(props: ReferenceLineProps): React.ReactElement | null {
const { axis } = useChartLayout()
const { orientation = 'horizontal', variant = 'goal', style, axisOrientation = axis.orientation } = props
- const resolved = useMemo(
- () => resolveStyle(variant, style),
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [variant, style?.color, style?.stroke, style?.width]
- )
+ const resolved = resolveStyle(variant, style)
const common: ResolvedProps = {
resolved,
diff --git a/packages/quill/packages/charts/src/overlays/TrendLineOverlay.tsx b/packages/quill/packages/charts/src/overlays/TrendLineOverlay.tsx
index ceec1778ba5a..0ef07b3d34fe 100644
--- a/packages/quill/packages/charts/src/overlays/TrendLineOverlay.tsx
+++ b/packages/quill/packages/charts/src/overlays/TrendLineOverlay.tsx
@@ -1,9 +1,9 @@
/* eslint-disable react/forbid-dom-props -- dynamic pixel positions from d3 scales */
import React, { useMemo } from 'react'
-import type { Series } from '../core/types'
import { useChartLayout } from '../core/chart-context'
import { resolveYScaleForSeries } from '../core/scales'
+import type { Series } from '../core/types'
interface TrendLineOverlayProps {
/** Pre-computed trend line series (from buildTrendLineSeries). One per source series. */