The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat: Add error state to charts (#46991)
Ivan Vasilov92e79e67d9f5
diff --git a/apps/design-system/registry/default/block/chart-composed-states.tsx b/apps/design-system/registry/default/block/chart-composed-states.tsxindex c4e25d545c2..2d3657cca2c 100644--- a/apps/design-system/registry/default/block/chart-composed-states.tsx+++ b/apps/design-system/registry/default/block/chart-composed-states.tsx@@ -1,7 +1,7 @@'use client'import { BarChart2, ExternalLink } from 'lucide-react'-import { Badge } from 'ui'+import { Badge, CriticalIcon } from 'ui'import {Chart,ChartActions,@@ -44,6 +44,35 @@ export default function ChartComposedStates() {</ChartCard></Chart>+ <Chart isErrored={true}>+ <ChartCard>+ <ChartHeader>+ <ChartTitle tooltip="This is a tooltip">Response Errors</ChartTitle>+ <ChartActions actions={actions} />+ </ChartHeader>+ <ChartContent+ isEmpty={true}+ errorState={+ <ChartEmptyState+ icon={<CriticalIcon />}+ title="Some error happened"+ description="Error happened why trying to fetch data. Please try again later."+ />+ }+ emptyState={+ <ChartEmptyState+ icon={<BarChart2 size={20} />}+ title="No data to show"+ description="It may take up to 24 hours for data to refresh"+ />+ }+ loadingState={<ChartLoadingState />}+ >+ My chart here...+ </ChartContent>+ </ChartCard>+ </Chart>+<Chart><ChartCard><ChartHeader>diff --git a/apps/studio/components/interfaces/ProjectHome/ProjectUsageSection.tsx b/apps/studio/components/interfaces/ProjectHome/ProjectUsageSection.tsxindex 54c02299725..db61af89df2 100644--- a/apps/studio/components/interfaces/ProjectHome/ProjectUsageSection.tsx+++ b/apps/studio/components/interfaces/ProjectHome/ProjectUsageSection.tsx@@ -3,15 +3,16 @@ import dayjs from 'dayjs'import Link from 'next/link'import { useRouter } from 'next/router'import { useEffect, useMemo, useState } from 'react'-import { Card, CardContent, CardHeader, CardTitle, Loading } from 'ui'+import { Card, CardContent, CardHeader, CardTitle, Loading, WarningIcon } from 'ui'import { Row } from 'ui-patterns'+import { ChartEmptyState } from 'ui-patterns/Chart'import { LogsBarChart } from 'ui-patterns/LogsBarChart'import NoDataPlaceholder from '@/components/ui/Charts/NoDataPlaceholder'import { ChartIntervalDropdown } from '@/components/ui/Logs/ChartIntervalDropdown'import { CHART_INTERVALS } from '@/components/ui/Logs/logs.utils'import { UsageApiCounts, useProjectLogStatsQuery } from '@/data/analytics/project-log-stats-query'-import { useFillTimeseriesSorted } from '@/hooks/analytics/useFillTimeseriesSorted'+import { fillTimeseriesSorted } from '@/hooks/analytics/useFillTimeseriesSorted'import { useCheckEntitlements } from '@/hooks/misc/useCheckEntitlements'import { useIsFeatureEnabled } from '@/hooks/misc/useIsFeatureEnabled'import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'@@ -71,33 +72,42 @@ export const ProjectUsageSection = () => {}, [selectedInterval])// Use V1 data fetching- const { data: logStatsData, isPending: isLoading } = useProjectLogStatsQuery({- projectRef,- interval,- })+ const {+ data: filledCharts,+ isPending: isLoading,+ error,+ } = useProjectLogStatsQuery(+ {+ projectRef,+ interval,+ },+ {+ select: (data) => {+ // Calculate date range for gap filling+ const startDateLocal = dayjs().subtract(+ selectedInterval.startValue,+ selectedInterval.startUnit as dayjs.ManipulateType+ )+ const endDateLocal = dayjs()- // Calculate date range for gap filling- const startDateLocal = dayjs().subtract(- selectedInterval.startValue,- selectedInterval.startUnit as dayjs.ManipulateType+ return fillTimeseriesSorted({+ data: data.result,+ timestampKey: 'timestamp',+ valueKey: [+ 'total_auth_requests',+ 'total_rest_requests',+ 'total_storage_requests',+ 'total_realtime_requests',+ ],+ defaultValue: 0,+ startDate: startDateLocal.toISOString(),+ endDate: endDateLocal.toISOString(),+ minPointsToFill: 5,+ })+ },+ refetchOnWindowFocus: false,+ })- const endDateLocal = dayjs()-- // Fill gaps in timeseries data- const { data: filledCharts } = useFillTimeseriesSorted({- data: logStatsData?.result ?? [],- timestampKey: 'timestamp',- valueKey: [- 'total_auth_requests',- 'total_rest_requests',- 'total_storage_requests',- 'total_realtime_requests',- ],- defaultValue: 0,- startDate: startDateLocal.toISOString(),- endDate: endDateLocal.toISOString(),- minPointsToFill: 5,- })const serviceBase: ServiceEntry[] = useMemo(() => [@@ -147,7 +157,7 @@ export const ProjectUsageSection = () => {// Transform V1 data to LogsBarChart format// Since V1 doesn't have error/warning breakdown, we show everything as "ok"- const transformedData: LogsBarChartDatum[] = (filledCharts || []).map((item) => ({+ const transformedData: LogsBarChartDatum[] = (filledCharts?.data || []).map((item) => ({timestamp: item.timestamp,error_count: 0,warning_count: 0,@@ -162,10 +172,10 @@ export const ProjectUsageSection = () => {data: transformedData,total,isLoading,- error: null,+ error: error || filledCharts?.error || null,}}),- [serviceBase, filledCharts, isLoading]+ [serviceBase, filledCharts, isLoading, error])const handleBarClick =@@ -239,6 +249,7 @@ export const ProjectUsageSection = () => {<LogsBarChartisFullHeightdata={s.data}+ error={s.error}DateTimeFormat={datetimeFormat}onBarClick={handleBarClick(s.route, s.key)}hideZeroValues={true}@@ -253,6 +264,13 @@ export const ProjectUsageSection = () => {label: 'Requests',},}}+ ErrorState={+ <ChartEmptyState+ icon={<WarningIcon />}+ title="Failed to load project usage"+ description="Check our Status Page or try again later."+ />+ }EmptyState={<NoDataPlaceholdersize="small"diff --git a/apps/studio/hooks/analytics/useFillTimeseriesSorted.ts b/apps/studio/hooks/analytics/useFillTimeseriesSorted.tsindex 662d71209f1..8448f46b865 100644--- a/apps/studio/hooks/analytics/useFillTimeseriesSorted.ts+++ b/apps/studio/hooks/analytics/useFillTimeseriesSorted.ts@@ -66,6 +66,23 @@ export function hasValidTimestamp<T extends Datum>(data: T[], timestampKey: stri*/export const useFillTimeseriesSorted = <T extends Datum = Datum>(options: FillTimeseriesOptions<T>+): FillTimeseriesResult<T> => {+ return useMemo(() => {+ return fillTimeseriesSorted(options)+ }, [+ JSON.stringify(options.data),+ options.timestampKey,+ JSON.stringify(options.valueKey),+ options.defaultValue,+ options.startDate,+ options.endDate,+ options.minPointsToFill,+ options.interval,+ ])+}++export const fillTimeseriesSorted = <T extends Datum = Datum>(+ options: FillTimeseriesOptions<T>): FillTimeseriesResult<T> => {const {data,@@ -78,50 +95,39 @@ export const useFillTimeseriesSorted = <T extends Datum = Datum>(interval,} = options- return useMemo(() => {- // Early return if no valid timestamp- if (!hasValidTimestamp(data, timestampKey)) {- return {- data,- error: null,- isError: false,- }+ // Early return if no valid timestamp+ if (!hasValidTimestamp(data, timestampKey)) {+ return {+ data,+ error: null,+ isError: false,}+ }- try {- const filled = fillTimeseries(- data,- timestampKey,- valueKey,- defaultValue,- startDate,- endDate,- minPointsToFill,- interval- ) as T[]+ try {+ const filled = fillTimeseries(+ data,+ timestampKey,+ valueKey,+ defaultValue,+ startDate,+ endDate,+ minPointsToFill,+ interval+ ) as T[]- const sorted = sortByTimestamp(filled, timestampKey)+ const sorted = sortByTimestamp(filled, timestampKey)- return {- data: sorted,- error: null,- isError: false,- }- } catch (error: unknown) {- return {- data: [],- error: error instanceof Error ? error : new Error(String(error)),- isError: true,- }+ return {+ data: sorted,+ error: null,+ isError: false,}- }, [- JSON.stringify(data),- timestampKey,- JSON.stringify(valueKey),- defaultValue,- startDate,- endDate,- minPointsToFill,- interval,- ])+ } catch (error: unknown) {+ return {+ data: [],+ error: error instanceof Error ? error : new Error(String(error)),+ isError: true,+ }+ }}diff --git a/packages/ui-patterns/src/Chart/index.tsx b/packages/ui-patterns/src/Chart/index.tsxindex ca9773a529a..3c0937a6159 100644--- a/packages/ui-patterns/src/Chart/index.tsx+++ b/packages/ui-patterns/src/Chart/index.tsx@@ -43,11 +43,13 @@ export type ChartConfig = {interface ChartContextValue {isLoading?: booleanisDisabled?: boolean+ isErrored?: boolean}const ChartContext = React.createContext<ChartContextValue>({isLoading: false,isDisabled: false,+ isErrored: false,})export const useChart = () => {@@ -59,15 +61,19 @@ interface ChartProps extends React.HTMLAttributes<HTMLDivElement> {children: React.ReactNodeisLoading?: booleanisDisabled?: boolean+ isErrored?: booleanclassName?: string}const chartTableClasses = `[&_tr]:border-b [&_tr]:border-border [&_thead_tr]:bg-transparent! [&_thead_th]:py-2! [&_thead_th]:!px-card [&_thead_th]:h-auto [&_tbody_td]:py-2.5 [&_tbody_td]:px-card [&_tbody_td]:text-xs [&_table]:mb-1 [&_table]:border-b [&_table]:border-border`const Chart = React.forwardRef<HTMLDivElement, ChartProps>(- ({ children, isLoading = false, isDisabled = false, className, ...props }, ref) => {+ (+ { children, isLoading = false, isDisabled = false, isErrored = false, className, ...props },+ ref+ ) => {return (- <ChartContext.Provider value={{ isLoading, isDisabled }}>+ <ChartContext.Provider value={{ isLoading, isDisabled, isErrored }}><div ref={ref} className={cn('relative w-full', className)} {...props}>{children}</div>@@ -306,6 +312,7 @@ interface ChartContentProps extends React.HTMLAttributes<HTMLDivElement> {isEmpty?: booleanemptyState?: React.ReactNodeloadingState?: React.ReactNode+ errorState?: React.ReactNodedisabledState?: React.ReactNodedisabledActions?: ChartAction[]}@@ -318,19 +325,22 @@ const ChartContent = React.forwardRef<HTMLDivElement, ChartContentProps>(isEmpty = false,emptyState,loadingState,+ errorState,disabledState,disabledActions,...props},ref) => {- const { isLoading, isDisabled } = useChart()+ const { isLoading, isDisabled, isErrored } = useChart()let content: React.ReactNodeif (isDisabled) {content = disabledState} else if (isLoading) {content = loadingState+ } else if (isErrored) {+ content = errorState} else if (isEmpty) {content = emptyState} else {diff --git a/packages/ui-patterns/src/LogsBarChart/index.tsx b/packages/ui-patterns/src/LogsBarChart/index.tsxindex 20316fc438f..c0ad0476d8b 100644--- a/packages/ui-patterns/src/LogsBarChart/index.tsx+++ b/packages/ui-patterns/src/LogsBarChart/index.tsx@@ -26,8 +26,10 @@ type LogsBarChartDatum = {export const LogsBarChart = ({data,+ error,onBarClick,EmptyState,+ ErrorState,DateTimeFormat = 'MMM D, YYYY, hh:mma',isFullHeight = false,chartConfig,@@ -36,8 +38,10 @@ export const LogsBarChart = ({hideXAxis = false,}: {data: LogsBarChartDatum[]+ error?: unknown | nullonBarClick?: (datum: LogsBarChartDatum, tooltipData?: CategoricalChartState) => voidEmptyState?: ReactNode+ ErrorState?: ReactNodeDateTimeFormat?: stringisFullHeight?: booleanchartConfig?: ChartConfig@@ -47,6 +51,11 @@ export const LogsBarChart = ({}) => {const [focusDataIndex, setFocusDataIndex] = useState<number | null>(null)+ if (error) {+ if (ErrorState) return ErrorState+ return null+ }+if (data.length === 0) {if (EmptyState) return EmptyStatereturn null