The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat: StackedBarChart implementation
TzeYiingb91da2d3bd5a
diff --git a/studio/components/ui/Charts/Charts.constants.ts b/studio/components/ui/Charts/Charts.constants.tsindex d423e9129e9..f9cff43f861 100644--- a/studio/components/ui/Charts/Charts.constants.ts+++ b/studio/components/ui/Charts/Charts.constants.ts@@ -9,6 +9,24 @@ export const CHART_COLORS = {GREEN_2: 'var(--colors-brand6)',}+// refer to packages/ui/radix-colors.js for full list of colors+export const STACK_COLORS = [+ ['brand', 8],+ ['mint', 8],+ ['blue', 8],+ ['sky', 7],+ ['bronze', 8],+ ['violet', 7],+ ['indigo', 8],+ ['tomato', 7],+ ['orange', 8],+ ['olive', 8],+].map(([color, n]) => ({+ lighter: `var(--colors-${color}${(n as number) - 1})`,+ base: `var(--colors-${color}${n})`,+ darker: `var(--colors-${color}${(n as number) + 1})`,+}))+export const USAGE_COLORS = {200: 'var(--colors-brand9)',201: 'var(--colors-brand8)',diff --git a/studio/components/ui/Charts/Charts.types.tsx b/studio/components/ui/Charts/Charts.types.tsxindex 239d1f29368..3332fc441ae 100644--- a/studio/components/ui/Charts/Charts.types.tsx+++ b/studio/components/ui/Charts/Charts.types.tsx@@ -1,3 +1,5 @@+import { AreaProps } from 'recharts'+export interface CommonChartProps<D>extends Pick<HeaderType<D>,@@ -9,8 +11,18 @@ export interface CommonChartProps<D>| 'minimalHeader'| 'displayDateInUtc'> {- title?: string;+ title?: stringclassName?: string+ isLoading?: boolean+ size?: 'small' | 'normal' | 'large'+}++export interface StackedChartProps<D> extends CommonChartProps<D> {+ xAxisKey: string+ xAxisFormatAsDate?: boolean+ dateFormat?: string+ yAxisKey: string+ stackKey: string}export type HeaderType<D> = {@@ -18,7 +30,7 @@ export type HeaderType<D> = {focus: number | nullformat?: stringhighlightedValue?: number | string- highlightedLabel?: string+ highlightedLabel?: stringdata: D[]customDateFormat?: stringlabel: stringdiff --git a/studio/components/ui/Charts/Charts.utils.ts b/studio/components/ui/Charts/Charts.utils.tsdeleted file mode 100644index 8683067c1b9..00000000000--- a/studio/components/ui/Charts/Charts.utils.ts+++ /dev/null@@ -1,38 +0,0 @@--/**- * Auto formats a number to a default precision if it is a float- *- * @example- * numberFormatter(123) // "123"- * numberFormatter(123.123) // "123.12"- * numberFormatter(123, 2) // "123.00"- */-export const numberFormatter = (num: number, precision = 2) => isFloat(num) ? precisionFormatter(num, precision) : String(num);---/**- * Tests if a number is a float.- *- * @example- * isFloat(123) // false- * isFloat(123.123) // true- */-export const isFloat = (num: number) => String(num).includes(".")---/**- * Formats a number to a particular precision.- *- * @example- * precisionFormatter(123, 2) // "123.00"- * precisionFormatter(123.123, 2) // "123.12"- */-export const precisionFormatter = (num: number, precision: number): string => {- if (isFloat(num)) {- const [head, tail] = String(num).split(".")- return head + "." + tail.slice(0, precision)- } else {- // pad int with 0- return String(num) + "." + ("0".repeat(precision))- }-}\ No newline at end of filediff --git a/studio/components/ui/Charts/Charts.utils.tsx b/studio/components/ui/Charts/Charts.utils.tsxnew file mode 100644index 00000000000..687603d651e--- /dev/null+++ b/studio/components/ui/Charts/Charts.utils.tsx@@ -0,0 +1,118 @@+import { DATETIME_FORMAT } from 'components/interfaces/Reports/Reports.constants'+import dayjs from 'dayjs'+import React, { useMemo } from 'react'+import { ResponsiveContainer } from 'recharts'+import { DateTimeFormats } from './Charts.constants'+import { CommonChartProps, StackedChartProps } from './Charts.types'++/**+ * Auto formats a number to a default precision if it is a float+ *+ * @example+ * numberFormatter(123) // "123"+ * numberFormatter(123.123) // "123.12"+ * numberFormatter(123, 2) // "123.00"+ */+export const numberFormatter = (num: number, precision = 2) =>+ isFloat(num) ? precisionFormatter(num, precision) : String(num)++/**+ * Tests if a number is a float.+ *+ * @example+ * isFloat(123) // false+ * isFloat(123.123) // true+ */+export const isFloat = (num: number) => String(num).includes('.')++/**+ * Formats a number to a particular precision.+ *+ * @example+ * precisionFormatter(123, 2) // "123.00"+ * precisionFormatter(123.123, 2) // "123.12"+ */+export const precisionFormatter = (num: number, precision: number): string => {+ if (isFloat(num)) {+ const [head, tail] = String(num).split('.')+ return head + '.' + tail.slice(0, precision)+ } else {+ // pad int with 0+ return String(num) + '.' + '0'.repeat(precision)+ }+}++export const timestampFormatter = (value: string, format: string= DateTimeFormats.FULL) => dayjs(value).format(format)++/**+ * Hook to create common wrapping components, perform data transformations+ * returns a Container component and the minHeight set+ */+export const useChartSize = (size: CommonChartProps<any>['size'] = 'normal') => {+ const minHeight = { small: 120, normal: 160, large: 280 }[size]+ const Container: React.FC = useMemo(+ () =>+ ({ children }) =>+ (+ <ResponsiveContainer height={minHeight} minHeight={minHeight} width="100%">+ {children as JSX.Element}+ </ResponsiveContainer>+ ),+ [size]+ )+ return {+ Container,+ minHeight,+ }+}++/**+ * Transforms data points into a stacked data structure that can be consumed by recharts+ */+export const useStacked = ({+ data,+ xAxisKey,+ yAxisKey,+ stackKey,+ variant = 'values',+}: Pick<StackedChartProps<any>, 'xAxisKey' | 'yAxisKey' | 'stackKey'> & {+ variant?: 'values' | 'percentages'+} & Pick<CommonChartProps<Record<string, number>>, 'data'>) => {+ const stackedData = 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+ }, {} as Record<string, Record<string, number>>)++ const flattened = Object.entries(mapping).map(([x, sMap]) => {+ let map = sMap+ if (variant === 'percentages') {+ const sum = Object.values(sMap).reduce((acc, value) => acc + value, 0)+ map = Object.entries(sMap).reduce((acc, [key, value]) => {+ acc[key] = value !== 0 ? value / sum : 0+ return acc+ }, {} as any)+ }+ return {+ ...map,+ [xAxisKey]: x,+ }+ })+ return flattened+ }, [JSON.stringify(data)])+ const dataKeys = useMemo(() => {+ return Object.keys(stackedData[0] || {})+ .filter((k) => k !== xAxisKey && k !== yAxisKey)+ .sort()+ }, [JSON.stringify(stackedData[0] || {})])++ return { dataKeys, stackedData }+}diff --git a/studio/components/ui/Charts/StackedBarChart.stories.tsx b/studio/components/ui/Charts/StackedBarChart.stories.tsxnew file mode 100644index 00000000000..3f3feabebb3--- /dev/null+++ b/studio/components/ui/Charts/StackedBarChart.stories.tsx@@ -0,0 +1,81 @@+import React from 'react'+import { ComponentStory, ComponentMeta } from '@storybook/react'+import dayjs from 'dayjs'+import Chart from './StackedBarChart'+import { StackedChartProps } from './Charts.types'+import { STACK_COLORS } from './Charts.constants'++export default {+ title: 'Charts/StackedBarChart',+} as ComponentMeta<typeof Chart>++const DATA = [290, 430, 649, 422, 321].flatMap((value, index) => [+ {+ count: value,+ level: 'error',+ timestamp: dayjs().subtract(index, 'day').toISOString(),+ },+ {+ count: value * 2,+ level: 'info',+ timestamp: dayjs().subtract(index, 'day').toISOString(),+ },+ {+ count: value * 1.3,+ level: 'warn',+ timestamp: dayjs().subtract(index, 'day').toISOString(),+ },+])++const PROPS = {+ title: 'Memory usage',+ xAxisKey: 'timestamp',+ yAxisKey: 'count',+ stackKey: 'level',+ data: DATA,+}+export const StackedBarChart = () => (+ <div className="flex flex-col gap-4 ">+ <ExampleName>Stack Colors</ExampleName>+ <div className="flex flex-row ">+ {STACK_COLORS.map((c) => (+ <div className="w-10 h-10" style={{ background: c.base }}></div>+ ))}+ </div>++ <ExampleName>Examples</ExampleName>+ <div className="flex flex-row gap-4 flex-wrap pb-10">+ {[+ { title: 'Normal', props: {} },+ { title: 'No title', props: { title: undefined } },+ { title: 'Minimal Header', props: { minimalHeader: true } },+ { title: 'Percentage Bars', props: { variant: 'percentages' as const } },+ {+ title: 'Formatter - Auto 2 Precision for floats',+ props: { data: DATA.map((d) => ({ ...d, count: d.count + 5.12 })) },+ },+ { title: 'UTC Dates', props: { displayDateInUtc: true } },+ { title: 'Custom date format', props: { customDateFormat: 'HH:mm' } },+ { title: 'Value format (c suffix)', props: { format: 'c' } },+ { title: 'Minimal Value format', props: { minimalHeader: true, format: 'c' } },+ { title: 'No data', props: { data: [] } },+ ].map(({ title, props }) => (+ <div className="w-72 h-72">+ <ExampleName>{title}</ExampleName>+ <div className="w-full h-full mt-4">+ <Chart {...PROPS} {...props} />+ </div>+ </div>+ ))}+ </div>+ </div>+)++const ExampleName: React.FC = ({ children }) => (+ <h1+ className="font-bold text-scale-+ 1100"+ >+ {children}+ </h1>+)diff --git a/studio/components/ui/Charts/StackedBarChart.tsx b/studio/components/ui/Charts/StackedBarChart.tsxnew file mode 100644index 00000000000..126e1eb2d0c--- /dev/null+++ b/studio/components/ui/Charts/StackedBarChart.tsx@@ -0,0 +1,129 @@+import dayjs from 'dayjs'+import { useState } from 'react'+import { BarChart, Bar, XAxis, Tooltip, Legend, Cell } from 'recharts'+import ChartHeader from './ChartHeader'+import { CHART_COLORS, STACK_COLORS, DateTimeFormats } from './Charts.constants'+import { CommonChartProps, StackedChartProps } from './Charts.types'+import { timestampFormatter, useChartSize, useStacked } from './Charts.utils'+import { precisionFormatter } from './Charts.utils'+import NoDataPlaceholder from './NoDataPlaceholder'++interface Props extends CommonChartProps<any> {+ xAxisKey: string+ yAxisKey: string+ stackKey: string+ onBarClick?: () => void+ variant?: 'values' | 'percentages'+ xAxisFormatAsDate?: boolean+}+const StackedBarChart: React.FC<Props> = ({+ size,+ data,+ xAxisKey,+ stackKey,+ yAxisKey,+ customDateFormat = DateTimeFormats.FULL,+ title,+ format,+ minimalHeader = false,+ onBarClick,+ variant,+ xAxisFormatAsDate = true,+}) => {+ const { Container } = useChartSize(size)+ const { dataKeys, stackedData } = useStacked({ data, xAxisKey, stackKey, yAxisKey, variant })+ const [focusDataIndex, setFocusDataIndex] = useState<number | null>(null)+ if (data.length === 0) return <NoDataPlaceholder />+ return (+ <div>+ <ChartHeader+ title={title}+ format={format}+ customDateFormat={customDateFormat}+ minimalHeader={minimalHeader}+ />+ <Container>+ <BarChart+ data={stackedData}+ margin={{+ top: 20,+ right: 20,+ left: 20,+ bottom: 5,+ }}+ className="cursor-pointer overflow-visible"+ // mouse hover focusing logic+ onMouseMove={(e: any) => {+ console.log(e)+ if (e.activeTooltipIndex !== focusDataIndex) {+ setFocusDataIndex(e.activeTooltipIndex)+ }+ }}+ onMouseLeave={() => setFocusDataIndex(null)}+ >+ <Legend+ wrapperStyle={{ top: -8, fontSize: '0.8rem' }}+ iconSize={8}+ iconType="circle"+ // margin={{ top: 0, left: 0, right: 0, bottom: 0 }}+ verticalAlign="top"+ />++ <XAxis+ dataKey={xAxisKey}+ interval={data.length - 2}+ angle={0}+ tick={{ fontSize: '0px' }}+ axisLine={{ stroke: CHART_COLORS.AXIS }}+ tickLine={{ stroke: CHART_COLORS.AXIS }}+ />+ {/* <YAxis dataKey={yAxisKey} /> */}+ {/* <Tooltip /> */}+ {dataKeys.map((datum, stackIndex) => (+ <Bar+ key={stackIndex}+ dataKey={datum}+ type="monotone"+ legendType="circle"+ fill={STACK_COLORS[stackIndex].base}+ stackId={1}+ animationDuration={300}+ maxBarSize={48}+ className={onBarClick ? 'cursor-pointer' : ''}+ >+ {stackedData?.map((_entry: unknown, index: any) => (+ <Cell+ key={`cell-${index}`}+ className={`transition-all duration-300`}+ opacity={focusDataIndex === index ? 0.85 : 1}+ />+ ))}+ </Bar>+ ))}+ <Tooltip+ labelFormatter={xAxisFormatAsDate ? (label) => timestampFormatter(label) : undefined}+ formatter={(value: number) => {+ if (variant === 'percentages') {+ return precisionFormatter(value * 100, 1) + '%'+ }+ return value+ }}+ cursor={false}+ labelClassName="text-white"+ contentStyle={{ backgroundColor: '#444444', borderColor: '#444444', fontSize: '12px' }}+ wrapperClassName="bg-gray-600 rounded"+ />+ </BarChart>+ </Container>+ {/* {console.log(data)} */}+ {stackedData && stackedData[0] && (+ <div className="text-scale-900 -mt-5 flex items-center justify-between text-xs">+ <span>{dayjs(stackedData[0][xAxisKey]).format(customDateFormat)}</span>+ <span>{dayjs(stackedData[data?.length - 1]?.[xAxisKey]).format(customDateFormat)}</span>+ </div>+ )}+ </div>+ )+}++export default StackedBarChart