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.

fix(mobile): make crowded bar charts readable (#129592)

Chris Volzerca178d7ca9ba
diff --git a/products/mobile/docs/VIEWS.md b/products/mobile/docs/VIEWS.md
index 236bc404ffd8..4a668a76cbf0 100644
--- a/products/mobile/docs/VIEWS.md
+++ b/products/mobile/docs/VIEWS.md
@@ -262,6 +262,9 @@ A SQL insight is a `DataVisualizationNode` with a `HogQLQuery` source. Its respo
- `key` is the JSON cache key of the snapshot that opened the screen. Full screen therefore shows the same session range, compare and tile layers as the tile or insight. While a new range loads on the insight screen, `key` names the previous range's entry, which is the one on screen (`InsightScreenState.queryKey`). Without `key`, it reads the insight's own entry.
- It reads the cache only and never sends a request. A key without a cached snapshot (the app restarted, or a deep link to an insight not opened yet) shows "This chart isn't loaded" with "Go back" (`chart-fullscreen-missing`).
- A line or bar chart fills the space, scrubs on a drag in any direction, shows every tooltip row, and lists every series as a 44 pt legend row that scrolls. Funnels, retention (all periods), bar lists (all rows) and SQL tables (up to 500 rows) show in a card.
+- Saved stacked bar charts keep their stacks in pins, tiles, insights and full screen. The value axis fits the full stack; zero values leave no bar. Full screen offers a small layout icon beside Back for multi-series bar charts. Tap it to switch between grouped and stacked bars. The choice persists on this device across visits and applies to all bar charts, including pins and dashboard tiles. Until a choice is made, each chart uses its saved layout.
+- When time-series bars would become too thin, inline and full-screen charts show a readable window of dates, starting with the most recent. The date arrows page through every bucket without changing the saved interval; tooltips and screen reader selection follow the visible dates. Compact pins retain the whole range.
+- Date controls fit within the chart's reserved height, so dashboard tiles keep their height when a canvas replaces its placeholder. Hourly page labels include the calendar date and time at both ends of the window.
- Charts on this screen send the usual chart events with `context: fullscreen`.
- Portrait only: the app has no `expo-screen-orientation`, and landscape needs that native module in a new binary. There is no "Zoom to range" or "Show as table" yet.
diff --git a/products/mobile/src/features/views/InsightChart.tsx b/products/mobile/src/features/views/InsightChart.tsx
index 0dc06afc9bf8..1aa0a98d1e8e 100644
--- a/products/mobile/src/features/views/InsightChart.tsx
+++ b/products/mobile/src/features/views/InsightChart.tsx
@@ -7,9 +7,10 @@ import { MetricChart } from '@/ui/chart/MetricChart'
import type { ChartAccessibilityAction, ChartCanvasSlot, ChartSeries } from '@/ui/chart/types'
import { useTheme } from '@/ui/theme'
import type { FullScreenEntry } from './analytics'
+import { useChartPreferences } from './chartPreferencesStore'
import { useChartSheets } from './pointSheet/ChartSheetsProvider'
import type { ChartSheetSource } from './pointSheet/chartSheetSource'
-import { snapshotChartSeries, snapshotFormatter } from './snapshotChart'
+import { snapshotBarLayout, snapshotChartSeries, snapshotFormatter } from './snapshotChart'
interface InsightChartModel {
series: ChartSeries[]
@@ -63,6 +64,7 @@ export function InsightChart({
onOpenFullScreen,
testID,
}: InsightChartProps): ReactElement | null {
+ const preferredLayout = useChartPreferences((state) => state.barLayout)
const sheets = useChartSheets()
const legend = useChartLegend()
const model = useInsightChartModel(snapshot, rangeText)
@@ -84,6 +86,7 @@ export function InsightChart({
<MetricChart
series={model.series}
kind={kind}
+ barLayout={snapshotBarLayout(snapshot, preferredLayout)}
interval={snapshot.interval}
label={snapshot.name}
formatValue={model.formatValue}
diff --git a/products/mobile/src/features/views/chartPreferencesStore.test.ts b/products/mobile/src/features/views/chartPreferencesStore.test.ts
new file mode 100644
index 000000000000..d6e4c4177ad9
--- /dev/null
+++ b/products/mobile/src/features/views/chartPreferencesStore.test.ts
@@ -0,0 +1,18 @@
+import AsyncStorage from '@react-native-async-storage/async-storage'
+
+import { useChartPreferences } from './chartPreferencesStore'
+
+const STORAGE_KEY = 'views-chart-preferences:v1'
+
+test.each(['grouped', 'stacked'] as const)('restores the %s bar preference after reloading storage', async (layout) => {
+ await useChartPreferences.persist.rehydrate()
+ useChartPreferences.getState().setBarLayout(layout)
+ const stored = await AsyncStorage.getItem(STORAGE_KEY)
+ expect(stored).not.toBeNull()
+
+ useChartPreferences.setState({ barLayout: null })
+ await AsyncStorage.setItem(STORAGE_KEY, stored as string)
+ await useChartPreferences.persist.rehydrate()
+
+ expect(useChartPreferences.getState().barLayout).toBe(layout)
+})
diff --git a/products/mobile/src/features/views/chartPreferencesStore.ts b/products/mobile/src/features/views/chartPreferencesStore.ts
new file mode 100644
index 000000000000..46b3310186e8
--- /dev/null
+++ b/products/mobile/src/features/views/chartPreferencesStore.ts
@@ -0,0 +1,24 @@
+import AsyncStorage from '@react-native-async-storage/async-storage'
+import { create } from 'zustand'
+import { createJSONStorage, persist } from 'zustand/middleware'
+
+import type { BarLayout } from '@/ui/chart/types'
+
+interface ChartPreferencesState {
+ barLayout: BarLayout | null
+ setBarLayout: (layout: BarLayout) => void
+}
+
+export const useChartPreferences = create<ChartPreferencesState>()(
+ persist(
+ (set) => ({
+ barLayout: null,
+ setBarLayout: (barLayout) => set({ barLayout }),
+ }),
+ {
+ name: 'views-chart-preferences:v1',
+ storage: createJSONStorage(() => AsyncStorage),
+ partialize: (state) => ({ barLayout: state.barLayout }),
+ }
+ )
+)
diff --git a/products/mobile/src/features/views/fullScreen/FullScreenChart.tsx b/products/mobile/src/features/views/fullScreen/FullScreenChart.tsx
index 3aba2e655637..b2e8e5460e4a 100644
--- a/products/mobile/src/features/views/fullScreen/FullScreenChart.tsx
+++ b/products/mobile/src/features/views/fullScreen/FullScreenChart.tsx
@@ -10,16 +10,19 @@ import { RetentionGrid } from '@/ui/chart/RetentionGrid'
import { SqlTable } from '@/ui/chart/SqlTable'
import { useChartListMotion } from '@/ui/chart/selection/ChartSelectionProvider'
import { SQL_TABLE_MAX_ROWS, sqlRowsText } from '@/ui/chart/sqlCellFormat'
-import type { ChartAccessibilityAction } from '@/ui/chart/types'
+import type { BarLayout, ChartAccessibilityAction } from '@/ui/chart/types'
import { Eyebrow } from '@/ui/Eyebrow'
+import { BarChartIcon } from '@/ui/icons/BarChartIcon'
+import { Pressable44 } from '@/ui/Pressable44'
import { ScreenChrome } from '@/ui/ScreenChrome'
import { StateView } from '@/ui/StateView'
import { SCREEN_CONTENT_TOP } from '@/ui/screenLayout'
-import { createStyles } from '@/ui/theme'
-import { layout, radii, type } from '@/ui/tokens'
+import { createStyles, useTheme } from '@/ui/theme'
+import { iconSizes, layout, radii, type } from '@/ui/tokens'
import { bottomOffset, topOffset, useScreenInsets } from '@/ui/useScreenInsets'
import { type ScrollTitleState, useScrollTitle } from '@/ui/useScrollTitle'
+import { useChartPreferences } from '../chartPreferencesStore'
import { useInsightChartModel } from '../InsightChart'
import { InsightNoData } from '../InsightVisual'
import { OpensOnWeb } from '../OpensOnWeb'
@@ -32,6 +35,7 @@ import {
insightRenderState,
intervalLabel,
resolvedRangeText,
+ snapshotBarLayout,
snapshotFormatter,
} from '../snapshotChart'
import { useViewsContext } from '../useViewsContext'
@@ -59,13 +63,44 @@ export function FullScreenChart({ shortId, queryKey }: FullScreenChartProps): Re
const { scope } = useViewsContext()
const key = useMemo(() => queryKey ?? viewsKeys.insight(scope, shortId, null, '-'), [queryKey, scope, shortId])
const snapshot = useSnapshot<InsightSnapshot>(key)
+ const styles = useStyles()
+ const { colors, shadows } = useTheme()
const scrollTitle = useScrollTitle(snapshot?.name ?? '')
+ const preferredLayout = useChartPreferences((state) => state.barLayout)
+ const setBarLayout = useChartPreferences((state) => state.setBarLayout)
+ const barLayout = snapshot ? snapshotBarLayout(snapshot, preferredLayout) : 'grouped'
+ const showLayout =
+ snapshot &&
+ insightRenderState(snapshot) === 'ready' &&
+ snapshot.chartKind === 'bar' &&
+ snapshot.allSeries.filter((series) => series.compare !== 'previous').length > 1
return (
<ViewScreenFrame
- chrome={<ScreenChrome onBack={back} backTestID="chart-fullscreen-back" title={scrollTitle.title} />}
+ chrome={
+ <ScreenChrome
+ onBack={back}
+ backTestID="chart-fullscreen-back"
+ title={scrollTitle.title}
+ right={
+ showLayout ? (
+ <Pressable44
+ onPress={() => setBarLayout(barLayout === 'stacked' ? 'grouped' : 'stacked')}
+ accessibilityLabel={barLayout === 'stacked' ? 'Show grouped bars' : 'Show stacked bars'}
+ accessibilityValue={{ text: barLayout === 'stacked' ? 'Stacked bars' : 'Grouped bars' }}
+ accessibilityHint="Applies to all bar charts on this device."
+ style={[styles.layoutButton, shadows.chip]}
+ pressedBackground={colors.sunken}
+ testID="chart-layout-toggle"
+ >
+ <BarChartIcon layout={barLayout} size={iconSizes.control} />
+ </Pressable44>
+ ) : null
+ }
+ />
+ }
>
{snapshot && insightRenderState(snapshot) !== 'pending' ? (
- <FullScreenBody scrollTitle={scrollTitle} snapshot={snapshot} queryKey={key} />
+ <FullScreenBody scrollTitle={scrollTitle} snapshot={snapshot} queryKey={key} barLayout={barLayout} />
) : (
<StateView
title="This chart isn't loaded"
@@ -83,10 +118,12 @@ function FullScreenBody({
snapshot,
queryKey,
scrollTitle,
+ barLayout,
}: {
snapshot: InsightSnapshot
queryKey: QueryKey
scrollTitle: ScrollTitleState
+ barLayout: BarLayout
}): ReactElement {
const styles = useStyles()
const insets = useScreenInsets()
@@ -123,7 +160,7 @@ function FullScreenBody({
return (
<View style={[styles.fill, styles.gutter, padding]}>
{header}
- <TimeSeries snapshot={snapshot} source={source} rangeText={rangeText} />
+ <TimeSeries snapshot={snapshot} source={source} rangeText={rangeText} barLayout={barLayout} />
</View>
)
}
@@ -207,6 +244,7 @@ function metaLead(snapshot: InsightSnapshot, display: InsightDisplay): string |
}
interface TimeSeriesProps {
+ barLayout: BarLayout
snapshot: InsightSnapshot
source: ChartSheetSource
rangeText: string | null
@@ -216,7 +254,7 @@ interface TimeSeriesProps {
* The chart fills the space under the title. It does not sit in a scroll view, because a full-screen drag scrubs in
* any direction. With several series the legend lists every one of them and scrolls on its own.
*/
-function TimeSeries({ snapshot, source, rangeText }: TimeSeriesProps): ReactElement | null {
+function TimeSeries({ snapshot, source, rangeText, barLayout }: TimeSeriesProps): ReactElement | null {
const styles = useStyles()
const sheets = useChartSheets()
const legend = useChartLegend()
@@ -239,6 +277,7 @@ function TimeSeries({ snapshot, source, rangeText }: TimeSeriesProps): ReactElem
<MetricChart
series={model.series}
kind={kind}
+ barLayout={barLayout}
interval={snapshot.interval}
label={snapshot.name}
formatValue={model.formatValue}
@@ -308,6 +347,16 @@ const useStyles = createStyles(({ colors }) => ({
color: colors.ink,
fontVariant: ['tabular-nums'],
},
+ layoutButton: {
+ width: 46,
+ height: 46,
+ borderRadius: radii.pill,
+ backgroundColor: colors.surface,
+ borderWidth: 1,
+ borderColor: colors.border,
+ alignItems: 'center',
+ justifyContent: 'center',
+ },
legend: {
flex: 1,
marginTop: LEGEND_GAP,
diff --git a/products/mobile/src/features/views/list/PinCard.tsx b/products/mobile/src/features/views/list/PinCard.tsx
index 26224e7cdf0f..3d2fe4daa6b8 100644
--- a/products/mobile/src/features/views/list/PinCard.tsx
+++ b/products/mobile/src/features/views/list/PinCard.tsx
@@ -21,11 +21,19 @@ import { ChevronRightIcon } from '@/ui/icons/ChevronRightIcon'
import { Pressable44 } from '@/ui/Pressable44'
import { createStyles, useColors, useTheme } from '@/ui/theme'
import { radii, type } from '@/ui/tokens'
+
+import { useChartPreferences } from '../chartPreferencesStore'
import { DeltaPill, deltaSpoken } from '../DeltaPill'
import { statusLine } from '../freshness'
import { type DashboardSnapshot, dashboardQueryKey } from '../items'
import { type PinData, usePinData } from '../pinHooks'
-import { deltaBasisText, snapshotChartSeries, snapshotFormatter, valueAtText } from '../snapshotChart'
+import {
+ deltaBasisText,
+ snapshotBarLayout,
+ snapshotChartSeries,
+ snapshotFormatter,
+ valueAtText,
+} from '../snapshotChart'
import { useViewsContext } from '../useViewsContext'
import { itemErrorMessage } from '../viewHooks'
import { useSnapshot } from '../viewsCache'
@@ -239,6 +247,7 @@ function NumberPin({ pin, data, onOpen, onMenu, onUnpin }: DataPinProps): ReactE
function ChartPin({ pin, index, data, onOpen, onMenu, onUnpin, onPressTooltip }: DataPinProps): ReactElement {
const { colors, chartPalette } = useTheme()
const styles = useStyles()
+ const preferredLayout = useChartPreferences((state) => state.barLayout)
const menu = useMenuTrigger(pin, onMenu)
const legend = useChartLegend()
const { snapshot } = data
@@ -288,6 +297,7 @@ function ChartPin({ pin, index, data, onOpen, onMenu, onUnpin, onPressTooltip }:
series={series}
hiddenKeys={legend.state.hiddenKeys}
kind={snapshot.chartKind ?? 'line'}
+ barLayout={snapshotBarLayout(snapshot, preferredLayout)}
interval={snapshot.interval}
label={snapshot.name}
formatValue={format}
diff --git a/products/mobile/src/features/views/snapshotChart.ts b/products/mobile/src/features/views/snapshotChart.ts
index 0624f2206244..6eda77291daa 100644
--- a/products/mobile/src/features/views/snapshotChart.ts
+++ b/products/mobile/src/features/views/snapshotChart.ts
@@ -1,4 +1,5 @@
import { parseBucketStart } from '@/lib/dates'
+import { asRecord } from '@/lib/records'
import { breakdownLabel, isRankingQuery } from '@/model/adapters/breakdown'
import { isDrawableFunnel } from '@/model/adapters/funnel'
import { formatInsightValue } from '@/model/adapters/insightFormatting'
@@ -10,7 +11,7 @@ import type { MetricInterval } from '@/model/types'
import type { InsightSeriesView, InsightSnapshot, NumberDelta, ResolvedRange } from '@/model/views'
import { formatAxisDate } from '@/ui/chart/chartMath'
import { seriesColor } from '@/ui/chart/palette'
-import type { ChartPoint, ChartSeries } from '@/ui/chart/types'
+import type { BarLayout, ChartPoint, ChartSeries } from '@/ui/chart/types'
import { hasGoodValue } from './freshness'
import { formatRangeSpan, rangeLabel } from './rangePresets'
@@ -150,6 +151,17 @@ export function snapshotChartSeries(snapshot: InsightSnapshot, palette: readonly
return result
}
+export function snapshotBarLayout(
+ snapshot: Pick<InsightSnapshot, 'query'>,
+ preferredLayout?: BarLayout | null
+): BarLayout {
+ if (preferredLayout) {
+ return preferredLayout
+ }
+ const filter = asRecord(asTrendsInsight(snapshot.query)?.source.trendsFilter)
+ return filter?.display === 'ActionsBar' || filter?.display === 'ActionsStackedBar' ? 'stacked' : 'grouped'
+}
+
/** The series behind a chart key, for the actors query at a point. */
export function seriesForKey(snapshot: InsightSnapshot, key: string): InsightSeriesView | undefined {
return snapshot.allSeries.find((series) => series.key === key)
diff --git a/products/mobile/src/model/adapters/insightSnapshot.test.ts b/products/mobile/src/model/adapters/insightSnapshot.test.ts
index 6e16eef57a17..bbea74532307 100644
--- a/products/mobile/src/model/adapters/insightSnapshot.test.ts
+++ b/products/mobile/src/model/adapters/insightSnapshot.test.ts
@@ -5,6 +5,7 @@ import {
insightRenderState,
noDataText,
pinRangeLabel,
+ snapshotBarLayout,
snapshotChartSeries,
snapshotFormatter,
} from '@/features/views/snapshotChart'
@@ -141,6 +142,17 @@ describe('insightSnapshot', () => {
expect(snapshotFormatter(snapshot)(snapshot.value as number)).toBe(expected)
})
+ test.each([
+ ['ActionsBar', null, 'stacked'],
+ ['ActionsStackedBar', null, 'stacked'],
+ ['ActionsUnstackedBar', null, 'grouped'],
+ ['ActionsBar', 'grouped', 'grouped'],
+ ['ActionsUnstackedBar', 'stacked', 'stacked'],
+ ] as const)('uses %s with the device preference %s as %s', (display, preferred, expected) => {
+ const snapshot = insightSnapshot(insight({ query: trends(undefined, display) }), undefined, CONTEXT)
+ expect(snapshotBarLayout(snapshot, preferred)).toBe(expected)
+ })
+
test.each<[string, Partial<InsightApi>]>([
[
'a rate-limited response',
diff --git a/products/mobile/src/ui/chart/ChartDatePager.tsx b/products/mobile/src/ui/chart/ChartDatePager.tsx
new file mode 100644
index 000000000000..25a4a7e74d17
--- /dev/null
+++ b/products/mobile/src/ui/chart/ChartDatePager.tsx
@@ -0,0 +1,67 @@
+import type { ReactElement } from 'react'
+import { Text, View } from 'react-native'
+
+import { ChevronLeftIcon } from '@/ui/icons/ChevronLeftIcon'
+import { ChevronRightIcon } from '@/ui/icons/ChevronRightIcon'
+import { Pressable44 } from '@/ui/Pressable44'
+import { createStyles, useColors } from '@/ui/theme'
+import { lineHeight } from '@/ui/tokens'
+
+import { formatPagerDate } from './chartMath'
+import type { ChartInterval } from './types'
+
+interface ChartDatePagerProps {
+ from: number
+ to: number
+ interval: ChartInterval
+ earlier: boolean
+ later: boolean
+ onEarlier: () => void
+ onLater: () => void
+}
+
+export function ChartDatePager({
+ from,
+ to,
+ interval,
+ earlier,
+ later,
+ onEarlier,
+ onLater,
+}: ChartDatePagerProps): ReactElement {
+ const colors = useColors()
+ const styles = useStyles()
+ return (
+ <View style={styles.row}>
+ <Pressable44
+ onPress={onEarlier}
+ disabled={!earlier}
+ accessibilityLabel="Show earlier dates"
+ accessibilityState={{ disabled: !earlier }}
+ style={styles.button}
+ testID="chart-dates-earlier"
+ >
+ <ChevronLeftIcon size={18} color={earlier ? colors.ink : colors.disabled} />
+ </Pressable44>
+ <Text style={styles.label} accessibilityLiveRegion="polite" numberOfLines={1}>
+ {formatPagerDate(from, interval)} - {formatPagerDate(to, interval)}
+ </Text>
+ <Pressable44
+ onPress={onLater}
+ disabled={!later}
+ accessibilityLabel="Show later dates"
+ accessibilityState={{ disabled: !later }}
+ style={styles.button}
+ testID="chart-dates-later"
+ >
+ <ChevronRightIcon size={18} color={later ? colors.ink : colors.disabled} />
+ </Pressable44>
+ </View>
+ )
+}
+
+const useStyles = createStyles(({ colors }) => ({
+ row: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', height: 44 },
+ button: { width: 44, height: 44, alignItems: 'center', justifyContent: 'center' },
+ label: { fontSize: 13, lineHeight: lineHeight(13), color: colors.secondary, flexShrink: 1 },
+}))
diff --git a/products/mobile/src/ui/chart/MetricChartCanvas.test.tsx b/products/mobile/src/ui/chart/MetricChartCanvas.test.tsx
new file mode 100644
index 000000000000..daabe3f49c79
--- /dev/null
+++ b/products/mobile/src/ui/chart/MetricChartCanvas.test.tsx
@@ -0,0 +1,45 @@
+import { fireEvent, render, screen } from '@testing-library/react-native'
+import 'react-native-gesture-handler/jestSetup'
+
+import { MetricChartCanvas } from './MetricChartCanvas'
+import type { ChartVariant } from './types'
+
+jest.unmock('./MetricChartCanvas')
+jest.mock('react-native-worklets', () => jest.requireActual('react-native-worklets/src/mock'))
+jest.mock('react-native-reanimated', () => jest.requireActual('react-native-reanimated/mock'))
+jest.mock('./MetricChartRenderer', () => ({ MetricChartRenderer: () => null }))
+
+describe('MetricChartCanvas', () => {
+ test.each<[ChartVariant, number | undefined, number, number]>([
+ ['inline', undefined, 48, 100],
+ ['inline', 240, 48, 196],
+ ['fullscreen', 400, 48, 356],
+ ['inline', undefined, 1, 144],
+ ['compact', undefined, 48, 96],
+ ])('fits the pager within the reserved height: %s, %s, %s buckets', (variant, height, count, plotHeight) => {
+ render(
+ <MetricChartCanvas
+ kind="bar"
+ accent="opportunity"
+ interval="hour"
+ label="Events"
+ formatValue={String}
+ variant={variant}
+ height={height}
+ points={Array.from({ length: count }, (_, index) => ({
+ at: new Date(2026, 9, 13, index).getTime(),
+ value: index + 1,
+ }))}
+ testID="metric"
+ />
+ )
+ fireEvent(screen.getByTestId('metric'), 'layout', { nativeEvent: { layout: { width: 320 } } })
+
+ expect(screen.getByTestId('metric')).toHaveStyle({ height: plotHeight })
+ if (variant !== 'compact' && count > 1) {
+ expect(screen.getByTestId('chart-dates-earlier')).toBeTruthy()
+ } else {
+ expect(screen.queryByTestId('chart-dates-earlier')).toBeNull()
+ }
+ })
+})
diff --git a/products/mobile/src/ui/chart/MetricChartCanvas.tsx b/products/mobile/src/ui/chart/MetricChartCanvas.tsx
index cd6d1317a2f5..461808f88ede 100644
--- a/products/mobile/src/ui/chart/MetricChartCanvas.tsx
+++ b/products/mobile/src/ui/chart/MetricChartCanvas.tsx
@@ -6,6 +6,8 @@ import { createStyles, useTheme } from '@/ui/theme'
import { fonts } from '@/ui/tokens'
import { useChartAccessibility } from './accessibility/useChartAccessibility'
+import { barPageSize, barSegments, barWindow } from './barLayout'
+import { ChartDatePager } from './ChartDatePager'
import { ChartOverlay } from './ChartOverlay'
import { chartGeometry, TICK_LINE_HEIGHT, X_LABEL_OFFSET, yPosition } from './chartGeometry'
import { samePoints, TICK_FONT_SIZE } from './chartMath'
@@ -21,7 +23,7 @@ import {
import { useChartGestures } from './gestures/useChartGestures'
import { MetricChartRenderer, type PlottedSeries } from './MetricChartRenderer'
import { useChartSelection } from './selection/useChartSelection'
-import type { ChartPoint, ChartSeries, MetricChartProps } from './types'
+import type { ChartPoint, ChartSeries, ChartTooltipPoint, MetricChartProps } from './types'
import { chartHeight } from './variant'
const NO_HIDDEN: readonly string[] = []
@@ -57,6 +59,7 @@ function useStableSeries(series: ChartSeries[]): ChartSeries[] {
export function MetricChartCanvas(props: MetricChartProps): ReactElement {
const {
kind,
+ barLayout = 'grouped',
interval,
label,
formatValue,
@@ -73,29 +76,85 @@ export function MetricChartCanvas(props: MetricChartProps): ReactElement {
} = props
const theme = useTheme()
const styles = useStyles()
- const height = chartHeight(variant, props.height)
- const series = useStableSeries(chartSeriesOf(props, theme))
- const accent = props.accent ? theme.accentColor[props.accent] : (series[0]?.color ?? theme.colors.blue)
+ const fullHeight = chartHeight(variant, props.height)
+ const allSeries = useStableSeries(chartSeriesOf(props, theme))
+ const accent = props.accent ? theme.accentColor[props.accent] : (allSeries[0]?.color ?? theme.colors.blue)
const [width, setWidth] = useState(0)
const viewRef = useRef<View>(null)
+ const [page, setPage] = useState({ data: allSeries, endOffset: 0 })
+ const endOffset = page.data === allSeries ? page.endOffset : 0
+ const allVisible = useMemo(() => visibleSeries(allSeries, hiddenKeys), [allSeries, hiddenKeys])
+ const totalCount = bucketCount(allSeries)
+ const currentCount = allVisible.filter((s) => !isCompareSeries(s)).length
+ const allSegments = useMemo(() => barSegments(allVisible, barLayout), [allVisible, barLayout])
+ const axisValues = useMemo(
+ () =>
+ allVisible.flatMap((s, index) =>
+ kind === 'bar'
+ ? isCompareSeries(s)
+ ? []
+ : [...(allSegments[index]?.starts ?? []), ...(allSegments[index]?.ends ?? [])]
+ : s.points.map((p) => p.value)
+ ),
+ [allVisible, allSegments, kind]
+ )
+ const axisGeometry = useMemo(
+ () =>
+ chartGeometry({
+ width,
+ height: fullHeight,
+ kind,
+ variant,
+ count: totalCount,
+ values: axisValues,
+ dates: [],
+ interval,
+ formatValue,
+ }),
+ [width, fullHeight, kind, variant, totalCount, axisValues, interval, formatValue]
+ )
+ const pageSize = barPageSize(axisGeometry.plot.right - axisGeometry.plot.left, currentCount, barLayout)
+ const paged = kind === 'bar' && variant !== 'compact' && width > 0 && totalCount > pageSize
+ const window = barWindow(totalCount, paged ? pageSize : Math.max(1, totalCount), endOffset)
+ const series = useMemo(
+ () =>
+ paged
+ ? allSeries.map((s) => ({
+ ...s,
+ points: s.points.slice(window.start, window.end),
+ incompleteFrom:
+ s.incompleteFrom === undefined ? undefined : Math.max(0, s.incompleteFrom - window.start),
+ }))
+ : allSeries,
+ [allSeries, paged, window.start, window.end]
+ )
+ const height = paged ? fullHeight - 44 : fullHeight
const visible = useMemo(() => visibleSeries(series, hiddenKeys), [series, hiddenKeys])
const count = bucketCount(series)
const dates = useMemo(() => bucketDates(series), [series])
const mask = useMemo(() => selectableMask(visible, count), [visible, count])
+ const segments = useMemo(() => barSegments(visible, barLayout), [visible, barLayout])
const geometry = useMemo(() => {
- const values = visible.flatMap((s) =>
- kind === 'bar' && isCompareSeries(s) ? [] : s.points.map((p) => p.value)
- )
- return chartGeometry({ width, height, kind, variant, count, values, dates, interval, formatValue })
- }, [width, height, kind, variant, count, visible, dates, interval, formatValue])
+ return chartGeometry({ width, height, kind, variant, count, values: axisValues, dates, interval, formatValue })
+ }, [width, height, kind, variant, count, axisValues, dates, interval, formatValue])
const plotted = useMemo<PlottedSeries[]>(
() =>
- visible.map((s) => {
- const ys = s.points.map((point) =>
- Number.isFinite(point.value) ? yPosition(point.value, geometry.yDomain, geometry.plot) : Number.NaN
+ visible.map((s, seriesIndex) => {
+ const segment = segments[seriesIndex]
+ const ys = s.points.map((point, index) =>
+ Number.isFinite(point.value)
+ ? yPosition(
+ kind === 'bar' ? (segment?.ends[index] ?? 0) : point.value,
+ geometry.yDomain,
+ geometry.plot
+ )
+ : Number.NaN
+ )
+ const baseYs = s.points.map((_, index) =>
+ yPosition(segment?.starts[index] ?? 0, geometry.yDomain, geometry.plot)
)
const points: PointsArray = s.points.map((point, index) => ({
x: geometry.xs[index] ?? 0,
@@ -111,10 +170,21 @@ export function MetricChartCanvas(props: MetricChartProps): ReactElement {
compare: isCompareSeries(s),
points,
ys,
+ baseYs,
incompleteFrom: s.incompleteFrom,
}
}),
- [visible, geometry, theme]
+ [visible, geometry, segments, kind, theme]
+ )
+
+ const pressTooltip = useMemo(
+ () =>
+ onPressTooltip
+ ? (point: ChartTooltipPoint): void => {
+ onPressTooltip({ ...point, index: point.index + (paged ? window.start : 0) })
+ }
+ : undefined,
+ [onPressTooltip, paged, window.start]
)
const pointAt = useCallback(
@@ -155,7 +225,7 @@ export function MetricChartCanvas(props: MetricChartProps): ReactElement {
dataUntil,
mask,
selection,
- onPressTooltip,
+ onPressTooltip: pressTooltip,
actions: accessibilityActions,
})
@@ -164,66 +234,81 @@ export function MetricChartCanvas(props: MetricChartProps): ReactElement {
}, [])
return (
- <View
- ref={viewRef}
- style={[styles.container, { height }]}
- onLayout={onLayout}
- onTouchStart={selection.onTouchStart}
- testID={testID}
- {...a11y}
- >
- {width > 0 ? (
- <>
- <MetricChartRenderer
- key={`${geometry.width}:${geometry.height}`}
- geometry={geometry}
- kind={kind}
- variant={variant}
- series={plotted}
- accent={accent}
- selection={selection.values}
- gestures={gestures}
- />
- {geometry.yTicks.map(({ value, y, text }) =>
- text === null ? null : (
+ <View onLayout={onLayout}>
+ {paged ? (
+ <ChartDatePager
+ from={dates[0] ?? 0}
+ to={dates[dates.length - 1] ?? 0}
+ interval={interval}
+ earlier={window.start > 0}
+ later={window.end < totalCount}
+ onEarlier={() => setPage({ data: allSeries, endOffset: totalCount - window.start })}
+ onLater={() =>
+ setPage({ data: allSeries, endOffset: Math.max(0, totalCount - window.end - pageSize) })
+ }
+ />
+ ) : null}
+ <View
+ ref={viewRef}
+ style={[styles.container, { height }]}
+ onTouchStart={selection.onTouchStart}
+ testID={testID}
+ {...a11y}
+ >
+ {width > 0 ? (
+ <>
+ <MetricChartRenderer
+ key={`${geometry.width}:${geometry.height}`}
+ geometry={geometry}
+ kind={kind}
+ barLayout={barLayout}
+ variant={variant}
+ series={plotted}
+ accent={accent}
+ selection={selection.values}
+ gestures={gestures}
+ />
+ {geometry.yTicks.map(({ value, y, text }) =>
+ text === null ? null : (
+ <Text
+ key={`y-${value}`}
+ numberOfLines={1}
+ style={[
+ styles.tick,
+ { right: width - geometry.yLabelWidth, top: y - TICK_LINE_HEIGHT / 2 },
+ ]}
+ >
+ {text}
+ </Text>
+ )
+ )}
+ {geometry.xLabels.map(({ index, left, width: labelWidth, text }) => (
<Text
- key={`y-${value}`}
+ key={`x-${index}`}
numberOfLines={1}
style={[
styles.tick,
- { right: width - geometry.yLabelWidth, top: y - TICK_LINE_HEIGHT / 2 },
+ styles.xTick,
+ { left, width: labelWidth, top: geometry.plot.bottom + X_LABEL_OFFSET },
]}
>
{text}
</Text>
- )
- )}
- {geometry.xLabels.map(({ index, left, width: labelWidth, text }) => (
- <Text
- key={`x-${index}`}
- numberOfLines={1}
- style={[
- styles.tick,
- styles.xTick,
- { left, width: labelWidth, top: geometry.plot.bottom + X_LABEL_OFFSET },
- ]}
- >
- {text}
- </Text>
- ))}
- <ChartOverlay
- selection={selection.values}
- geometry={geometry}
- series={series}
- hiddenKeys={hiddenKeys}
- interval={interval}
- variant={variant}
- formatValue={formatValue}
- dataUntil={dataUntil}
- onPressTooltip={onPressTooltip}
- />
- </>
- ) : null}
+ ))}
+ <ChartOverlay
+ selection={selection.values}
+ geometry={geometry}
+ series={series}
+ hiddenKeys={hiddenKeys}
+ interval={interval}
+ variant={variant}
+ formatValue={formatValue}
+ dataUntil={dataUntil}
+ onPressTooltip={pressTooltip}
+ />
+ </>
+ ) : null}
+ </View>
</View>
)
}
diff --git a/products/mobile/src/ui/chart/MetricChartRenderer.tsx b/products/mobile/src/ui/chart/MetricChartRenderer.tsx
index 5baab67d0d69..f1838d7a5f60 100644
--- a/products/mobile/src/ui/chart/MetricChartRenderer.tsx
+++ b/products/mobile/src/ui/chart/MetricChartRenderer.tsx
@@ -19,7 +19,7 @@ import { barSpan, type ChartGeometry, type PlotRect, yPosition } from './chartGe
import { BAR_BAND_PADDING } from './chartMath'
import { gestureHandlerConfig } from './gestures/useChartGestures'
import type { ChartSelectionValues } from './selection/useChartSelection'
-import type { ChartKind, ChartVariant } from './types'
+import type { BarLayout, ChartKind, ChartVariant } from './types'
/** One visible series in canvas coordinates. */
export interface PlottedSeries {
@@ -30,6 +30,7 @@ export interface PlottedSeries {
points: PointsArray
/** The y of each bucket, NaN for a gap. */
ys: number[]
+ baseYs: number[]
incompleteFrom?: number
}
@@ -46,6 +47,7 @@ const NO_Y_AXIS = [{ lineWidth: 0, tickCount: 0, font: null }]
interface MetricChartRendererProps {
geometry: ChartGeometry
+ barLayout: BarLayout
kind: ChartKind
variant: ChartVariant
series: PlottedSeries[]
@@ -62,6 +64,7 @@ interface MetricChartRendererProps {
export function MetricChartRenderer({
geometry,
kind,
+ barLayout,
variant,
series,
accent,
@@ -117,6 +120,7 @@ export function MetricChartRenderer({
{kind === 'bar' ? (
<Bars
series={current}
+ layout={barLayout}
geometry={geometry}
accent={accent}
selection={selection}
@@ -261,12 +265,14 @@ function Dot({
function Bars({
series,
+ layout,
geometry,
accent,
selection,
variant,
}: {
series: PlottedSeries[]
+ layout: BarLayout
geometry: ChartGeometry
accent: string
selection: ChartSelectionValues
@@ -277,18 +283,27 @@ function Bars({
const zeroY = yPosition(0, geometry.yDomain, plot)
const single = series.length === 1
const groupWidth = bandWidth * (1 - BAR_BAND_PADDING)
- const barWidth = groupWidth / Math.max(1, series.length)
+ const barWidth = groupWidth / (layout === 'stacked' ? 1 : Math.max(1, series.length))
const paths = useMemo(
() =>
series.map((s, seriesIndex) => {
const builder = Skia.PathBuilder.Make()
- for (const point of s.points) {
- if (typeof point.y !== 'number' || !Number.isFinite(point.y)) {
+ for (const [index, point] of s.points.entries()) {
+ if (typeof point.y !== 'number' || !Number.isFinite(point.y) || !point.yValue) {
continue
}
- const { top, height } = barSpan(point.y, zeroY)
- const left = point.x - groupWidth / 2 + seriesIndex * barWidth
- builder.addRRect(Skia.RRectXY(Skia.XYWHRect(left, top, barWidth, height), 1, 1))
+ const base = s.baseYs[index] ?? zeroY
+ const { top, height } =
+ layout === 'stacked'
+ ? { top: Math.min(point.y, base), height: Math.abs(base - point.y) }
+ : barSpan(point.y, base)
+ const left = point.x - groupWidth / 2 + (layout === 'stacked' ? 0 : seriesIndex * barWidth)
+ const rect = Skia.XYWHRect(left, top, barWidth, height)
+ if (layout === 'stacked') {
+ builder.addRect(rect)
+ } else {
+ builder.addRRect(Skia.RRectXY(rect, 1, 1))
+ }
}
return {
key: s.key,
@@ -296,7 +311,7 @@ function Bars({
color: single && variant !== 'compact' ? colors.barNeutral : s.color,
}
}),
- [series, zeroY, groupWidth, barWidth, single, colors, variant]
+ [series, zeroY, groupWidth, barWidth, single, colors, variant, layout]
)
const first = series[0]
return (
@@ -345,9 +360,9 @@ function BarHighlight({
width: number
color: string
}): ReactElement {
- const { ys } = series
+ const { ys, baseYs } = series
const x = useDerivedValue(() => (xs[sel.value] ?? 0) - width / 2)
- const span = useDerivedValue(() => barSpan(ys[sel.value] ?? zeroY, zeroY))
+ const span = useDerivedValue(() => barSpan(ys[sel.value] ?? zeroY, baseYs[sel.value] ?? zeroY))
const y = useDerivedValue(() => span.value.top)
const barHeight = useDerivedValue(() => span.value.height)
const opacity = useDerivedValue(() => (sel.value >= 0 && Number.isFinite(ys[sel.value]) ? 1 : 0))
diff --git a/products/mobile/src/ui/chart/barLayout.ts b/products/mobile/src/ui/chart/barLayout.ts
new file mode 100644
index 000000000000..183f0f44b0e4
--- /dev/null
+++ b/products/mobile/src/ui/chart/barLayout.ts
@@ -0,0 +1,35 @@
+import { BAR_BAND_PADDING } from './chartMath'
+import { bucketCount, isCompareSeries } from './chartSeries'
+import type { BarLayout, ChartSeries } from './types'
+
+const MIN_BAR_WIDTH = 6
+const MIN_STACK_WIDTH = 14
+
+export function barPageSize(plotWidth: number, seriesCount: number, layout: BarLayout): number {
+ const groupWidth = layout === 'stacked' ? MIN_STACK_WIDTH : MIN_BAR_WIDTH * Math.max(1, seriesCount)
+ return Math.max(1, Math.floor((plotWidth * (1 - BAR_BAND_PADDING)) / groupWidth))
+}
+
+export function barWindow(count: number, size: number, endOffset: number): { start: number; end: number } {
+ const end = Math.max(1, count - Math.max(0, endOffset))
+ return { start: Math.max(0, end - size), end: Math.min(count, end) }
+}
+
+export function barSegments(series: ChartSeries[], layout: BarLayout): { starts: number[]; ends: number[] }[] {
+ const positive = Array<number>(bucketCount(series)).fill(0)
+ const negative = Array<number>(positive.length).fill(0)
+ return series.map((s) => {
+ const starts: number[] = []
+ const ends: number[] = []
+ s.points.forEach((point, index) => {
+ const totals = point.value < 0 ? negative : positive
+ const start = layout === 'stacked' && !isCompareSeries(s) ? (totals[index] ?? 0) : 0
+ starts.push(start)
+ ends.push(Number.isFinite(point.value) ? start + point.value : Number.NaN)
+ if (Number.isFinite(point.value) && !isCompareSeries(s)) {
+ totals[index] = start + point.value
+ }
+ })
+ return { starts, ends }
+ })
+}
diff --git a/products/mobile/src/ui/chart/chartMath.test.ts b/products/mobile/src/ui/chart/chartMath.test.ts
index 8ed5f43824dc..6810d7fcfaae 100644
--- a/products/mobile/src/ui/chart/chartMath.test.ts
+++ b/products/mobile/src/ui/chart/chartMath.test.ts
@@ -1,7 +1,9 @@
+import { barPageSize, barSegments, barWindow } from './barLayout'
import { barSpan, yPosition } from './chartGeometry'
import {
formatAxisDate,
formatChange,
+ formatPagerDate,
formatTooltipDate,
nearestIndex,
snapToValue,
@@ -9,9 +11,48 @@ import {
xTickIndices,
yAxisTicks,
} from './chartMath'
-import type { ChartInterval, ChartKind } from './types'
+import type { ChartInterval, ChartKind, ChartSeries } from './types'
describe('chartMath', () => {
+ test.each(['grouped', 'stacked'] as const)('bar windows cover every bucket at a readable width: %s', (layout) => {
+ const size = barPageSize(300, 6, layout)
+ const indices: number[] = []
+ for (let page = 0; page < Math.ceil(31 / size); page++) {
+ const { start, end } = barWindow(31, size, page * size)
+ expect(((300 / (end - start)) * 0.75) / (layout === 'stacked' ? 1 : 6)).toBeGreaterThanOrEqual(
+ layout === 'stacked' ? 14 : 6
+ )
+ indices.push(...Array.from({ length: end - start }, (_, index) => start + index))
+ }
+ expect(indices.sort((a, b) => a - b)).toEqual(Array.from({ length: 31 }, (_, index) => index))
+ expect(barWindow(31, size, 99)).toEqual({ start: 0, end: 1 })
+ expect(barWindow(31, size + 2, size).end).toBe(barWindow(31, size, size).end)
+ })
+
+ test('stacks fit the sum, keep negative values below zero, and exclude gaps and previous periods', () => {
+ const series: ChartSeries[] = [
+ [2, -3, 0],
+ [5, -2, Number.NaN],
+ [4, 1, 0],
+ ].map((values, index) => ({
+ key: String(index),
+ label: String(index),
+ color: '#000000',
+ points: values.map((value) => ({ at: 0, value })),
+ }))
+ series.splice(1, 0, { ...(series[0] as ChartSeries), key: 'previous', compareOf: '0' })
+ const stacked = barSegments(series, 'stacked')
+ expect(stacked[2]).toEqual({ starts: [2, -3, 0], ends: [7, -5, Number.NaN] })
+ expect(stacked[3]).toEqual({ starts: [7, 0, 0], ends: [11, 1, 0] })
+ expect(
+ barSegments(
+ series.filter((s) => s.key !== '0'),
+ 'stacked'
+ )[1]?.ends
+ ).toEqual([5, -2, Number.NaN])
+ expect(barSegments(series, 'grouped')[2]).toEqual({ starts: [0, 0, 0], ends: [5, -2, Number.NaN] })
+ })
+
test.each<[string, number[], ChartKind, [number, number], number[]]>([
['small counts never get fractional ticks', [0, 1, 2, 1], 'bar', [0, 2], [0, 1, 2]],
['signed bars include zero', [-10, 0, 20], 'bar', [-10, 20], [-10, 0, 10, 20]],
@@ -62,15 +103,16 @@ describe('chartMath', () => {
expect(tooltipLeft(anchorX, 100, containerWidth, 10)).toBe(expected)
})
- test.each<[ChartInterval, string, string]>([
- ['hour', '09:05', 'Tue, Oct 13, 09:05'],
- ['day', 'Oct 13', 'Tue, Oct 13, 2026'],
- ['week', 'Oct 13', 'Oct 13 – 19, 2026'],
- ['month', 'Oct 2026', 'Oct 2026'],
- ])('formats %s dates for the axis and the tooltip', (interval, axis, tooltip) => {
+ test.each<[ChartInterval, string, string, string]>([
+ ['hour', '09:05', 'Tue, Oct 13, 09:05', 'Oct 13, 09:05'],
+ ['day', 'Oct 13', 'Tue, Oct 13, 2026', 'Oct 13'],
+ ['week', 'Oct 13', 'Oct 13 – 19, 2026', 'Oct 13'],
+ ['month', 'Oct 2026', 'Oct 2026', 'Oct 2026'],
+ ])('formats %s dates for the axis, tooltip and pager', (interval, axis, tooltip, pager) => {
const at = new Date(2026, 9, 13, 9, 5).getTime()
expect(formatAxisDate(at, interval)).toBe(axis)
expect(formatTooltipDate(at, interval)).toBe(tooltip)
+ expect(formatPagerDate(at, interval)).toBe(pager)
})
test.each<[string, Date, boolean, string]>([
diff --git a/products/mobile/src/ui/chart/chartMath.ts b/products/mobile/src/ui/chart/chartMath.ts
index 7b3abff8a24c..4bcdd3652e23 100644
--- a/products/mobile/src/ui/chart/chartMath.ts
+++ b/products/mobile/src/ui/chart/chartMath.ts
@@ -179,6 +179,12 @@ export function formatAxisDate(at: number, interval: ChartInterval): string {
}
}
+export function formatPagerDate(at: number, interval: ChartInterval): string {
+ return interval === 'hour'
+ ? `${formatMonthDay(new Date(at))}, ${formatAxisDate(at, interval)}`
+ : formatAxisDate(at, interval)
+}
+
const MINUS = '−'
function weekEnd(start: Date): Date {
diff --git a/products/mobile/src/ui/chart/types.ts b/products/mobile/src/ui/chart/types.ts
index cd5793246f87..0d72e138f7c3 100644
--- a/products/mobile/src/ui/chart/types.ts
+++ b/products/mobile/src/ui/chart/types.ts
@@ -1,6 +1,7 @@
import type { Accent } from '@/model/types'
export type ChartKind = 'line' | 'bar'
+export type BarLayout = 'grouped' | 'stacked'
export type ChartInterval = 'hour' | 'day' | 'week' | 'month'
@@ -73,6 +74,7 @@ export interface ChartCanvasSlot {
interface MetricChartBaseProps {
kind: ChartKind
+ barLayout?: BarLayout
interval: ChartInterval
/** The chart's name, for the accessibility summary. With `points`, also the tooltip row label. */
label: string
diff --git a/products/mobile/src/ui/icons/BarChartIcon.tsx b/products/mobile/src/ui/icons/BarChartIcon.tsx
new file mode 100644
index 000000000000..e6cfdcd15541
--- /dev/null
+++ b/products/mobile/src/ui/icons/BarChartIcon.tsx
@@ -0,0 +1,30 @@
+import type { ReactElement } from 'react'
+import Svg, { Rect } from 'react-native-svg'
+
+import type { BarLayout } from '@/ui/chart/types'
+import { useColors } from '@/ui/theme'
+
+import type { IconProps } from './types'
+
+export function BarChartIcon({ layout, size = 20, color }: IconProps & { layout: BarLayout }): ReactElement {
+ const colors = useColors()
+ return (
+ <Svg width={size} height={size} viewBox="0 0 24 24" fill={color ?? colors.ink}>
+ {layout === 'stacked' ? (
+ <>
+ <Rect x={3} y={4} width={7} height={7} rx={1} />
+ <Rect x={3} y={13} width={7} height={7} rx={1} />
+ <Rect x={14} y={8} width={7} height={5} rx={1} />
+ <Rect x={14} y={15} width={7} height={5} rx={1} />
+ </>
+ ) : (
+ <>
+ <Rect x={3} y={8} width={3} height={12} rx={1} />
+ <Rect x={7} y={13} width={3} height={7} rx={1} />
+ <Rect x={14} y={4} width={3} height={16} rx={1} />
+ <Rect x={18} y={10} width={3} height={10} rx={1} />
+ </>
+ )}
+ </Svg>
+ )
+}