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): compute chart margins without the noise memos (#129015)

Sam Penningtonb46f352c19a8
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index ac022db887c8..d93c52edefea 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -2665,9 +2665,9 @@ snapshots:
components-sample-data-tag--default--light:
hash: v1.k794b7964.8ebad648dbf23b4ccf50c7b2543d02e9429c2f5c67446cee8823fc06fc98a97d.MSu4A4yz_nNpo8sN007sucqXSdbb7pJQExT5Z2ki0Ys
components-search--default--dark:
- hash: v1.k794b7964.a31e507e5100bda9cf79afe63ff56f09ae4b8bf87cf21262dc41aac4743d7bfb.bXeCWe9xu6E09y_REa_qrvoiXNd0oIAmeS47a6C0prQ
+ hash: v1.k794b7964.8bca0ce8beeda976c50694c82ff59efa5ef71dd69bd6933b752946b496585290.XT8M9kdCB7rY6IrsIdEwimlExYjWZZAQrTtiKE3dm0I
components-search--default--light:
- hash: v1.k794b7964.dd6e176d613ede77b64c03c5b698c8d1552ba65edf3c7aa2678909ce1a55f77e.TVkA8RF5EfKRAQ4dH5HeKZekeVwzUWN8R7GFw29b0UE
+ hash: v1.k794b7964.ef8f1544da02a0d9973f16cbecde26acae54786e498ac6ebc152b34c19f88e40.HBG_apkBv14LNSXkz1oqwsujkw8dJDJLA6f81FiRU5o
components-search--no-recents--dark:
hash: v1.k794b7964.0fd0f5d4767912eb77720bd4c629f886a998551875574392ee5ba4140cde90e9.W0slxaCCdN_quO_OA4mBH35mVBVVoWTbw5jMNLwb1HY
components-search--no-recents--light:
diff --git a/packages/quill/packages/charts/src/core/hooks/useChartMargins.ts b/packages/quill/packages/charts/src/core/hooks/useChartMargins.ts
index b035570ff763..f9f04ee7f80b 100644
--- a/packages/quill/packages/charts/src/core/hooks/useChartMargins.ts
+++ b/packages/quill/packages/charts/src/core/hooks/useChartMargins.ts
@@ -8,7 +8,7 @@ import {
rotatedTickLabelSize,
} from '../../utils/axis-labels'
import { measureLabelWidth } from '../../utils/text-measure'
-import { autoFormatterFor, orderedAxisPositions, seriesValueRange } from '../scales'
+import { autoFormatterFor, groupVisibleSeriesByAxis, orderedAxisPositions, seriesValueRange } from '../scales'
import { DEFAULT_Y_AXIS_ID } from '../types'
import type { ChartMargins, Series } from '../types'
@@ -129,12 +129,17 @@ function categoryLabelWidths(
return { first, last, widest }
}
-function widestValueLabelWidth(series: Series[], yTickFormatter: ((value: number) => string) | undefined): number {
- const range = seriesValueRange(series)
+function widestValueLabelWidth(
+ series: Series[],
+ yTickFormatter: ((value: number) => string) | undefined,
+ isPercent: boolean
+): number {
+ const range = isPercent ? null : seriesValueRange(series)
// No data: the scale falls back to a [0, 1] domain (see `buildValueScale`), whose automatic ticks
// render as "0".."1". Measure those so the empty-state margin still fits its labels — returning 0
// here collapses the margin to its floor and clips the labels against the wrapper's overflow.
- const [min, max] = range.count === 0 ? [0, 1] : [range.min > 0 ? 0 : range.min, range.max < 0 ? 0 : range.max]
+ const [min, max] =
+ !range || range.count === 0 ? [0, 1] : [range.min > 0 ? 0 : range.min, range.max < 0 ? 0 : range.max]
const ticks = scaleLinear().domain([min, max]).nice(6).ticks(6)
if (ticks.length === 0) {
return 0
@@ -147,6 +152,56 @@ function widestValueLabelWidth(series: Series[], yTickFormatter: ((value: number
return widest
}
+interface SideReserve {
+ left: number
+ right: number
+}
+
+const NO_RESERVE: SideReserve = { left: 0, right: 0 }
+
+interface PerAxisOptions {
+ rangeSeries: Series[]
+ isPercent: boolean
+ yTickFormatter?: (value: number) => string
+ yAxisFormatters?: Record<string, (value: number) => string>
+ yAxisPositions?: Record<string, 'left' | 'right'>
+ yAxisTitles?: Record<string, string>
+ yAxisHidden?: Record<string, boolean>
+}
+
+// Mirrors AxisLabels' gutter layout.
+function perAxisReserves(options: PerAxisOptions): { gutters: SideReserve; titles: SideReserve } {
+ const { rangeSeries, isPercent, yTickFormatter, yAxisFormatters, yAxisPositions, yAxisTitles, yAxisHidden } =
+ options
+ const byAxis = groupVisibleSeriesByAxis(rangeSeries)
+ const gutters = { left: 0, right: 0 }
+ const titles = { left: 0, right: 0 }
+ for (const { axisId, position } of orderedAxisPositions(rangeSeries)) {
+ if (yAxisHidden?.[axisId]) {
+ continue
+ }
+ const side = yAxisPositions?.[axisId] ?? position
+ const formatter = yAxisFormatters?.[axisId] ?? yTickFormatter
+ const width = Math.ceil(widestValueLabelWidth(byAxis.get(axisId) ?? [], formatter, isPercent))
+ gutters[side] += width + Y_LABEL_RIGHT_PADDING + (gutters[side] > 0 ? GUTTER_GAP : 0)
+ titles[side] += yAxisTitles?.[axisId] ? Y_AXIS_TITLE_MARGIN : 0
+ }
+ return { gutters, titles }
+}
+
+function categoryEdgeReserves(categoryWidths: CategoryLabelWidths, tickLabelRotation: number): SideReserve {
+ if (tickLabelRotation === 0) {
+ const halfWidth = Math.ceil(categoryWidths.widest / 2)
+ return { left: halfWidth, right: halfWidth }
+ }
+ const radians = (Math.abs(tickLabelRotation) * Math.PI) / 180
+ const thinEdgeReserve = Math.ceil(AXIS_TICK_LABEL_HEIGHT * Math.sin(radians))
+ if (tickLabelRotation < 0) {
+ return { left: Math.ceil(categoryWidths.first * Math.cos(radians)), right: thinEdgeReserve }
+ }
+ return { left: thinEdgeReserve, right: Math.ceil(categoryWidths.last * Math.cos(radians)) }
+}
+
export function useChartMargins({
series,
labels,
@@ -158,7 +213,7 @@ export function useChartMargins({
yTickFormatter,
axisOrientation = 'vertical',
isPercent = false,
- override: rawOverride,
+ override,
valueRangeSeries,
maxCategoryLabelWidth = 0,
yAxisFormatters,
@@ -166,181 +221,71 @@ export function useChartMargins({
yAxisTitles,
yAxisHidden,
}: UseChartMarginsOptions): ChartMargins {
- const override = useStableMargins(rawOverride)
const isHorizontal = axisOrientation === 'horizontal'
- const valueSeries = useMemo(
- () => (isPercent ? series.map((s) => ({ ...s, data: [0, 1] })) : (valueRangeSeries ?? series)),
- [isPercent, series, valueRangeSeries]
- )
- const normalizedXAxisLabel = normalizeAxisLabel(xAxisLabel)
+ const rangeSeries = isPercent ? series : (valueRangeSeries ?? series)
const tickLabelRotation = isHorizontal ? 0 : normalizeTickLabelRotation(xTickLabelRotation)
+ // A single axis pinned right draws its gutter on the right, so it needs the per-side layout too.
+ const axisCount = useMemo(() => orderedAxisPositions(series).length, [series])
+ const usesPerSideGutters = axisCount > 1 || Object.values(yAxisPositions ?? {}).includes('right')
+ const perAxis = !hideYAxis && !isHorizontal && usesPerSideGutters
+ const needsWidestValue = isHorizontal ? !hideXAxis : !hideYAxis && !perAxis
+
const categoryWidths = useMemo(
() => categoryLabelWidths(labels, xTickFormatter, maxCategoryLabelWidth),
[labels, xTickFormatter, maxCategoryLabelWidth]
)
-
- const hasMultipleAxes = useMemo(() => {
- const axisIds = new Set(
- series.filter((s) => !s.visibility?.excluded).map((s) => s.yAxisId ?? DEFAULT_Y_AXIS_ID)
- )
- return axisIds.size > 1
- }, [series])
-
- // Per-side gutter layout also applies to a single axis explicitly pinned right — the series-count
- // check above misses it, which would reserve the left margin while the gutter draws on the right.
- const usesPerSideGutters = useMemo(
- () => hasMultipleAxes || Object.values(yAxisPositions ?? {}).some((side) => side === 'right'),
- [hasMultipleAxes, yAxisPositions]
+ const widestValue = useMemo(
+ () => (needsWidestValue ? widestValueLabelWidth(rangeSeries, yTickFormatter, isPercent) : 0),
+ [needsWidestValue, rangeSeries, yTickFormatter, isPercent]
+ )
+ const perAxisWidths = useMemo(
+ () =>
+ perAxis
+ ? perAxisReserves({
+ rangeSeries,
+ isPercent,
+ yTickFormatter,
+ yAxisFormatters,
+ yAxisPositions,
+ yAxisTitles,
+ yAxisHidden,
+ })
+ : null,
+ [perAxis, rangeSeries, isPercent, yTickFormatter, yAxisFormatters, yAxisPositions, yAxisTitles, yAxisHidden]
)
- // One rotated-title band per titled axis, on its side. Horizontal charts (category axis on the
- // left) and single-value-axis charts only ever title the default left axis.
- const titleReserve = useMemo<{ left: number; right: number }>(() => {
- if (hideYAxis || !yAxisTitles) {
- return { left: 0, right: 0 }
- }
- if (isHorizontal || !usesPerSideGutters) {
- return { left: yAxisTitles[DEFAULT_Y_AXIS_ID] ? Y_AXIS_TITLE_MARGIN : 0, right: 0 }
- }
- let left = 0
- let right = 0
- for (const { axisId, position } of orderedAxisPositions(valueSeries)) {
- if (!yAxisTitles[axisId] || yAxisHidden?.[axisId]) {
- continue
- }
- if ((yAxisPositions?.[axisId] ?? position) === 'left') {
- left += Y_AXIS_TITLE_MARGIN
- } else {
- right += Y_AXIS_TITLE_MARGIN
- }
- }
- return { left, right }
- }, [hideYAxis, isHorizontal, usesPerSideGutters, valueSeries, yAxisPositions, yAxisTitles, yAxisHidden])
-
- const yLabelWidth = useMemo<number>(() => {
- if (hideYAxis) {
- return 0
- }
- if (isHorizontal) {
- return categoryWidths.widest
- }
- return widestValueLabelWidth(valueSeries, yTickFormatter)
- }, [valueSeries, yTickFormatter, hideYAxis, isHorizontal, categoryWidths.widest])
-
- const xLabelEdgeReserves = useMemo<{ left: number; right: number }>(() => {
- if (hideXAxis) {
- return { left: 0, right: 0 }
- }
- if (isHorizontal) {
- const widest = widestValueLabelWidth(valueSeries, yTickFormatter)
- const halfWidth = Math.ceil(widest / 2)
- return { left: halfWidth, right: halfWidth }
- }
- if (labels.length === 0) {
- return { left: 0, right: 0 }
- }
- if (tickLabelRotation === 0) {
- const halfWidth = Math.ceil(categoryWidths.widest / 2)
- return { left: halfWidth, right: halfWidth }
- }
+ const defaultTitle = !hideYAxis && yAxisTitles?.[DEFAULT_Y_AXIS_ID] ? Y_AXIS_TITLE_MARGIN : 0
+ const titles = perAxisWidths?.titles ?? { left: defaultTitle, right: 0 }
- const radians = (Math.abs(tickLabelRotation) * Math.PI) / 180
- const thinEdgeReserve = Math.ceil(AXIS_TICK_LABEL_HEIGHT * Math.sin(radians))
- if (tickLabelRotation < 0) {
- return {
- left: Math.ceil(categoryWidths.first * Math.cos(radians)),
- right: thinEdgeReserve,
- }
- }
- return {
- left: thinEdgeReserve,
- right: Math.ceil(categoryWidths.last * Math.cos(radians)),
- }
- }, [categoryWidths, hideXAxis, isHorizontal, labels.length, tickLabelRotation, valueSeries, yTickFormatter])
+ let xLabelEdges = NO_RESERVE
+ if (!hideXAxis && isHorizontal) {
+ xLabelEdges = { left: Math.ceil(widestValue / 2), right: Math.ceil(widestValue / 2) }
+ } else if (!hideXAxis && labels.length > 0) {
+ xLabelEdges = categoryEdgeReserves(categoryWidths, tickLabelRotation)
+ }
- const xLabelExtraBottom = useMemo<number>(() => {
- if (hideXAxis || isHorizontal || tickLabelRotation === 0) {
- return 0
- }
- const rotatedHeight = rotatedTickLabelSize(categoryWidths.widest, tickLabelRotation).height
- return Math.max(0, Math.ceil(rotatedHeight - AXIS_TICK_LABEL_HEIGHT))
- }, [categoryWidths.widest, hideXAxis, isHorizontal, tickLabelRotation])
+ let bottom = COLLAPSED_AXIS_MARGIN
+ if (!hideXAxis) {
+ const rotatedHeight =
+ tickLabelRotation === 0 ? 0 : rotatedTickLabelSize(categoryWidths.widest, tickLabelRotation).height
+ const extraBottom = Math.max(0, Math.ceil(rotatedHeight - AXIS_TICK_LABEL_HEIGHT))
+ bottom = DEFAULT_MARGINS.bottom + extraBottom + (normalizeAxisLabel(xAxisLabel) ? X_AXIS_TITLE_MARGIN : 0)
+ }
- // With multiple y-axes the value-axis labels stack into several gutters per side; reserve the
- // cumulative width so the outer gutters aren't clipped. Mirrors AxisLabels' gutter layout.
- const gutterReserves = useMemo<{ left: number; right: number } | null>(() => {
- if (hideYAxis || isHorizontal || !usesPerSideGutters) {
- return null
- }
- const byAxis = new Map<string, Series[]>()
- for (const s of valueSeries) {
- if (s.visibility?.excluded) {
- continue
- }
- const id = s.yAxisId ?? DEFAULT_Y_AXIS_ID
- const bucket = byAxis.get(id)
- if (bucket) {
- bucket.push(s)
- } else {
- byAxis.set(id, [s])
- }
- }
- let left = 0
- let right = 0
- for (const { axisId, position } of orderedAxisPositions(valueSeries)) {
- if (yAxisHidden?.[axisId]) {
- continue
- }
- const formatter = yAxisFormatters?.[axisId] ?? yTickFormatter
- const side = yAxisPositions?.[axisId] ?? position
- const width = Math.ceil(widestValueLabelWidth(byAxis.get(axisId) ?? [], formatter)) + Y_LABEL_RIGHT_PADDING
- if (side === 'left') {
- left += width + (left > 0 ? GUTTER_GAP : 0)
- } else {
- right += width + (right > 0 ? GUTTER_GAP : 0)
- }
- }
- return { left, right }
- }, [
- hideYAxis,
- isHorizontal,
- usesPerSideGutters,
- valueSeries,
- yTickFormatter,
- yAxisFormatters,
- yAxisPositions,
- yAxisHidden,
- ])
+ const yLabelWidth = isHorizontal ? categoryWidths.widest : widestValue
+ const leftLabelReserve = perAxisWidths?.gutters.left ?? Math.ceil(yLabelWidth) + Y_LABEL_RIGHT_PADDING
+ // The first x label overhangs the plot's left edge even with the y-axis hidden.
+ const left = hideYAxis
+ ? Math.max(COLLAPSED_AXIS_MARGIN, xLabelEdges.left + X_LABEL_EDGE_PADDING)
+ : Math.max(MIN_LEFT_MARGIN, leftLabelReserve + Y_LABEL_LEFT_GUTTER, xLabelEdges.left + X_LABEL_EDGE_PADDING) +
+ titles.left
+ const rightFloor = usesPerSideGutters && !hideYAxis ? MIN_RIGHT_MARGIN_DUAL_AXIS : DEFAULT_MARGINS.right
+ const rightLabelReserve = (perAxisWidths?.gutters.right ?? 0) + titles.right
+ const right = Math.max(rightFloor, rightLabelReserve, xLabelEdges.right + X_LABEL_EDGE_PADDING)
- return useMemo<ChartMargins>(() => {
- const bottom = hideXAxis
- ? COLLAPSED_AXIS_MARGIN
- : DEFAULT_MARGINS.bottom + xLabelExtraBottom + (normalizedXAxisLabel ? X_AXIS_TITLE_MARGIN : 0)
- const leftLabelReserve = gutterReserves ? gutterReserves.left : Math.ceil(yLabelWidth) + Y_LABEL_RIGHT_PADDING
- // Even with the y-axis collapsed, the first x label still overhangs the plot's left edge,
- // so its edge reserve keeps the floor (the right margin already does the same).
- const left = hideYAxis
- ? Math.max(COLLAPSED_AXIS_MARGIN, xLabelEdgeReserves.left + X_LABEL_EDGE_PADDING)
- : Math.max(
- MIN_LEFT_MARGIN,
- leftLabelReserve + Y_LABEL_LEFT_GUTTER,
- xLabelEdgeReserves.left + X_LABEL_EDGE_PADDING
- ) + titleReserve.left
- const rightFloor = usesPerSideGutters && !hideYAxis ? MIN_RIGHT_MARGIN_DUAL_AXIS : DEFAULT_MARGINS.right
- const rightLabelReserve = (gutterReserves?.right ?? 0) + titleReserve.right
- const right = Math.max(rightFloor, rightLabelReserve, xLabelEdgeReserves.right + X_LABEL_EDGE_PADDING)
- const computed: ChartMargins = { top: DEFAULT_MARGINS.top, right, bottom, left }
- return applyMarginOverride(computed, override)
- }, [
- hideXAxis,
- hideYAxis,
- usesPerSideGutters,
- gutterReserves,
- yLabelWidth,
- xLabelEdgeReserves,
- xLabelExtraBottom,
- normalizedXAxisLabel,
- titleReserve,
- override,
- ])
+ const margins = applyMarginOverride({ top: DEFAULT_MARGINS.top, right, bottom, left }, override ?? {})
+ return useMemo(
+ () => ({ top: margins.top, right: margins.right, bottom: margins.bottom, left: margins.left }),
+ [margins.top, margins.right, margins.bottom, margins.left]
+ )
}