Files
supabase/apps/studio/components/ui/Charts/BarChart.tsx
Maksym Ionutsa 028d329417 Fix/studio observability timezone labels (#54198)
## Problem

Observability date labels ignore the timezone set in the profile. They
always show the browser timezone or UTC. The header range label (for
example "Nov 27, 12:40pm → 12:50pm") uses bare `dayjs()`. The Data API
charts (Total Requests, Error Counts, Response Speed, Network Traffic)
pass `displayDateInUtc`, so the first and last timestamps under each
chart always show UTC.

## Solution

- Format the header range label with `useFormatDateTime()` on the
Database, Auth, Storage, Realtime, PostgREST and Edge Functions
observability pages.
- Remove `displayDateInUtc` from the four Data API charts in
`ApiRenderers.tsx`.
- Use `text-xs` for the date labels in `BarChart`, so they match
`ComposedChart` and `StackedBarChart`. This is a separate commit.

## Review instructions

1. Open Observability, Database, and set a timezone in your profile that
differs from your browser.
2. Check that the range label next to the date picker and the tooltip
show the same timezone.
3. Open Observability, Data API. Check that the labels under each chart
follow the profile timezone and use the same font size as the Database
charts.

<details>
<summary>Screenshots</summary>

<img width="1124" height="844" alt="CleanShot 2026-11-27 at 13 37 14@2x"
src="https://github.com/user-attachments/assets/e3d29c77-317a-4489-aa4c-1fbf4783cb57"
/>


font in Data API
<img width="318" height="72" alt="CleanShot 2026-11-27 at 13 40 19@2x"
src="https://github.com/user-attachments/assets/06e4d12f-245f-4d4e-9dc9-b7f2f7879e52"
/>
font in Database
<img width="342" height="66" alt="CleanShot 2026-11-27 at 13 41 08@2x"
src="https://github.com/user-attachments/assets/de200eb2-4351-471d-a220-bacea142b0d9"
/>


</details>


## Checklist

- [x] I have read
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
- [x] If I wrote a new docs topic or edited an existing topic, I used
the `/write-the-docs` or `/edit-the-docs` skill (not applicable, no docs
changes)
2026-11-27 16:39:47 +01:00

249 lines
7.5 KiB
TypeScript

import { ComponentProps, useMemo, useState } from 'react'
import {
Bar,
CartesianGrid,
Cell,
Legend,
Line,
BarChart as RechartBarChart,
ComposedChart as RechartComposedChart,
Tooltip,
XAxis,
YAxis,
} from 'recharts'
import type { CategoricalChartState } from 'recharts/types/chart/types'
import { ChartHeader } from './ChartHeader'
import type { CommonChartProps, Datum } from './Charts.types'
import { numberFormatter, useChartSize } from './Charts.utils'
import { NoDataPlaceholder } from './NoDataPlaceholder'
import { useChartHoverState } from './useChartHoverState'
import { CHART_COLORS, DateTimeFormats } from '@/components/ui/Charts/Charts.constants'
import { formatDateTime, useFormatDateTime } from '@/lib/datetime'
export interface BarChartProps<D = Datum> extends CommonChartProps<D> {
yAxisKey: string
xAxisKey: string
customDateFormat?: string
displayDateInUtc?: boolean
onBarClick?: (datum: D, tooltipData?: CategoricalChartState) => void
emptyStateMessage?: string
showLegend?: boolean
xAxisIsDate?: boolean
XAxisProps?: ComponentProps<typeof XAxis>
YAxisProps?: ComponentProps<typeof YAxis>
showGrid?: boolean
chartStyle?: 'bar' | 'line'
syncId?: string
}
function BarChart<D extends Datum = Datum>({
data,
yAxisKey,
xAxisKey,
format,
customDateFormat = DateTimeFormats.FULL,
title,
highlightedValue,
highlightedLabel,
displayDateInUtc,
minimalHeader,
valuePrecision,
className = '',
size = 'normal',
emptyStateMessage,
onBarClick,
showLegend = false,
xAxisIsDate = true,
XAxisProps,
YAxisProps,
showGrid = false,
syncId,
chartStyle = 'bar',
}: BarChartProps<D>) {
const Chart = chartStyle === 'line' ? RechartComposedChart : RechartBarChart
const { hoveredIndex, isHovered, isCurrentChart, setHover, clearHover } =
useChartHoverState('default')
const { Container } = useChartSize(size)
const [focusDataIndex, setFocusDataIndex] = useState<number | null>(null)
// Transform data to ensure yAxisKey values are numbers
const transformedData = useMemo(() => {
return data.map((item) => ({
...item,
[yAxisKey]: typeof item[yAxisKey] === 'string' ? Number(item[yAxisKey]) : item[yAxisKey],
}))
}, [data, yAxisKey])
// Default props
const _XAxisProps = XAxisProps || {
interval: data.length - 2,
angle: 0,
tick: false,
}
const _YAxisProps = YAxisProps || {
tickFormatter: (value) => numberFormatter(value, valuePrecision),
tick: false,
width: 0,
}
// When `displayDateInUtc` is set the chart explicitly wants UTC labels.
// Otherwise honour the user's selected timezone via the picker, which
// `useFormatDateTime` reads from context.
const formatPickerDate = useFormatDateTime()
const formatChartDate = (value: number | string) =>
displayDateInUtc
? formatDateTime(value, { tz: 'UTC', format: customDateFormat })
: formatPickerDate(value, customDateFormat)
function getHeaderLabel() {
if (!xAxisIsDate) {
if (!focusDataIndex) return highlightedLabel
return data[focusDataIndex]?.[xAxisKey]
}
return (
(focusDataIndex !== null &&
data &&
data[focusDataIndex] !== undefined &&
formatChartDate(data[focusDataIndex][xAxisKey] as number | string)) ||
highlightedLabel
)
}
const resolvedHighlightedLabel = getHeaderLabel()
const resolvedHighlightedValue =
focusDataIndex !== null ? data[focusDataIndex]?.[yAxisKey] : highlightedValue
if (data.length === 0) {
return (
<NoDataPlaceholder
message={emptyStateMessage}
description="It may take up to 24 hours for data to refresh"
size={size}
className={className}
attribute={title}
format={format}
/>
)
}
return (
<div className={['flex flex-col gap-y-3', className].join(' ')}>
<ChartHeader
title={title}
format={format}
customDateFormat={customDateFormat}
highlightedValue={resolvedHighlightedValue}
highlightedLabel={resolvedHighlightedLabel}
minimalHeader={minimalHeader}
syncId={syncId}
data={data}
xAxisKey={xAxisKey}
yAxisKey={yAxisKey}
xAxisIsDate={xAxisIsDate}
displayDateInUtc={displayDateInUtc}
valuePrecision={valuePrecision}
attributes={[]}
/>
<Container>
<Chart
data={transformedData}
className="overflow-visible"
onMouseMove={(e: any) => {
if (e.activeTooltipIndex !== focusDataIndex) {
setFocusDataIndex(e.activeTooltipIndex)
}
setHover(e.activeTooltipIndex)
}}
onMouseLeave={() => {
setFocusDataIndex(null)
clearHover()
}}
onClick={(tooltipData) => {
const datum = tooltipData?.activePayload?.[0]?.payload
if (onBarClick) onBarClick(datum, tooltipData)
}}
>
{showLegend && <Legend />}
{showGrid && <CartesianGrid stroke={CHART_COLORS.AXIS} />}
<YAxis
{..._YAxisProps}
axisLine={{ stroke: CHART_COLORS.AXIS }}
tickLine={{ stroke: CHART_COLORS.AXIS }}
key={yAxisKey}
/>
<XAxis
{..._XAxisProps}
axisLine={{ stroke: CHART_COLORS.AXIS }}
tickLine={{ stroke: CHART_COLORS.AXIS }}
key={xAxisKey}
/>
<Tooltip
content={(_props) =>
syncId && isHovered && isCurrentChart && hoveredIndex !== null ? (
<div className="bg-black/90 text-white p-2 rounded-sm text-xs">
<div className="font-medium">
{formatChartDate(data[hoveredIndex]?.[xAxisKey] as number | string)}
</div>
<div>
{numberFormatter(Number(data[hoveredIndex]?.[yAxisKey]) || 0, valuePrecision)}
{typeof format === 'string' ? format : ''}
</div>
</div>
) : null
}
/>
{chartStyle === 'line' ? (
<Line
dataKey={yAxisKey}
type="linear"
stroke={CHART_COLORS.GREEN_1}
dot={false}
animationDuration={300}
/>
) : (
<Bar
dataKey={yAxisKey}
fill={CHART_COLORS.GREEN_1}
animationDuration={300}
maxBarSize={48}
>
{data?.map((_entry: D, index: number) => (
<Cell
key={`cell-${index}`}
className={`transition-all duration-300 ${onBarClick ? 'cursor-pointer' : ''}`}
fill={
focusDataIndex === index || focusDataIndex === null
? CHART_COLORS.GREEN_1
: CHART_COLORS.GREEN_2
}
enableBackground={12}
/>
))}
</Bar>
)}
</Chart>
</Container>
{data && (
<div className="text-foreground-lighter -mt-10 flex items-center justify-between text-xs">
<span>
{xAxisIsDate
? formatChartDate(data[0][xAxisKey] as number | string)
: data[0][xAxisKey]}
</span>
<span>
{xAxisIsDate
? formatChartDate(data[data?.length - 1]?.[xAxisKey] as number | string)
: data[data?.length - 1]?.[xAxisKey]}
</span>
</div>
)}
</div>
)
}
export default BarChart