Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

added StackedAreaChart implementation

TzeYiingedc318dc27ea
diff --git a/studio/components/interfaces/Home/ChartData.types.ts b/studio/components/interfaces/Home/ChartData.types.ts
new file mode 100644
index 00000000000..e7e2596c7d9
--- /dev/null
+++ b/studio/components/interfaces/Home/ChartData.types.ts
@@ -0,0 +1,10 @@
+export interface StatusCodesDatum {
+ timestamp: number
+ status_code: number
+ count: number
+}
+
+export interface EndpointResponse<T> {
+ result: Array<T>
+ error: Object
+}
diff --git a/studio/components/interfaces/Home/ProjectUsage.tsx b/studio/components/interfaces/Home/ProjectUsage.tsx
index 458bb1a882b..fe0aa9382df 100644
--- a/studio/components/interfaces/Home/ProjectUsage.tsx
+++ b/studio/components/interfaces/Home/ProjectUsage.tsx
@@ -23,6 +23,7 @@ import { API_URL, METRICS, DATE_FORMAT } from 'lib/constants'
import { useFlag } from 'hooks'
import StackedAreaChart from 'components/ui/charts/StackedAreaChart'
import Table from 'components/to-be-cleaned/Table'
+import { EndpointResponse, StatusCodesDatum } from './ChartData.types'
const CHART_INTERVALS = [
{ key: 'minutely', label: '60 minutes', startValue: 1, startUnit: 'hour', format: 'MMM D, h:ma' },
@@ -39,13 +40,18 @@ const ProjectUsage: FC<Props> = ({ project }) => {
const router = useRouter()
const { ref } = router.query
const { data, error }: any = useSWR(
- // only fetch when browser window is active
`${API_URL}/projects/${ref}/log-stats?interval=${interval}`,
get
- // increase refresh rate x10 to 30s when focus lost
- // conditional fetching will cause cached data to clear (not desirable)
- // { refreshInterval: isActive ? 3000 : 30000 }
)
+ const { data: codesData, error: codesFetchError } = useSWR<EndpointResponse<StatusCodesDatum>>(
+ `${API_URL}/projects/${ref}/analytics/endpoints/usage.api-codes?interval=${interval}`,
+ get
+ )
+ const { data: pathsData, error: _pathsFetchError }: any = useSWR(
+ `${API_URL}/projects/${ref}/analytics/endpoints/usage.api-paths?interval=${interval}`,
+ get
+ )
+ console.log({ codesData, pathsData })
const selectedInterval = logsUsageChartIntervals
? CHART_INTERVALS.find((i) => i.key === interval) || CHART_INTERVALS[1]
: CHART_INTERVALS[2]
@@ -203,45 +209,55 @@ const ProjectUsage: FC<Props> = ({ project }) => {
/> */}
</Panel.Content>
</Panel>
- <div>
- <Panel>
- <Panel.Content className="space-y-4">
- <PanelHeader title="API Status Codes" />
- <StackedAreaChart
- label="Status Codes"
- customDateFormat={datetimeFormat}
- data={[]}
- isLoading={!charts && !error ? true : false}
- />
- </Panel.Content>
- </Panel>
+ <Panel className="col-start-1 col-span-2" wrapWithLoading={false}>
+ <Panel.Content className="space-y-4">
+ <PanelHeader title="API Status Codes" />
+ <StackedAreaChart
+ dateFormat={datetimeFormat}
+ data={codesData?.result}
+ stackKey="status_code"
+ xAxisKey="timestamp"
+ yAxisKey="count"
+ isLoading={!codesData && !codesFetchError ? true : false}
+ xAxisFormatAsDate
+ size="large"
+ styleMap={{
+ 200: { stroke: '#08cc49', fill: '#0bee56' },
+ 201: { stroke: '#0ad83a', fill: '#0ce43e' },
+ 400: { stroke: '#d2b40a', fill: '#e2c10a' },
+ 401: { stroke: '#cc940e ', fill: '#dfa210 ' },
+ 404: { stroke: '#d0a40a', fill: '#dfb00b' },
+ 500: { stroke: '#d56d0c', fill: '#e0740e' },
+ }}
+ />
+ </Panel.Content>
+ </Panel>
- <Panel>
- <Panel.Content className="space-y-4">
- <PanelHeader title="Top Routes" />
- <Table
- head={
- <>
- <Table.th>Path</Table.th>
- <Table.th>Count</Table.th>
- <Table.th>Avg. Latency</Table.th>
- </>
- }
- body={
- <>
- {[{ path: '123', count: 123, average_latency: 123 }].map((row) => (
- <Table.tr>
- <Table.td>{row.path}</Table.td>
- <Table.td>{row.count}</Table.td>
- <Table.td>{row.average_latency}</Table.td>
- </Table.tr>
- ))}
- </>
- }
- />
- </Panel.Content>
- </Panel>
- </div>
+ <Panel className="col-start-3 col-span-2" wrapWithLoading={false}>
+ <Panel.Content className="space-y-4">
+ <PanelHeader title="Top Routes" />
+ <Table
+ head={
+ <>
+ <Table.th>Path</Table.th>
+ <Table.th>Count</Table.th>
+ <Table.th>Avg. Latency</Table.th>
+ </>
+ }
+ body={
+ <>
+ {[{ path: '123', count: 123, average_latency: 123 }].map((row) => (
+ <Table.tr>
+ <Table.td>{row.path}</Table.td>
+ <Table.td>{row.count}</Table.td>
+ <Table.td>{row.average_latency}</Table.td>
+ </Table.tr>
+ ))}
+ </>
+ }
+ />
+ </Panel.Content>
+ </Panel>
</div>
)}
</div>
diff --git a/studio/components/to-be-cleaned/Charts/ChartRenderer.tsx b/studio/components/to-be-cleaned/Charts/ChartRenderer.tsx
index ee54bb52d60..d9554ef159c 100644
--- a/studio/components/to-be-cleaned/Charts/ChartRenderer.tsx
+++ b/studio/components/to-be-cleaned/Charts/ChartRenderer.tsx
@@ -133,7 +133,7 @@ const Header = ({
)
}
-const NoData = () => (
+export const NoData = () => (
<div
className="
h-full w-full
diff --git a/studio/components/to-be-cleaned/Panel.tsx b/studio/components/to-be-cleaned/Panel.tsx
index ba6f1f802a0..4f7d9bf4769 100644
--- a/studio/components/to-be-cleaned/Panel.tsx
+++ b/studio/components/to-be-cleaned/Panel.tsx
@@ -17,31 +17,35 @@ function Panel(props: any) {
]
}
- return (
- <Loading active={props.loading}>
- <div
- className={`
- border border-panel-border-light dark:border-panel-border-dark
- rounded ${props.noMargin ? '' : 'mb-8'} ${props.className}`}
- >
- {props.title && (
- <div className={headerClasses.join(' ')}>
- <div className="px-6 py-4 flex items-center">{props.title}</div>
- </div>
- )}
- <div className="bg-panel-body-light dark:bg-panel-body-dark">{props.children}</div>
- {props.footer && (
- <div
- className="
- bg-panel-footer-light dark:bg-panel-footer-dark
- border-t border-panel-border-interior-light dark:border-panel-border-interior-dark"
- >
- <div className="px-6 h-12 flex items-center">{props.footer}</div>
- </div>
- )}
- </div>
- </Loading>
+ const content = (
+ <div
+ className={`
+ border border-panel-border-light dark:border-panel-border-dark
+ rounded ${props.noMargin ? '' : 'mb-8'} ${props.className}`}
+ >
+ {props.title && (
+ <div className={headerClasses.join(' ')}>
+ <div className="px-6 py-4 flex items-center">{props.title}</div>
+ </div>
+ )}
+ <div className="bg-panel-body-light dark:bg-panel-body-dark">{props.children}</div>
+ {props.footer && (
+ <div
+ className="
+ bg-panel-footer-light dark:bg-panel-footer-dark
+ border-t border-panel-border-interior-light dark:border-panel-border-interior-dark"
+ >
+ <div className="px-6 h-12 flex items-center">{props.footer}</div>
+ </div>
+ )}
+ </div>
)
+
+ if (props.wrapWithLoading === false) {
+ return content
+ }
+
+ return <Loading active={props.loading}>{content}</Loading>
}
function Content(props: any) {
diff --git a/studio/components/ui/charts/StackedAreaChart.tsx b/studio/components/ui/charts/StackedAreaChart.tsx
index f32667b2e32..f835b3bdbfe 100644
--- a/studio/components/ui/charts/StackedAreaChart.tsx
+++ b/studio/components/ui/charts/StackedAreaChart.tsx
@@ -1,39 +1,122 @@
-import { AreaChart, XAxis, YAxis, Area, Tooltip, ResponsiveContainer } from 'recharts'
+import { TooltipContent } from '@radix-ui/react-tooltip'
+import { NoData } from 'components/to-be-cleaned/Charts/ChartRenderer'
+import dayjs from 'dayjs'
+import { useMemo } from 'react'
+import {
+ AreaChart,
+ XAxis,
+ YAxis,
+ Area,
+ Tooltip,
+ ResponsiveContainer,
+ CartesianGrid,
+ AreaProps,
+} from 'recharts'
+
+type Datum = {
+ [key: string]: any
+}
+
+type Data = Datum[]
interface Props {
- label: string
- customDateFormat: string
- data: any[]
+ data?: Data
isLoading: boolean
+ xAxisKey: string
+ xAxisFormatAsDate?: boolean
+ dateFormat?: string
+ yAxisKey: string
+ stackKey: string
+ size?: 'small' | 'normal' | 'large'
+ styleMap: {
+ [key: string]: Pick<AreaProps, 'fill' | 'stroke'>
+ }
}
-const StackedAreaChart: React.FC<Props> = () => (
- <ResponsiveContainer>
- <AreaChart
- width={730}
- height={250}
- data={[
- {
- day: '05-01',
- temperature: [-1, 10],
- },
- {
- day: '05-02',
- temperature: [2, 15],
- },
- ]}
- margin={{
- top: 20,
- right: 20,
- bottom: 20,
- left: 20,
- }}
- >
- <XAxis dataKey="day" />
- <YAxis />
- <Area dataKey="temperature" stroke="#8884d8" fill="#8884d8" />
- <Tooltip />
- </AreaChart>
- </ResponsiveContainer>
-)
+const StackedAreaChart: React.FC<Props> = ({
+ data,
+ xAxisKey,
+ dateFormat,
+ yAxisKey,
+ stackKey,
+ isLoading,
+ size = 'normal',
+ styleMap = {},
+ xAxisFormatAsDate = false,
+}) => {
+ if (!isLoading && (data === undefined || data === null)) return <NoData />
+ const transformed = useMemo(() => {
+ if (!data) return []
+ const mapping = data.reduce((acc, datum) => {
+ const x = datum[xAxisKey]
+ const y = datum[yAxisKey]
+ const s = datum[stackKey]
+ if (!acc[x]) {
+ acc[x] = {}
+ }
+ acc[x][s] = y
+ return acc
+ }, {})
+
+ const flattened = Object.entries(mapping).map(([x, sMap]) => ({
+ ...(sMap as Datum),
+ [xAxisKey]: x,
+ }))
+ return flattened
+ }, [JSON.stringify(data)])
+ const dataKeys = Object.keys(transformed[0] || {}).filter((k) => k !== xAxisKey && k !== yAxisKey)
+
+ const formatToDate = (value: string | number | any) => {
+ if (!dateFormat) return value
+ if (typeof value === 'number') {
+ const unix = String(value).length > 10 ? Number(String(value).slice(0, 10)) : value
+ return dayjs.unix(unix).format(dateFormat)
+ } else {
+ return dayjs(value).format(dateFormat)
+ }
+ }
+ const minHeight = { small: '120px', normal: '160px', large: '280px' }[size]
+ return (
+ <ResponsiveContainer height="100%" minHeight={minHeight} width="100%">
+ <AreaChart data={transformed} onClick={(_tooltipData: any) => {}}>
+ <CartesianGrid strokeDasharray="3 3" style={{ stroke: '#444444' }} />
+ <XAxis
+ dataKey={xAxisKey}
+ angle={0}
+ axisLine={{ stroke: '#444444' }}
+ tickLine={{ stroke: '#444444' }}
+ tickFormatter={xAxisFormatAsDate ? formatToDate : undefined}
+ tickMargin={12}
+ interval="preserveStartEnd"
+ style={{ fontSize: '12px' }}
+ />
+ <YAxis
+ style={{ fontSize: '12px' }}
+ minTickGap={10}
+ axisLine={{ stroke: '#444444' }}
+ tickLine={{ stroke: '#444444' }}
+ />
+ {dataKeys.map((k, index) => (
+ <Area
+ key={index}
+ dataKey={String(k)}
+ type="monotone"
+ legendType="circle"
+ fill={'rgba(62, 207, 142, 0.2)'}
+ stroke="#4884d8"
+ connectNulls
+ stackId={1}
+ {...(styleMap[k] || {})}
+ />
+ ))}
+ <Tooltip
+ labelFormatter={xAxisFormatAsDate ? formatToDate : undefined}
+ labelClassName="text-gray-100"
+ contentStyle={{ backgroundColor: '#444444', borderColor: '#444444', fontSize: '12px' }}
+ wrapperClassName="bg-gray-600"
+ />
+ </AreaChart>
+ </ResponsiveContainer>
+ )
+}
export default StackedAreaChart
diff --git a/studio/pages/project/[ref]/index.tsx b/studio/pages/project/[ref]/index.tsx
index f694cb0754b..2329d02adb4 100644
--- a/studio/pages/project/[ref]/index.tsx
+++ b/studio/pages/project/[ref]/index.tsx
@@ -47,6 +47,7 @@ const Home: NextPage = () => {
{projectName}
</Typography.Title>
</div>
+ <ProjectUsage project={project} />
{IS_PLATFORM && project && (
<>
{isUndefined(usage) ? (