The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(design-system): add <MetricsCard /> component (#40355)
kemal.earth06ac40118115
diff --git a/apps/design-system/__registry__/index.tsx b/apps/design-system/__registry__/index.tsxindex 2bb69907c83..553c807886f 100644--- a/apps/design-system/__registry__/index.tsx+++ b/apps/design-system/__registry__/index.tsx@@ -2480,6 +2480,50 @@ export const Index: Record<string, any> = {subcategory: "undefined",chunks: []},+ "metric-card": {+ name: "metric-card",+ type: "components:example",+ registryDependencies: undefined,+ component: React.lazy(() => import("@/registry/default/example/metric-card")),+ source: "",+ files: ["registry/default/example/metric-card.tsx"],+ category: "undefined",+ subcategory: "undefined",+ chunks: []+ },+ "metric-card-minimal": {+ name: "metric-card-minimal",+ type: "components:example",+ registryDependencies: undefined,+ component: React.lazy(() => import("@/registry/default/example/metric-card-minimal")),+ source: "",+ files: ["registry/default/example/metric-card-minimal.tsx"],+ category: "undefined",+ subcategory: "undefined",+ chunks: []+ },+ "metric-card-minimal-horizontal": {+ name: "metric-card-minimal-horizontal",+ type: "components:example",+ registryDependencies: undefined,+ component: React.lazy(() => import("@/registry/default/example/metric-card-minimal-horizontal")),+ source: "",+ files: ["registry/default/example/metric-card-minimal-horizontal.tsx"],+ category: "undefined",+ subcategory: "undefined",+ chunks: []+ },+ "metric-card-with-icon-link-tooltip": {+ name: "metric-card-with-icon-link-tooltip",+ type: "components:example",+ registryDependencies: undefined,+ component: React.lazy(() => import("@/registry/default/example/metric-card-with-icon-link-tooltip")),+ source: "",+ files: ["registry/default/example/metric-card-with-icon-link-tooltip.tsx"],+ category: "undefined",+ subcategory: "undefined",+ chunks: []+ },"chart-area-axes": {name: "chart-area-axes",type: "components:block",diff --git a/apps/design-system/config/docs.ts b/apps/design-system/config/docs.tsindex 775c8817e8e..c517b8a066c 100644--- a/apps/design-system/config/docs.ts+++ b/apps/design-system/config/docs.ts@@ -140,6 +140,11 @@ export const docsConfig: DocsConfig = {href: '/docs/fragments/logs-bar-chart',items: [],},+ {+ title: 'Metric Card',+ href: '/docs/fragments/metric-card',+ items: [],+ },{title: 'Table of Contents (TOC)',href: '/docs/fragments/toc',diff --git a/apps/design-system/content/docs/fragments/metric-card.mdx b/apps/design-system/content/docs/fragments/metric-card.mdxnew file mode 100644index 00000000000..e21bc532348--- /dev/null+++ b/apps/design-system/content/docs/fragments/metric-card.mdx@@ -0,0 +1,21 @@+---+title: Metric Card+description: A card to display pull out metrics at a glance.+fragment: true+---++<ComponentPreview name="metric-card" peekCode wide />++## Examples++### Minimal++<ComponentPreview name="metric-card-minimal" />++### Minimal Horizontal++<ComponentPreview name="metric-card-minimal-horizontal" />++### With Icon, Link and Tooltip++<ComponentPreview name="metric-card-with-icon-link-tooltip" />diff --git a/apps/design-system/registry/default/example/metric-card-minimal-horizontal.tsx b/apps/design-system/registry/default/example/metric-card-minimal-horizontal.tsxnew file mode 100644index 00000000000..cbb1452fcd5--- /dev/null+++ b/apps/design-system/registry/default/example/metric-card-minimal-horizontal.tsx@@ -0,0 +1,49 @@+'use client'++import { useEffect, useState } from 'react'+import {+ MetricCard,+ MetricCardHeader,+ MetricCardLabel,+ MetricCardContent,+ MetricCardValue,+ MetricCardDifferential,+} from 'ui-patterns/MetricCard'++export default function MetricsCardDemo() {+ const [data, setData] = useState<Array<{ value: number; timestamp: string }>>([])++ useEffect(() => {+ const now = new Date()+ setData(+ Array.from({ length: 12 }, (_, i) => ({+ value: Math.floor(4000 + i * 100 + (Math.random() * 2000 - 800)),+ timestamp: new Date(now.getTime() - (11 - i) * 60 * 60 * 1000).toISOString(),+ }))+ )+ }, [])++ const averageValue = data.reduce((acc, curr) => acc + curr.value, 0) / data.length++ const diff = data[data.length - 1]?.value - data[0]?.value || 0+ const diffPercentage = (diff / averageValue) * 100++ return (+ <div className="w-1/2">+ <MetricCard isLoading={!data.length}>+ <MetricCardHeader>+ <MetricCardLabel>Active Users</MetricCardLabel>+ </MetricCardHeader>+ <MetricCardContent orientation="horizontal">+ <MetricCardValue>+ {averageValue.toLocaleString(undefined, { maximumFractionDigits: 0 })}+ </MetricCardValue>+ <MetricCardDifferential variant={diffPercentage > 0 ? 'positive' : 'negative'}>+ {diffPercentage > 0 ? '+' : '-'}+ {Math.abs(diffPercentage).toFixed(1)}%+ </MetricCardDifferential>+ </MetricCardContent>+ </MetricCard>+ </div>+ )+}diff --git a/apps/design-system/registry/default/example/metric-card-minimal.tsx b/apps/design-system/registry/default/example/metric-card-minimal.tsxnew file mode 100644index 00000000000..0d38fb9ae94--- /dev/null+++ b/apps/design-system/registry/default/example/metric-card-minimal.tsx@@ -0,0 +1,49 @@+'use client'++import { useEffect, useState } from 'react'+import {+ MetricCard,+ MetricCardHeader,+ MetricCardLabel,+ MetricCardContent,+ MetricCardValue,+ MetricCardDifferential,+} from 'ui-patterns/MetricCard'++export default function MetricsCardDemo() {+ const [data, setData] = useState<Array<{ value: number; timestamp: string }>>([])++ useEffect(() => {+ const now = new Date()+ setData(+ Array.from({ length: 12 }, (_, i) => ({+ value: Math.floor(4000 + i * 100 + (Math.random() * 2000 - 800)),+ timestamp: new Date(now.getTime() - (11 - i) * 60 * 60 * 1000).toISOString(),+ }))+ )+ }, [])++ const averageValue = data.reduce((acc, curr) => acc + curr.value, 0) / data.length++ const diff = data[data.length - 1]?.value - data[0]?.value || 0+ const diffPercentage = (diff / averageValue) * 100++ return (+ <div className="w-1/2">+ <MetricCard isLoading={!data.length}>+ <MetricCardHeader>+ <MetricCardLabel>Active Users</MetricCardLabel>+ </MetricCardHeader>+ <MetricCardContent>+ <MetricCardValue>+ {averageValue.toLocaleString(undefined, { maximumFractionDigits: 0 })}+ </MetricCardValue>+ <MetricCardDifferential variant={diffPercentage > 0 ? 'positive' : 'negative'}>+ {diffPercentage > 0 ? '+' : '-'}+ {Math.abs(diffPercentage).toFixed(1)}%+ </MetricCardDifferential>+ </MetricCardContent>+ </MetricCard>+ </div>+ )+}diff --git a/apps/design-system/registry/default/example/metric-card-with-icon-link-tooltip.tsx b/apps/design-system/registry/default/example/metric-card-with-icon-link-tooltip.tsxnew file mode 100644index 00000000000..072db7c70bd--- /dev/null+++ b/apps/design-system/registry/default/example/metric-card-with-icon-link-tooltip.tsx@@ -0,0 +1,58 @@+'use client'++import { useEffect, useState } from 'react'+import {+ MetricCard,+ MetricCardHeader,+ MetricCardIcon,+ MetricCardLabel,+ MetricCardContent,+ MetricCardValue,+ MetricCardDifferential,+ MetricCardSparkline,+} from 'ui-patterns/MetricCard'+import { User2 } from 'lucide-react'++export default function MetricsCardDemo() {+ const [data, setData] = useState<Array<{ value: number; timestamp: string }>>([])++ useEffect(() => {+ const now = new Date()+ setData(+ Array.from({ length: 12 }, (_, i) => ({+ value: Math.floor(4000 + i * 100 + (Math.random() * 2000 - 800)),+ timestamp: new Date(now.getTime() - (11 - i) * 60 * 60 * 1000).toISOString(),+ }))+ )+ }, [])++ const averageValue = data.reduce((acc, curr) => acc + curr.value, 0) / data.length++ const diff = data[data.length - 1]?.value - data[0]?.value || 0+ const diffPercentage = (diff / averageValue) * 100++ return (+ <div className="w-1/2">+ <MetricCard isLoading={!data.length}>+ <MetricCardHeader href="https://www.supabase.io">+ <MetricCardIcon>+ <User2 size={14} strokeWidth={1.5} />+ </MetricCardIcon>+ <MetricCardLabel tooltip="The number of active users over the last 24 hours">+ Active Users+ </MetricCardLabel>+ </MetricCardHeader>+ <MetricCardContent>+ <MetricCardValue>+ {averageValue.toLocaleString(undefined, { maximumFractionDigits: 0 })}+ </MetricCardValue>+ <MetricCardDifferential variant={diffPercentage > 0 ? 'positive' : 'negative'}>+ {diffPercentage > 0 ? '+' : '-'}+ {Math.abs(diffPercentage).toFixed(1)}%+ </MetricCardDifferential>+ </MetricCardContent>+ <MetricCardSparkline data={data} dataKey="value" />+ </MetricCard>+ </div>+ )+}diff --git a/apps/design-system/registry/default/example/metric-card.tsx b/apps/design-system/registry/default/example/metric-card.tsxnew file mode 100644index 00000000000..fca2d8f7818--- /dev/null+++ b/apps/design-system/registry/default/example/metric-card.tsx@@ -0,0 +1,53 @@+'use client'++import { useEffect, useState } from 'react'+import {+ MetricCard,+ MetricCardHeader,+ MetricCardLabel,+ MetricCardContent,+ MetricCardValue,+ MetricCardDifferential,+ MetricCardSparkline,+} from 'ui-patterns/MetricCard'++export default function MetricsCardDemo() {+ const [data, setData] = useState<Array<{ value: number; timestamp: string }>>([])++ useEffect(() => {+ const now = new Date()+ setData(+ Array.from({ length: 12 }, (_, i) => ({+ value: Math.floor(4000 + i * 100 + (Math.random() * 2000 - 800)),+ timestamp: new Date(now.getTime() - (11 - i) * 60 * 60 * 1000).toISOString(),+ }))+ )+ }, [])++ const averageValue = data.reduce((acc, curr) => acc + curr.value, 0) / data.length++ const diff = data[data.length - 1]?.value - data[0]?.value || 0+ const diffPercentage = (diff / averageValue) * 100++ return (+ <div className="w-1/2">+ <MetricCard isLoading={!data.length}>+ <MetricCardHeader href="https://www.supabase.io">+ <MetricCardLabel tooltip="The number of active users over the last 24 hours">+ Active Users+ </MetricCardLabel>+ </MetricCardHeader>+ <MetricCardContent>+ <MetricCardValue>+ {averageValue.toLocaleString(undefined, { maximumFractionDigits: 0 })}+ </MetricCardValue>+ <MetricCardDifferential variant={diffPercentage > 0 ? 'positive' : 'negative'}>+ {diffPercentage > 0 ? '+' : '-'}+ {Math.abs(diffPercentage).toFixed(1)}%+ </MetricCardDifferential>+ </MetricCardContent>+ <MetricCardSparkline data={data} dataKey="value" />+ </MetricCard>+ </div>+ )+}diff --git a/apps/design-system/registry/examples.ts b/apps/design-system/registry/examples.tsindex 1403f630391..d33f7acbec6 100644--- a/apps/design-system/registry/examples.ts+++ b/apps/design-system/registry/examples.ts@@ -1333,4 +1333,24 @@ export const examples: Registry = [type: 'components:example',files: ['example/empty-state-zero-items-data-grid.tsx'],},+ {+ name: 'metric-card',+ type: 'components:example',+ files: ['example/metric-card.tsx'],+ },+ {+ name: 'metric-card-minimal',+ type: 'components:example',+ files: ['example/metric-card-minimal.tsx'],+ },+ {+ name: 'metric-card-minimal-horizontal',+ type: 'components:example',+ files: ['example/metric-card-minimal-horizontal.tsx'],+ },+ {+ name: 'metric-card-with-icon-link-tooltip',+ type: 'components:example',+ files: ['example/metric-card-with-icon-link-tooltip.tsx'],+ },]diff --git a/packages/ui-patterns/package.json b/packages/ui-patterns/package.jsonindex fb2309218db..e74c2cd3db7 100644--- a/packages/ui-patterns/package.json+++ b/packages/ui-patterns/package.json@@ -601,6 +601,10 @@"./types/assets.d": {"import": "./src/types/assets.d.ts","types": "./src/types/assets.d.ts"+ },+ "./MetricCard": {+ "import": "./src/MetricCard/index.tsx",+ "types": "./src/MetricCard/index.tsx"}},"dependencies": {diff --git a/packages/ui-patterns/src/MetricCard/index.tsx b/packages/ui-patterns/src/MetricCard/index.tsxnew file mode 100644index 00000000000..653ec273a72--- /dev/null+++ b/packages/ui-patterns/src/MetricCard/index.tsx@@ -0,0 +1,269 @@+'use client'++import * as React from 'react'+import { useContext } from 'react'+import {+ Button,+ Tooltip,+ TooltipContent,+ TooltipTrigger,+ Card,+ CardTitle,+ cn,+ CardContent,+ Skeleton,+} from 'ui'+import { ExternalLink, HelpCircle } from 'lucide-react'+import Link from 'next/link'+import {+ AreaChart,+ Area,+ ResponsiveContainer,+ Tooltip as RechartsTooltip,+ TooltipProps as RechartsTooltipProps,+} from 'recharts'+import dayjs from 'dayjs'++interface MetricCardContextValue {+ isLoading?: boolean+ isDisabled?: boolean+}++const MetricCardContext = React.createContext<MetricCardContextValue>({+ isLoading: false,+ isDisabled: false,+})++const useMetricCard = () => {+ return useContext(MetricCardContext)+}++interface MetricCardProps extends React.HTMLAttributes<HTMLDivElement> {+ isLoading?: boolean+ isDisabled?: boolean+}++const MetricCard = React.forwardRef<HTMLDivElement, MetricCardProps>(+ ({ isLoading = false, isDisabled = false, className, children, ...props }, ref) => {+ return (+ <Card ref={ref} className={cn(className)} {...props}>+ <MetricCardContext.Provider value={{ isLoading, isDisabled }}>+ {children}+ </MetricCardContext.Provider>+ </Card>+ )+ }+)+MetricCard.displayName = 'MetricCard'++interface MetricCardHeaderProps extends React.HTMLAttributes<HTMLDivElement> {+ href?: string+ children: React.ReactNode+}++const MetricCardHeader = React.forwardRef<HTMLDivElement, MetricCardHeaderProps>(+ ({ className, href, children, ...props }, ref) => {+ return (+ <div+ ref={ref}+ className={cn(+ 'py-4 px-6 flex flex-row items-center justify-between gap-2 space-y-0 pb-0 border-b-0 relative',+ className+ )}+ {...props}+ >+ <div className="flex flex-row items-center gap-2">{children}</div>+ {href && (+ <Button type="text" size="tiny" className="px-1 text-foreground-lighter" asChild>+ <Link href={href}>+ <ExternalLink aria-disabled={true} size={14} strokeWidth={1.5} />+ <span className="sr-only">More information</span>+ </Link>+ </Button>+ )}+ </div>+ )+ }+)+MetricCardHeader.displayName = 'MetricCardHeader'++interface MetricCardContentProps extends React.HTMLAttributes<HTMLDivElement> {+ orientation?: 'horizontal' | 'vertical'+}++const MetricCardContent = React.forwardRef<HTMLDivElement, MetricCardContentProps>(+ ({ className, orientation = 'vertical', ...props }, ref) => (+ <CardContent+ ref={ref}+ className={cn(+ 'pb-4 px-6 pt-0 flex-1 flex h-full items-start gap-1 overflow-hidden border-b-0',+ orientation === 'horizontal' ? 'flex-row' : 'flex-col ',+ className+ )}+ {...props}+ />+ )+)+MetricCardContent.displayName = 'MetricCardContent'++const MetricCardIcon = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(+ ({ className, ...props }, ref) => (+ <div ref={ref} className={cn('text-foreground-light', className)} {...props} />+ )+)+MetricCardIcon.displayName = 'MetricCardIcon'++interface MetricCardLabelProps extends React.HTMLAttributes<HTMLDivElement> {+ tooltip?: string+ children: React.ReactNode+}++const MetricCardLabel = React.forwardRef<HTMLDivElement, MetricCardLabelProps>(+ ({ className, tooltip, children, ...props }, ref) => {+ return (+ <CardTitle+ ref={ref}+ className={cn('flex items-center gap-2 text-foreground-light', className)}+ {...props}+ >+ <span>{children}</span>+ {tooltip && (+ <Tooltip>+ <TooltipTrigger asChild>+ <HelpCircle size={14} strokeWidth={1.5} />+ </TooltipTrigger>+ <TooltipContent>{tooltip}</TooltipContent>+ </Tooltip>+ )}+ </CardTitle>+ )+ }+)+MetricCardLabel.displayName = 'MetricCardLabel'++const MetricCardValue = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(+ ({ className, ...props }, ref) => {+ const { isLoading } = useMetricCard()++ if (isLoading) {+ return <Skeleton className="w-32 h-7" />+ }++ return (+ <span ref={ref} className={cn('font-normal text-xl tabular-nums', className)} {...props} />+ )+ }+)++MetricCardValue.displayName = 'MetricCardValue'++interface MetricCardDifferentialProps extends React.HTMLAttributes<HTMLDivElement> {+ variant?: 'positive' | 'negative' | 'default'+}++const MetricCardDifferential = React.forwardRef<HTMLDivElement, MetricCardDifferentialProps>(+ ({ className, variant = 'default', ...props }, ref) => {+ const { isLoading } = useMetricCard()++ if (isLoading) {+ return <Skeleton className="w-16 h-5" />+ }++ return (+ <span+ ref={ref}+ className={cn(+ variant === 'positive'+ ? 'text-brand'+ : variant === 'negative'+ ? 'text-destructive'+ : 'text-foreground-light',+ 'tabular-nums text-sm',+ className+ )}+ {...props}+ />+ )+ }+)++MetricCardDifferential.displayName = 'MetricCardDifferential'++const SparklineTooltip = ({ active, payload, label }: RechartsTooltipProps<any, any>) => {+ if (!active || !payload || !payload.length) return null++ const formatTimestamp = (timestamp: string) => {+ const date = dayjs(timestamp)+ const hour = date.hour()+ const period = hour >= 12 ? 'pm' : 'am'+ const displayHour = hour % 12 || 12++ return `${date.format('MMM D')}, ${displayHour}${period}`+ }++ return (+ <div className="bg-black/90 text-white p-2 rounded text-xs">+ {label && (+ <div className="dark:text-foreground-light text-white/60">+ {formatTimestamp(payload[0].payload.timestamp)}+ </div>+ )}+ <div>{payload[0].value.toLocaleString(undefined, { maximumFractionDigits: 0 })}</div>+ </div>+ )+}+interface MetricCardSparklineProps extends React.HTMLAttributes<HTMLDivElement> {+ data?: Array<{ value: number; [key: string]: any }>+ dataKey?: string+ className?: string+}++const MetricCardSparkline = React.forwardRef<HTMLDivElement, MetricCardSparklineProps>(+ ({ className, data, dataKey, ...props }, ref) => {+ const { isLoading } = useMetricCard()+ if (isLoading) {+ return <Skeleton className="w-full h-[56px] rounded-none" />+ }++ if (!data || data.length === 0) {+ return null+ }++ return (+ <div ref={ref} className={cn('w-full h-16 relative', className)} {...props}>+ <ResponsiveContainer width="100%" height="100%" className="relative">+ <AreaChart data={data} margin={{ top: 5, left: 0, right: 0, bottom: 0 }}>+ <defs>+ <linearGradient id="sparklineGradient" x1="0" y1="0" x2="0" y2="1">+ <stop offset="5%" stopColor="hsl(var(--brand-default))" stopOpacity={0.8} />+ <stop offset="95%" stopColor="hsl(var(--brand-default))" stopOpacity={0} />+ </linearGradient>+ </defs>+ <RechartsTooltip content={<SparklineTooltip />} />+ <Area+ type="step"+ dataKey={dataKey || 'value'}+ fill="url(#sparklineGradient)"+ fillOpacity={0.1}+ stroke="hsl(var(--brand-default))"+ strokeWidth={1.5}+ />+ </AreaChart>+ </ResponsiveContainer>+ </div>+ )+ }+)+MetricCardSparkline.displayName = 'MetricCardSparkline'++export {+ MetricCard,+ MetricCardHeader,+ MetricCardIcon,+ MetricCardLabel,+ MetricCardContent,+ MetricCardValue,+ MetricCardDifferential,+ MetricCardSparkline,+ useMetricCard,+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 45d2f69d5d9..c4efbb1bddc 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -9679,9 +9679,6 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==}- '@types/[email protected]':- resolution: {integrity: sha512-vmQSUcfalpIq0R9q7uTo2lXs6eGIpt9wtnLdMv9LVpIjCA/+ufZRozlVoVelIYixx1ugCBKDhn89vnsEGOCx9A==}-'@types/[email protected]':resolution: {integrity: sha512-T7SEL8b/eN7AEhHQ8oFt7c6Y+l3p8OpH7KwJIe+5oBOPLMMioPeMsUTB3huNgEnXhiittV8Ohdw21Jg8E/f70Q==}@@ -13623,6 +13620,7 @@ packages:resolution: {integrity: sha512-fn4bQ0Xq8FTej09YC/jqKZwtijpvARlRp6wxL5WTA6yPe2YWSJ5RJh7Nm79rK2qB0wr6iDQzH60XGq5V/7u8YQ==}+ deprecated: The Intersection Observer polyfill is no longer needed and can safely be removed. Intersection Observer has been Baseline since 2019.resolution: {integrity: sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA==}@@ -22836,7 +22834,7 @@ snapshots:'@graphql-tools/executor-legacy-ws': 1.1.17([email protected])'@graphql-tools/utils': 10.8.6([email protected])'@graphql-tools/wrap': 10.0.35([email protected])- '@types/ws': 8.5.10+ '@types/ws': 8.18.1'@whatwg-node/fetch': 0.10.6'@whatwg-node/promise-helpers': 1.3.1graphql: 16.11.0@@ -29758,10 +29756,6 @@ snapshots:dependencies:'@types/node': 22.13.14- '@types/[email protected]':- dependencies:- '@types/node': 22.13.14-'@types/[email protected]': {}'@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected]([email protected])([email protected]))([email protected])([email protected])':