The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
add syncing between charts (#37599)
Jordi Enric28e5a0ef19be
diff --git a/apps/studio/components/ui/Charts/AreaChart.tsx b/apps/studio/components/ui/Charts/AreaChart.tsxindex c5820d5b7e9..035582d4a22 100644--- a/apps/studio/components/ui/Charts/AreaChart.tsx+++ b/apps/studio/components/ui/Charts/AreaChart.tsx@@ -1,6 +1,7 @@import dayjs from 'dayjs'import { useState } from 'react'import { Area, AreaChart as RechartAreaChart, Tooltip, XAxis } from 'recharts'+import { useChartSync } from './useChartSync'import { CHART_COLORS, DateTimeFormats } from 'components/ui/Charts/Charts.constants'import ChartHeader from './ChartHeader'@@ -14,6 +15,7 @@ export interface AreaChartProps<D = Datum> extends CommonChartProps<D> {format?: stringcustomDateFormat?: stringdisplayDateInUtc?: boolean+ syncId?: string}const AreaChart = ({@@ -30,8 +32,14 @@ const AreaChart = ({className = '',valuePrecision,size = 'normal',+ syncId,}: AreaChartProps) => {const { Container } = useChartSize(size)+ const {+ state: syncState,+ updateState: updateSyncState,+ clearState: clearSyncState,+ } = useChartSync(syncId)const [focusDataIndex, setFocusDataIndex] = useState<number | null>(null)const day = (value: number | string) => (displayDateInUtc ? dayjs(value).utc() : dayjs(value))@@ -70,6 +78,14 @@ const AreaChart = ({}highlightedLabel={resolvedHighlightedLabel}minimalHeader={minimalHeader}+ syncId={syncId}+ data={data}+ xAxisKey={xAxisKey}+ yAxisKey={yAxisKey}+ xAxisIsDate={true}+ displayDateInUtc={displayDateInUtc}+ valuePrecision={valuePrecision}+ attributes={[]}/><Container><RechartAreaChart@@ -81,13 +97,27 @@ const AreaChart = ({bottom: 0,}}className="overflow-visible"- // mouse hover focusing logiconMouseMove={(e: any) => {if (e.activeTooltipIndex !== focusDataIndex) {setFocusDataIndex(e.activeTooltipIndex)}++ if (syncId) {+ updateSyncState({+ activeIndex: e.activeTooltipIndex,+ activePayload: e.activePayload,+ activeLabel: e.activeLabel,+ isHovering: true,+ })+ }+ }}+ onMouseLeave={() => {+ setFocusDataIndex(null)++ if (syncId) {+ clearSyncState()+ }}}- onMouseLeave={() => setFocusDataIndex(null)}><defs><linearGradient id="colorUv" x1="0" y1="0" x2="0" y2="1">@@ -105,7 +135,24 @@ const AreaChart = ({axisLine={{ stroke: CHART_COLORS.AXIS }}tickLine={{ stroke: CHART_COLORS.AXIS }}/>- <Tooltip content={() => null} />+ <Tooltip+ content={(props) =>+ syncId && syncState.isHovering && syncState.activeIndex !== null ? (+ <div className="bg-black/90 text-white p-2 rounded text-xs">+ <div className="font-medium">+ {dayjs(data[syncState.activeIndex]?.[xAxisKey]).format(customDateFormat)}+ </div>+ <div>+ {numberFormatter(+ Number(data[syncState.activeIndex]?.[yAxisKey]) || 0,+ valuePrecision+ )}+ {format}+ </div>+ </div>+ ) : null+ }+ /><Areatype="monotone"dataKey={yAxisKey}diff --git a/apps/studio/components/ui/Charts/BarChart.tsx b/apps/studio/components/ui/Charts/BarChart.tsxindex 9a6f6afefcf..c406134d3ee 100644--- a/apps/studio/components/ui/Charts/BarChart.tsx+++ b/apps/studio/components/ui/Charts/BarChart.tsx@@ -1,5 +1,6 @@import dayjs from 'dayjs'import { ComponentProps, useState, useMemo } from 'react'+import { useChartSync } from './useChartSync'import {Bar,CartesianGrid,@@ -30,6 +31,7 @@ export interface BarChartProps<D = Datum> extends CommonChartProps<D> {XAxisProps?: ComponentProps<typeof XAxis>YAxisProps?: ComponentProps<typeof YAxis>showGrid?: boolean+ syncId?: string}const BarChart = ({@@ -53,8 +55,14 @@ const BarChart = ({XAxisProps,YAxisProps,showGrid = false,+ syncId,}: BarChartProps) => {const { Container } = useChartSize(size)+ const {+ state: syncState,+ updateState: updateSyncState,+ clearState: clearSyncState,+ } = useChartSync(syncId)const [focusDataIndex, setFocusDataIndex] = useState<number | null>(null)// Transform data to ensure yAxisKey values are numbers@@ -125,20 +133,41 @@ const BarChart = ({}highlightedLabel={resolvedHighlightedLabel}minimalHeader={minimalHeader}+ syncId={syncId}+ data={data}+ xAxisKey={xAxisKey}+ yAxisKey={yAxisKey}+ xAxisIsDate={xAxisIsDate}+ displayDateInUtc={displayDateInUtc}+ valuePrecision={valuePrecision}+ attributes={[]}/><Container><RechartBarChartdata={transformedData}className="overflow-visible"- // mouse hover focusing logiconMouseMove={(e: any) => {if (e.activeTooltipIndex !== focusDataIndex) {setFocusDataIndex(e.activeTooltipIndex)}++ if (syncId) {+ updateSyncState({+ activeIndex: e.activeTooltipIndex,+ activePayload: e.activePayload,+ activeLabel: e.activeLabel,+ isHovering: true,+ })+ }+ }}+ onMouseLeave={() => {+ setFocusDataIndex(null)++ if (syncId) {+ clearSyncState()+ }}}- onMouseLeave={() => setFocusDataIndex(null)}onClick={(tooltipData) => {- // receives tooltip data https://github.com/recharts/recharts/blob/2a3405ff64a0c050d2cf94c36f0beef738d9e9c2/src/chart/generateCategoricalChart.tsxconst datum = tooltipData?.activePayload?.[0]?.payloadif (onBarClick) onBarClick(datum, tooltipData)}}@@ -157,12 +186,28 @@ const BarChart = ({tickLine={{ stroke: CHART_COLORS.AXIS }}key={xAxisKey}/>- <Tooltip content={() => null} />+ <Tooltip+ content={(props) =>+ syncId && syncState.isHovering && syncState.activeIndex !== null ? (+ <div className="bg-black/90 text-white p-2 rounded text-xs">+ <div className="font-medium">+ {dayjs(data[syncState.activeIndex]?.[xAxisKey]).format(customDateFormat)}+ </div>+ <div>+ {numberFormatter(+ Number(data[syncState.activeIndex]?.[yAxisKey]) || 0,+ valuePrecision+ )}+ {typeof format === 'string' ? format : ''}+ </div>+ </div>+ ) : null+ }+ /><BardataKey={yAxisKey}fill={CHART_COLORS.GREEN_1}animationDuration={300}- // Max bar size required to prevent bars from expanding to max width.maxBarSize={48}>{data?.map((_entry: Datum, index: any) => (diff --git a/apps/studio/components/ui/Charts/ChartHeader.tsx b/apps/studio/components/ui/Charts/ChartHeader.tsxindex e15ee1d9eed..28ca8a92a98 100644--- a/apps/studio/components/ui/Charts/ChartHeader.tsx+++ b/apps/studio/components/ui/Charts/ChartHeader.tsx@@ -1,6 +1,11 @@import { Button, Tooltip, TooltipContent, TooltipTrigger } from 'ui'import { Activity, BarChartIcon, GitCommitHorizontalIcon, InfoIcon } from 'lucide-react'import Link from 'next/link'+import { useEffect, useState } from 'react'+import dayjs from 'dayjs'+import { formatBytes } from 'lib/helpers'+import { useChartSync } from './useChartSync'+import { numberFormatter } from './Charts.utils'export interface ChartHeaderProps {title?: string@@ -17,6 +22,15 @@ export interface ChartHeaderProps {showMaxValue?: booleansetShowMaxValue?: (value: boolean) => voiddocsUrl?: string+ syncId?: string+ data?: any[]+ xAxisKey?: string+ yAxisKey?: string+ xAxisIsDate?: boolean+ valuePrecision?: number+ shouldFormatBytes?: boolean+ isNetworkChart?: boolean+ attributes?: any[]}const ChartHeader = ({@@ -32,7 +46,100 @@ const ChartHeader = ({showMaxValue = false,setShowMaxValue,docsUrl,+ syncId,+ data,+ xAxisKey,+ yAxisKey,+ xAxisIsDate = true,+ displayDateInUtc,+ customDateFormat,+ valuePrecision = 2,+ shouldFormatBytes = false,+ isNetworkChart = false,+ attributes,}: ChartHeaderProps) => {+ const { state: syncState } = useChartSync(syncId)+ const [localHighlightedValue, setLocalHighlightedValue] = useState(highlightedValue)+ const [localHighlightedLabel, setLocalHighlightedLabel] = useState(highlightedLabel)++ const formatHighlightedValue = (value: any) => {+ if (typeof value !== 'number') {+ return value+ }++ if (shouldFormatBytes) {+ const bytesValue = isNetworkChart ? Math.abs(value) : value+ return formatBytes(bytesValue, valuePrecision)+ }++ return numberFormatter(value, valuePrecision)+ }++ useEffect(() => {+ if (syncId && syncState.activeIndex !== null && data && xAxisKey && yAxisKey) {+ const activeDataPoint = data[syncState.activeIndex]+ if (activeDataPoint) {+ // For stacked charts, we need to calculate the total of all attributes+ // that should be included in the total (excluding reference lines, max values, etc.)+ let newValue = activeDataPoint[yAxisKey]++ // If this is a stacked chart with multiple attributes, calculate the total+ if (attributes && attributes.length > 1) {+ const attributesToIgnore =+ attributes+ ?.filter((a) => a.omitFromTotal || a.isMaxValue || a.provider === 'reference-line')+ ?.map((a) => a.attribute) ?? []++ const totalValue = Object.entries(activeDataPoint)+ .filter(([key, value]) => {+ // Include only numeric values that are not in the ignore list+ return (+ typeof value === 'number' &&+ key !== 'timestamp' &&+ key !== 'period_start' &&+ !attributesToIgnore.includes(key) &&+ attributes.some((attr) => attr.attribute === key && attr.enabled !== false)+ )+ })+ .reduce((sum, [_, value]) => sum + (value as number), 0)++ newValue = totalValue+ }++ setLocalHighlightedValue(newValue)++ // Update highlighted label based on sync state+ let newLabel = highlightedLabel+ if (xAxisIsDate && activeDataPoint[xAxisKey]) {+ const day = (value: number | string) =>+ displayDateInUtc ? dayjs(value).utc() : dayjs(value)+ newLabel = day(activeDataPoint[xAxisKey]).format(+ customDateFormat || 'YYYY-MM-DD HH:mm:ss'+ )+ } else if (activeDataPoint[xAxisKey]) {+ newLabel = activeDataPoint[xAxisKey]+ }+ setLocalHighlightedLabel(newLabel)+ }+ } else {+ // Reset to original values when not syncing+ setLocalHighlightedValue(highlightedValue)+ setLocalHighlightedLabel(highlightedLabel)+ }+ }, [+ syncState,+ syncId,+ data,+ xAxisKey,+ yAxisKey,+ xAxisIsDate,+ displayDateInUtc,+ customDateFormat,+ highlightedValue,+ highlightedLabel,+ attributes,+ ])+const chartTitle = (<div className="flex flex-row items-center gap-x-2"><h3 className={'text-foreground-lighter ' + (minimalHeader ? 'text-xs' : 'text-sm')}>@@ -61,14 +168,14 @@ const ChartHeader = ({<h4className={`text-foreground text-xl font-normal ${minimalHeader ? 'text-base' : 'text-2xl'}`}>- {highlightedValue !== undefined && highlightedValue}+ {localHighlightedValue !== undefined && formatHighlightedValue(localHighlightedValue)}{format === 'seconds' ? ' ' : ''}<span className="text-lg">- {typeof format === 'function' ? format(highlightedValue) : format}+ {typeof format === 'function' ? format(localHighlightedValue) : format}</span></h4>)- const label = <h4 className="text-foreground-lighter text-xs">{highlightedLabel}</h4>+ const label = <h4 className="text-foreground-lighter text-xs">{localHighlightedLabel}</h4>if (minimalHeader) {return (@@ -82,12 +189,16 @@ const ChartHeader = ({)}+ const hasHighlightedValue = highlightedValue !== undefined && !hideHighlightedValue+return (<div className="flex-grow flex justify-between items-start min-h-16"><div className="flex flex-col">{title && chartTitle}- {highlightedValue !== undefined && !hideHighlightedValue && highlighted}- {label}+ <div className="h-4">+ {hasHighlightedValue && highlighted}+ {label}+ </div></div><div className="flex items-center gap-2">{!hideChartType && onChartStyleChange && (diff --git a/apps/studio/components/ui/Charts/ComposedChart.tsx b/apps/studio/components/ui/Charts/ComposedChart.tsxindex 5f891992832..b7b052b4159 100644--- a/apps/studio/components/ui/Charts/ComposedChart.tsx+++ b/apps/studio/components/ui/Charts/ComposedChart.tsx@@ -4,6 +4,7 @@ import dayjs from 'dayjs'import { formatBytes } from 'lib/helpers'import { useTheme } from 'next-themes'import { ComponentProps, useEffect, useState } from 'react'+import { useChartSync } from './useChartSync'import {Area,Bar,@@ -101,6 +102,11 @@ export default function ComposedChart({docsUrl,}: ComposedChartProps) {const { resolvedTheme } = useTheme()+ const {+ state: syncState,+ updateState: updateSyncState,+ clearState: clearSyncState,+ } = useChartSync(syncId)const [_activePayload, setActivePayload] = useState<any>(null)const [_showMaxValue, setShowMaxValue] = useState(showMaxValue)const [focusDataIndex, setFocusDataIndex] = useState<number | null>(null)@@ -108,7 +114,6 @@ export default function ComposedChart({const [isActiveHoveredChart, setIsActiveHoveredChart] = useState(false)const isDarkMode = resolvedTheme?.includes('dark')- // Update chart colors when theme changesuseEffect(() => {updateStackedChartColors(isDarkMode ?? false)}, [resolvedTheme])@@ -122,16 +127,13 @@ export default function ComposedChart({return ''}- // Timestamps from auth logs can be in microsecondsif (typeof ts === 'number' && ts > 1e14) {return day(ts / 1000).format(customDateFormat)}- // dayjs can handle ISO strings and millisecond numbersreturn day(ts).format(customDateFormat)}- // Default propsconst _XAxisProps = XAxisProps || {interval: data.length - 2,angle: 0,@@ -161,46 +163,71 @@ export default function ComposedChart({)}+ function computeHighlightedValue() {+ const maxAttribute = attributes.find((a) => a.isMaxValue)+ const referenceLines = attributes.filter(+ (attribute) => attribute?.provider === 'reference-line'+ )++ const attributesToIgnore =+ attributes?.filter((a) => a.omitFromTotal)?.map((a) => a.attribute) ?? []+ const attributesToIgnoreFromTotal = [+ ...attributesToIgnore,+ ...(referenceLines?.map((a: MultiAttribute) => a.attribute) ?? []),+ ...(maxAttribute?.attribute ? [maxAttribute?.attribute] : []),+ ]++ const lastDataPoint = data[data.length - 1]+ ? Object.entries(data[data.length - 1])+ .map(([key, value]) => ({+ dataKey: key,+ value: value as number,+ }))+ .filter(+ (entry) =>+ entry.dataKey !== 'timestamp' &&+ entry.dataKey !== 'period_start' &&+ attributes.some((attr) => attr.attribute === entry.dataKey && attr.enabled !== false)+ )+ : undefined++ if (focusDataIndex !== null) {+ return showTotal+ ? calculateTotalChartAggregate(_activePayload, attributesToIgnoreFromTotal)+ : data[focusDataIndex]?.[yAxisKey]+ }++ if (showTotal && lastDataPoint) {+ return calculateTotalChartAggregate(lastDataPoint, attributesToIgnoreFromTotal)+ }++ return highlightedValue+ }++ function formatHighlightedValue(value: any) {+ if (typeof value !== 'number') {+ return value+ }++ if (shouldFormatBytes) {+ const bytesValue = isNetworkChart ? Math.abs(value) : value+ return formatBytes(bytesValue, valuePrecision)+ }++ return numberFormatter(value, valuePrecision)+ }+const maxAttribute = attributes.find((a) => a.isMaxValue)const maxAttributeData = {name: maxAttribute?.attribute,color: CHART_COLORS.REFERENCE_LINE,}- const lastDataPoint = !!data[data.length - 1]- ? Object.entries(data[data.length - 1])- .map(([key, value]) => ({- dataKey: key,- value: value as number,- }))- .filter(- (entry) =>- entry.dataKey !== 'timestamp' &&- entry.dataKey !== 'period_start' &&- attributes.some((attr) => attr.attribute === entry.dataKey && attr.enabled !== false)- )- : undefinedconst referenceLines = attributes.filter((attribute) => attribute?.provider === 'reference-line')const resolvedHighlightedLabel = getHeaderLabel()- const attributesToIgnore =- attributes?.filter((a) => a.omitFromTotal)?.map((a) => a.attribute) ?? []-- const attributesToIgnoreFromTotal = [- ...attributesToIgnore,- ...(referenceLines?.map((a: MultiAttribute) => a.attribute) ?? []),- ...(maxAttribute?.attribute ? [maxAttribute?.attribute] : []),- ]-- const resolvedHighlightedValue =- focusDataIndex !== null- ? showTotal- ? calculateTotalChartAggregate(_activePayload, attributesToIgnoreFromTotal)- : data[focusDataIndex]?.[yAxisKey]- : showTotal && lastDataPoint- ? calculateTotalChartAggregate(lastDataPoint, attributesToIgnoreFromTotal)- : highlightedValue+ const resolvedHighlightedValue = computeHighlightedValue()const showHighlightActions =chartHighlight?.coordinates.left &&@@ -280,16 +307,7 @@ export default function ComposedChart({title={title}format={format}customDateFormat={customDateFormat}- highlightedValue={- typeof resolvedHighlightedValue === 'number'- ? shouldFormatBytes- ? formatBytes(- isNetworkChart ? Math.abs(resolvedHighlightedValue) : resolvedHighlightedValue,- valuePrecision- )- : numberFormatter(resolvedHighlightedValue, valuePrecision)- : resolvedHighlightedValue- }+ highlightedValue={formatHighlightedValue(resolvedHighlightedValue)}highlightedLabel={resolvedHighlightedLabel}minimalHeader={minimalHeader}hideChartType={hideChartType}@@ -299,6 +317,16 @@ export default function ComposedChart({setShowMaxValue={maxAttribute ? setShowMaxValue : undefined}hideHighlightedValue={hideHighlightedValue}docsUrl={docsUrl}+ syncId={syncId}+ data={data}+ xAxisKey={xAxisKey}+ yAxisKey={yAxisKey}+ xAxisIsDate={xAxisIsDate}+ displayDateInUtc={displayDateInUtc}+ valuePrecision={valuePrecision}+ shouldFormatBytes={shouldFormatBytes}+ isNetworkChart={isNetworkChart}+ attributes={attributes}/><Container className="relative z-10"><RechartComposedChart@@ -310,6 +338,16 @@ export default function ComposedChart({setFocusDataIndex(e.activeTooltipIndex)setActivePayload(e.activePayload)}++ if (syncId) {+ updateSyncState({+ activeIndex: e.activeTooltipIndex,+ activePayload: e.activePayload,+ activeLabel: e.activeLabel,+ isHovering: true,+ })+ }+const activeTimestamp = data[e.activeTooltipIndex]?.timestampchartHighlight?.handleMouseMove({activeLabel: activeTimestamp?.toString(),@@ -328,6 +366,10 @@ export default function ComposedChart({setIsActiveHoveredChart(false)setFocusDataIndex(null)setActivePayload(null)++ if (syncId) {+ clearSyncState()+ }}}onClick={(tooltipData) => {const datum = tooltipData?.activePayload?.[0]?.payload@@ -362,7 +404,7 @@ export default function ComposedChart({attributes={attributes}valuePrecision={valuePrecision}showTotal={showTotal}- isActiveHoveredChart={isActiveHoveredChart}+ isActiveHoveredChart={isActiveHoveredChart || (!!syncId && syncState.isHovering)}/>) : null}@@ -404,7 +446,6 @@ export default function ComposedChart({name={attributes?.find((a) => a.attribute === attribute.name)?.label || attribute.name}- // Show dot for the first attribute when a point is focuseddot={false}/>))}diff --git a/apps/studio/components/ui/Charts/ComposedChartHandler.tsx b/apps/studio/components/ui/Charts/ComposedChartHandler.tsxindex 400a7a40afc..785874c9229 100644--- a/apps/studio/components/ui/Charts/ComposedChartHandler.tsx+++ b/apps/studio/components/ui/Charts/ComposedChartHandler.tsx@@ -43,6 +43,7 @@ export interface ComposedChartHandlerProps {isVisible?: booleandocsUrl?: stringhide?: boolean+ syncId?: string}/**@@ -113,6 +114,7 @@ const ComposedChartHandler = ({valuePrecision,isVisible = true,id,+ syncId,...otherProps}: PropsWithChildren<ComposedChartHandlerProps>) => {const router = useRouter()@@ -124,7 +126,6 @@ const ComposedChartHandler = ({const databaseIdentifier = state.selectedDatabaseId- // Use the custom hook at the top level of the componentconst attributeQueries = useAttributeQueries(attributes,ref,@@ -136,7 +137,6 @@ const ComposedChartHandler = ({isVisible)- // Combine all the data into a single datasetconst combinedData = useMemo(() => {if (data) return data@@ -146,7 +146,6 @@ const ComposedChartHandler = ({const hasError = attributeQueries.some((query: any) => !query.data)if (hasError) return undefined- // Get all unique timestamps from all datasetsconst timestamps = new Set<string>()attributeQueries.forEach((query: any) => {query.data?.data?.forEach((point: any) => {@@ -160,32 +159,26 @@ const ComposedChartHandler = ({(_, index) => attributes[index].provider === 'reference-line')- // Combine data points for each timestampconst combined = Array.from(timestamps).sort().map((timestamp) => {const point: any = { timestamp }- // Add regular attributesattributes.forEach((attr, index) => {if (!attr) return- // Handle custom value attributes (like disk size)if (attr.customValue !== undefined) {point[attr.attribute] = attr.customValuereturn}- // Skip reference line attributes here, we'll add them belowif (attr.provider === 'reference-line') returnconst queryData = attributeQueries[index]?.data?.dataconst matchingPoint = queryData?.find((p: any) => p.period_start === timestamp)let value = matchingPoint?.[attr.attribute] ?? 0- // Apply value manipulation if providedif (attr.manipulateValue && typeof attr.manipulateValue === 'function') {- // Ensure value is a number before manipulationconst numericValue = typeof value === 'number' ? value : Number(value) || 0value = attr.manipulateValue(numericValue)}@@ -193,7 +186,6 @@ const ComposedChartHandler = ({point[attr.attribute] = value})- // Add reference line values for each timestampreferenceLineQueries.forEach((query: any) => {const attr = query.data.attributeconst value = query.data.total@@ -213,7 +205,6 @@ const ComposedChartHandler = ({const loading = isLoading || attributeQueries.some((query: any) => query.isLoading)- // Calculate highlighted value based on the first attribute's dataconst _highlightedValue = useMemo(() => {if (highlightedValue !== undefined) return highlightedValue@@ -266,7 +257,6 @@ const ComposedChartHandler = ({)}- // Rest of the component remains similar, but pass all attributes to chartsreturn (<PanelnoMargin@@ -297,6 +287,7 @@ const ComposedChartHandler = ({updateDateRange={updateDateRange}valuePrecision={valuePrecision}hideChartType={hideChartType}+ syncId={syncId}{...otherProps}/></Panel.Content>@@ -348,7 +339,7 @@ const useAttributeQueries = (return {data: {- data: [], // Will be populated in combinedData+ data: [],attribute: line.attribute,total: value,maximum: value,diff --git a/apps/studio/components/ui/Charts/StackedBarChart.tsx b/apps/studio/components/ui/Charts/StackedBarChart.tsxindex 1bf9b9a4528..9d25d99b644 100644--- a/apps/studio/components/ui/Charts/StackedBarChart.tsx+++ b/apps/studio/components/ui/Charts/StackedBarChart.tsx@@ -2,6 +2,7 @@ import { useState } from 'react'import { Bar, BarChart, Cell, Legend, Tooltip, XAxis } from 'recharts'import dayjs from 'dayjs'import utc from 'dayjs/plugin/utc'+import { useChartSync } from './useChartSync'import ChartHeader from './ChartHeader'import {CHART_COLORS,@@ -32,6 +33,7 @@ interface Props extends CommonChartProps<any> {hideLegend?: booleanhideHeader?: booleanstackColors?: ValidStackColor[]+ syncId?: string}const StackedBarChart: React.FC<Props> = ({size,@@ -53,8 +55,14 @@ const StackedBarChart: React.FC<Props> = ({hideLegend = false,hideHeader = false,stackColors = DEFAULT_STACK_COLORS,+ syncId,}) => {const { Container } = useChartSize(size)+ const {+ updateState: updateSyncState,+ clearState: clearSyncState,+ state: syncState,+ } = useChartSync(syncId)const { dataKeys, stackedData, percentagesStackedData } = useStacked({data,xAxisKey,@@ -91,6 +99,14 @@ const StackedBarChart: React.FC<Props> = ({: resolvedHighlightedValue}highlightedLabel={resolvedHighlightedLabel}+ syncId={syncId}+ data={data}+ xAxisKey={xAxisKey}+ yAxisKey={yAxisKey}+ xAxisIsDate={xAxisFormatAsDate}+ displayDateInUtc={displayDateInUtc}+ valuePrecision={valuePrecision}+ attributes={[]}/>)}<Container>@@ -108,8 +124,23 @@ const StackedBarChart: React.FC<Props> = ({if (e.activeTooltipIndex !== focusDataIndex) {setFocusDataIndex(e.activeTooltipIndex)}++ if (syncId) {+ updateSyncState({+ activeIndex: e.activeTooltipIndex,+ activePayload: e.activePayload,+ activeLabel: e.activeLabel,+ isHovering: true,+ })+ }+ }}+ onMouseLeave={() => {+ setFocusDataIndex(null)++ if (syncId) {+ clearSyncState()+ }}}- onMouseLeave={() => setFocusDataIndex(null)}>{!hideLegend && (<Legend@@ -174,6 +205,7 @@ const StackedBarChart: React.FC<Props> = ({fontSize: '12px',}}wrapperClassName="bg-gray-600 rounded min-w-md"+ active={!!syncId && syncState.isHovering}/></BarChart></Container>diff --git a/apps/studio/components/ui/Charts/useChartSync.test.tsx b/apps/studio/components/ui/Charts/useChartSync.test.tsxnew file mode 100644index 00000000000..9f12b06e882--- /dev/null+++ b/apps/studio/components/ui/Charts/useChartSync.test.tsx@@ -0,0 +1,153 @@+import { renderHook, act } from '@testing-library/react'+import { describe, it, expect, beforeEach } from 'vitest'+import { useChartSync, cleanupChartSync } from './useChartSync'++describe('useChartSync', () => {+ beforeEach(() => {+ cleanupChartSync('test-sync-1')+ cleanupChartSync('test-sync-2')+ })++ it('should initialize with default state', () => {+ const { result } = renderHook(() => useChartSync('test-sync-1'))++ expect(result.current.state).toEqual({+ activeIndex: null,+ activePayload: null,+ activeLabel: null,+ isHovering: false,+ })+ })++ it('should update state correctly', () => {+ const { result } = renderHook(() => useChartSync('test-sync-1'))++ act(() => {+ result.current.updateState({+ activeIndex: 5,+ activePayload: { test: 'data' },+ activeLabel: 'test-label',+ isHovering: true,+ })+ })++ expect(result.current.state).toEqual({+ activeIndex: 5,+ activePayload: { test: 'data' },+ activeLabel: 'test-label',+ isHovering: true,+ })+ })++ it('should clear state correctly', () => {+ const { result } = renderHook(() => useChartSync('test-sync-1'))++ // First update the state+ act(() => {+ result.current.updateState({+ activeIndex: 5,+ activePayload: { test: 'data' },+ activeLabel: 'test-label',+ isHovering: true,+ })+ })++ // Then clear it+ act(() => {+ result.current.clearState()+ })++ expect(result.current.state).toEqual({+ activeIndex: null,+ activePayload: null,+ activeLabel: null,+ isHovering: false,+ })+ })++ it('should sync state between multiple hooks with same syncId', () => {+ const { result: result1 } = renderHook(() => useChartSync('test-sync-1'))+ const { result: result2 } = renderHook(() => useChartSync('test-sync-1'))++ act(() => {+ result1.current.updateState({+ activeIndex: 10,+ activePayload: { test: 'data' },+ activeLabel: 'test-label',+ isHovering: true,+ })+ })++ // Both hooks should have the same state+ expect(result1.current.state.activeIndex).toBe(10)+ expect(result2.current.state.activeIndex).toBe(10)+ })++ it('should not sync state between hooks with different syncId', () => {+ const { result: result1 } = renderHook(() => useChartSync('test-sync-1'))+ const { result: result2 } = renderHook(() => useChartSync('test-sync-2'))++ act(() => {+ result1.current.updateState({+ activeIndex: 10,+ activePayload: { test: 'data' },+ activeLabel: 'test-label',+ isHovering: true,+ })+ })++ // Only the first hook should have updated state+ expect(result1.current.state.activeIndex).toBe(10)+ expect(result2.current.state.activeIndex).toBe(null)+ })++ it('should handle partial state updates', () => {+ const { result } = renderHook(() => useChartSync('test-sync-1'))++ // Set initial state+ act(() => {+ result.current.updateState({+ activeIndex: 5,+ activePayload: { test: 'data' },+ activeLabel: 'test-label',+ isHovering: true,+ })+ })++ // Update only some fields+ act(() => {+ result.current.updateState({+ activeIndex: 10,+ isHovering: false,+ })+ })++ expect(result.current.state).toEqual({+ activeIndex: 10,+ activePayload: { test: 'data' },+ activeLabel: 'test-label',+ isHovering: false,+ })+ })++ it('should handle undefined syncId', () => {+ const { result } = renderHook(() => useChartSync(undefined))++ act(() => {+ result.current.updateState({+ activeIndex: 5,+ activePayload: { test: 'data' },+ activeLabel: 'test-label',+ isHovering: true,+ })+ })++ // State should remain unchanged when syncId is undefined+ expect(result.current.state).toEqual({+ activeIndex: null,+ activePayload: null,+ activeLabel: null,+ isHovering: false,+ })+ })+})diff --git a/apps/studio/components/ui/Charts/useChartSync.tsx b/apps/studio/components/ui/Charts/useChartSync.tsxnew file mode 100644index 00000000000..bfc5400cbb6--- /dev/null+++ b/apps/studio/components/ui/Charts/useChartSync.tsx@@ -0,0 +1,117 @@+import { useCallback, useEffect, useRef, useState } from 'react'++export interface ChartSyncState {+ activeIndex: number | null+ activePayload: any+ activeLabel: string | null+ isHovering: boolean+}++export interface ChartSyncHook {+ syncId: string+ state: ChartSyncState+ updateState: (newState: Partial<ChartSyncState>) => void+ clearState: () => void+ subscribe: (callback: (state: ChartSyncState) => void) => () => void+}++const syncStateMap = new Map<string, ChartSyncState>()+const subscribersMap = new Map<string, Set<(state: ChartSyncState) => void>>()++const getInitialState = (): ChartSyncState => ({+ activeIndex: null,+ activePayload: null,+ activeLabel: null,+ isHovering: false,+})++export function useChartSync(syncId?: string): ChartSyncHook {+ const [state, setState] = useState<ChartSyncState>(getInitialState())+ const isInitialized = useRef(false)++ useEffect(() => {+ if (!syncId) return++ if (!syncStateMap.has(syncId)) {+ syncStateMap.set(syncId, getInitialState())+ }++ if (!subscribersMap.has(syncId)) {+ subscribersMap.set(syncId, new Set())+ }++ setState(syncStateMap.get(syncId) || getInitialState())+ isInitialized.current = true+ }, [syncId])++ useEffect(() => {+ if (!syncId || !isInitialized.current) return++ const subscribers = subscribersMap.get(syncId)!+ const callback = (newState: ChartSyncState) => {+ setState(newState)+ }++ subscribers.add(callback)++ return () => {+ subscribers.delete(callback)+ }+ }, [syncId])++ const updateState = useCallback(+ (newState: Partial<ChartSyncState>) => {+ if (!syncId) return++ const currentState = syncStateMap.get(syncId) || getInitialState()+ const updatedState = { ...currentState, ...newState }++ syncStateMap.set(syncId, updatedState)++ const subscribers = subscribersMap.get(syncId)+ if (subscribers) {+ subscribers.forEach((callback) => callback(updatedState))+ }+ },+ [syncId]+ )++ const clearState = useCallback(() => {+ if (!syncId) return++ const clearedState = getInitialState()+ syncStateMap.set(syncId, clearedState)++ const subscribers = subscribersMap.get(syncId)+ if (subscribers) {+ subscribers.forEach((callback) => callback(clearedState))+ }+ }, [syncId])++ const subscribe = useCallback(+ (callback: (state: ChartSyncState) => void) => {+ if (!syncId) return () => {}++ const subscribers = subscribersMap.get(syncId)!+ subscribers.add(callback)++ return () => {+ subscribers.delete(callback)+ }+ },+ [syncId]+ )++ return {+ syncId: syncId || '',+ state,+ updateState,+ clearState,+ subscribe,+ }+}++export function cleanupChartSync(syncId: string) {+ syncStateMap.delete(syncId)+ subscribersMap.delete(syncId)+}diff --git a/apps/studio/pages/project/[ref]/reports/database.tsx b/apps/studio/pages/project/[ref]/reports/database.tsxindex f7288df3aee..a598bb3712b 100644--- a/apps/studio/pages/project/[ref]/reports/database.tsx+++ b/apps/studio/pages/project/[ref]/reports/database.tsx@@ -278,6 +278,7 @@ const DatabaseUsage = () => {? true: chart.showMaxValue}+ syncId={chart.syncId}/>) : (<ReportChart