Skip to content

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

joshen/fe 4150 explorer query cells result display settings (#49003)

Joshen Limd434c63bada6
diff --git a/apps/studio/components/interfaces/Explorer/QueryCell/DisplaySettingsButton.tsx b/apps/studio/components/interfaces/Explorer/QueryCell/DisplaySettingsButton.tsx
new file mode 100644
index 00000000000..96460ec03ec
--- /dev/null
+++ b/apps/studio/components/interfaces/Explorer/QueryCell/DisplaySettingsButton.tsx
@@ -0,0 +1,225 @@
+import { BarChart2, Settings2, Table } from 'lucide-react'
+import {
+ Checkbox,
+ Popover,
+ PopoverContent,
+ PopoverSeparator,
+ PopoverTrigger,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+ ToggleGroup,
+ ToggleGroupItem,
+} from 'ui'
+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
+import { type Snapshot } from 'valtio'
+
+import { ExplorerToolbarAction } from '../ExplorerToolbar'
+import { type DatabaseCell as DatabaseCellSchema } from '@/data/content/notebooks/notebook-schema'
+import { useCurrentNotebook, useNotebooksStateSnapshot } from '@/state/notebooks/notebooks-state'
+
+interface DisplaySettingsButtonProps {
+ cell: Snapshot<DatabaseCellSchema>
+ columns: string[]
+ disabled: boolean
+}
+
+// [Joshen] TODO support multiple y axis charts
+
+export const DisplaySettingsButton = ({ cell, columns, disabled }: DisplaySettingsButtonProps) => {
+ const snap = useNotebooksStateSnapshot()
+ const currentNotebook = useCurrentNotebook()
+ const cells = currentNotebook?.notebook.content?.cells ?? []
+
+ const { view, chart } = cell
+ const {
+ type = 'bar',
+ x_column,
+ y_columns,
+ cumulative = false,
+ show_labels = false,
+ scale = 'linear',
+ } = chart ?? {}
+
+ const onChangeView = (view: 'table' | 'chart') => {
+ const notebookId = currentNotebook?.notebook.id
+ if (!notebookId) return
+
+ const nextCells = cells.map((c) =>
+ c.id === cell.id && c._tag === 'database_cell' ? { ...c, view } : c
+ )
+ snap.updateCells({ id: notebookId, cells: nextCells })
+ }
+
+ const onUpdateChartConfig = (
+ payload:
+ | { type: 'bar' | 'line' }
+ | { x_column: string }
+ | { y_columns: string[] }
+ | { cumulative: boolean }
+ | { show_labels: boolean }
+ | { scale: 'linear' | 'log' }
+ ) => {
+ const notebookId = currentNotebook?.notebook.id
+ if (!notebookId) return
+
+ const nextCells = cells.map((c) => {
+ if (c.id !== cell.id || c._tag !== 'database_cell') return c
+
+ return {
+ ...c,
+ chart: {
+ type: c.chart?.type ?? 'bar',
+ x_column: c.chart?.x_column ?? '',
+ y_columns: c.chart?.y_columns ?? [],
+ cumulative: c.chart?.cumulative ?? false,
+ scale: c.chart?.scale ?? 'linear',
+ show_labels: c.chart?.show_labels ?? false,
+ ...payload,
+ },
+ }
+ })
+ snap.updateCells({ id: notebookId, cells: nextCells })
+ }
+
+ return (
+ <Popover>
+ <PopoverTrigger asChild>
+ <ExplorerToolbarAction disabled={disabled} icon={<Settings2 />} tooltip="Result settings" />
+ </PopoverTrigger>
+ <PopoverContent side="bottom" className="flex flex-col gap-y-3 p-0 py-3">
+ <div className="flex flex-col gap-y-3 px-3">
+ <p className="text-xs tracking-tighter uppercase font-mono text-foreground-lighter">
+ Result display settings
+ </p>
+
+ <FormItemLayout isReactForm={false} label="View data as">
+ <ToggleGroup
+ value={view}
+ onValueChange={(value) => {
+ if (value === 'table' || value === 'chart') onChangeView(value)
+ }}
+ variant="outline"
+ type="single"
+ >
+ <ToggleGroupItem value="table" className="w-full gap-x-2 data-[state=on]:bg-accent">
+ <Table size={14} />
+ <p>Table</p>
+ </ToggleGroupItem>
+ <ToggleGroupItem value="chart" className="w-full gap-x-2 data-[state=on]:bg-accent">
+ <BarChart2 size={14} />
+ <p>Chart</p>
+ </ToggleGroupItem>
+ </ToggleGroup>
+ </FormItemLayout>
+ </div>
+
+ {view === 'chart' && (
+ <>
+ <PopoverSeparator />
+
+ <FormItemLayout isReactForm={false} label="Render chart as" className="px-3 mb-1">
+ <ToggleGroup
+ value={type}
+ onValueChange={(value) => {
+ if (value === 'bar' || value === 'line') onUpdateChartConfig({ type: value })
+ }}
+ variant="outline"
+ type="single"
+ >
+ <ToggleGroupItem value="bar" className="w-full data-[state=on]:bg-accent">
+ Bar
+ </ToggleGroupItem>
+ <ToggleGroupItem value="line" className="w-full data-[state=on]:bg-accent">
+ Line
+ </ToggleGroupItem>
+ </ToggleGroup>
+ </FormItemLayout>
+
+ <div className="px-3 flex flex-col gap-y-2">
+ <FormItemLayout isReactForm={false} layout="flex-row-reverse" label="X axis">
+ <Select
+ value={x_column}
+ onValueChange={(x_column) => onUpdateChartConfig({ x_column })}
+ >
+ <SelectTrigger className="w-32">
+ <SelectValue placeholder="Select a column" />
+ </SelectTrigger>
+ <SelectContent>
+ {columns.map((x) => (
+ <SelectItem key={x} value={x}>
+ {x}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </FormItemLayout>
+
+ <FormItemLayout isReactForm={false} layout="flex-row-reverse" label="Y Axis">
+ <Select
+ value={y_columns?.[0]}
+ onValueChange={(y_column) => onUpdateChartConfig({ y_columns: [y_column] })}
+ >
+ <SelectTrigger className="w-32">
+ <SelectValue placeholder="Select a column" />
+ </SelectTrigger>
+ <SelectContent>
+ {columns.map((x) => (
+ <SelectItem key={x} value={x}>
+ {x}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </FormItemLayout>
+
+ <FormItemLayout isReactForm={false} layout="flex-row-reverse" label="Scale">
+ <Select
+ value={scale}
+ onValueChange={(scale) =>
+ onUpdateChartConfig({ scale: scale as 'log' | 'linear' })
+ }
+ >
+ <SelectTrigger className="w-32">
+ <SelectValue placeholder="Select a column" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="linear">Linear</SelectItem>
+ <SelectItem value="log">Logarithmic</SelectItem>
+ </SelectContent>
+ </Select>
+ </FormItemLayout>
+
+ <FormItemLayout id="cumulative" isReactForm={false} layout="flex" label="Cumulative">
+ <Checkbox
+ id="cumulative"
+ checked={cumulative}
+ onCheckedChange={(cumulative) =>
+ onUpdateChartConfig({ cumulative: Boolean(cumulative) })
+ }
+ />
+ </FormItemLayout>
+
+ <FormItemLayout
+ id="show_labels"
+ isReactForm={false}
+ layout="flex"
+ label="Show labels"
+ >
+ <Checkbox
+ id="show_labels"
+ checked={show_labels}
+ onCheckedChange={(show_labels) =>
+ onUpdateChartConfig({ show_labels: Boolean(show_labels) })
+ }
+ />
+ </FormItemLayout>
+ </div>
+ </>
+ )}
+ </PopoverContent>
+ </Popover>
+ )
+}
diff --git a/apps/studio/components/interfaces/Explorer/QueryCell/QueryResultChart.tsx b/apps/studio/components/interfaces/Explorer/QueryCell/QueryResultChart.tsx
new file mode 100644
index 00000000000..8f6db1ffc8c
--- /dev/null
+++ b/apps/studio/components/interfaces/Explorer/QueryCell/QueryResultChart.tsx
@@ -0,0 +1,96 @@
+import { useMemo } from 'react'
+import { Chart, ChartBar, ChartCard, ChartContent, ChartLine } from 'ui-patterns/Chart'
+import { type Snapshot } from 'valtio'
+
+import { type QueryResult } from '../types'
+import NoDataPlaceholder from '@/components/ui/Charts/NoDataPlaceholder'
+import { getCumulativeResults } from '@/components/ui/QueryBlock/QueryBlock.utils'
+import { type DatabaseCell as DatabaseCellSchema } from '@/data/content/notebooks/notebook-schema'
+
+interface QueryResultChartProps {
+ cell: Snapshot<DatabaseCellSchema>
+ result?: QueryResult
+}
+
+// [Joshen] Will need to implement log scale - refer to QueryBlock.tsx `effectiveLogScale`
+// [Joshen] Will also need to implement error handling where appropriate (e.g if query errors)
+
+const toChartValue = (value: unknown): string | number => {
+ if (typeof value === 'number' || typeof value === 'string') return value
+ if (value === null || value === undefined) return ''
+ return String(value)
+}
+
+export const QueryResultChart = ({ cell, result }: QueryResultChartProps) => {
+ const { chart } = cell
+ const { type, x_column, y_columns = [], cumulative, show_labels } = chart ?? {}
+
+ const hasConfig = !!x_column && y_columns.length > 0
+ const chartRows = useMemo(() => {
+ const xKey = x_column ?? ''
+ const yKey = y_columns[0] ?? ''
+ return (result?.rows ?? []).map((row) => ({
+ [xKey]: toChartValue(row[xKey]),
+ [yKey]: toChartValue(row[yKey]),
+ }))
+ }, [result, x_column, y_columns])
+
+ const cumulativeResults = useMemo(
+ () => getCumulativeResults({ rows: chartRows }, { yKey: y_columns[0] ?? '' }),
+ [chartRows, y_columns]
+ )
+ const resultToRender = cumulative ? cumulativeResults : chartRows
+
+ if (!result || (result?.rows && result.rows.length === 0)) {
+ return (
+ <NoDataPlaceholder
+ className="bg border-0"
+ size="normal"
+ message="No results"
+ description="Your query returned no rows"
+ />
+ )
+ }
+
+ if (!hasConfig) {
+ return (
+ <NoDataPlaceholder
+ className="bg border-0"
+ size="normal"
+ message="Configure your chart"
+ description="Select your X and Y axis in the display settings"
+ />
+ )
+ }
+
+ return (
+ <Chart>
+ <ChartCard className="rounded-none border-0">
+ <ChartContent>
+ <div className="h-40">
+ {type === 'bar' && (
+ <ChartBar
+ isFullHeight
+ xKey={x_column}
+ dataKey={y_columns[0]}
+ showXAxis={show_labels}
+ showYAxis={show_labels}
+ data={resultToRender}
+ />
+ )}
+ {type === 'line' && (
+ <ChartLine
+ isFullHeight
+ xKey={x_column}
+ dataKey={y_columns[0]}
+ showXAxis={show_labels}
+ showYAxis={show_labels}
+ data={resultToRender}
+ />
+ )}
+ </div>
+ </ChartContent>
+ </ChartCard>
+ </Chart>
+ )
+}
diff --git a/apps/studio/components/interfaces/Explorer/QueryCell/index.tsx b/apps/studio/components/interfaces/Explorer/QueryCell/index.tsx
index bc3846d41d8..bf225ba54c5 100644
--- a/apps/studio/components/interfaces/Explorer/QueryCell/index.tsx
+++ b/apps/studio/components/interfaces/Explorer/QueryCell/index.tsx
@@ -1,7 +1,8 @@
import { acceptUntrustedSql, untrustedSql } from '@supabase/pg-meta'
-import { CodeSquare, Eye, EyeOff, Play, Settings2 } from 'lucide-react'
+import { CodeSquare, Eye, EyeOff, Play } from 'lucide-react'
import { useState } from 'react'
import { cn } from 'ui'
+import { type Snapshot } from 'valtio'
import {
ExplorerQuery,
@@ -18,6 +19,8 @@ import {
} from '../ExplorerToolbar'
import { QueryResultTable } from '../QueryResultTable'
import { type QueryResult } from '../types'
+import { DisplaySettingsButton } from './DisplaySettingsButton'
+import { QueryResultChart } from './QueryResultChart'
import { CodeEditor } from '@/components/ui/CodeEditor/CodeEditor'
import { SortableSection } from '@/components/ui/SortableSection'
import { type DatabaseCell as DatabaseCellSchema } from '@/data/content/notebooks/notebook-schema'
@@ -28,7 +31,7 @@ import { useCurrentNotebook, useNotebooksStateSnapshot } from '@/state/notebooks
import { type ResponseError } from '@/types'
interface QueryCellProps {
- cell: DatabaseCellSchema
+ cell: Snapshot<DatabaseCellSchema>
}
/**
@@ -46,11 +49,12 @@ export const QueryCell = ({ cell }: QueryCellProps) => {
const { data: project } = useSelectedProjectQuery()
const cells = currentNotebook?.notebook.content?.cells ?? []
- const { title = 'Untitled snippet', row_limit } = cell
+ const { title = 'Untitled snippet', row_limit, view } = cell
const [showQuery, setShowQuery] = useState(true)
const [value, setValue] = useState<string>(cell.unchecked_sql)
const [result, setResult] = useState<QueryResult>()
+ const columns = Object.keys(result?.rows?.[0] ?? {})
const valueRef = useLatest(value)
@@ -114,10 +118,10 @@ export const QueryCell = ({ cell }: QueryCellProps) => {
{title}
</ExplorerToolbarTitle>
<ExplorerToolbarActions>
- <ExplorerToolbarAction
+ <DisplaySettingsButton
+ cell={cell}
+ columns={columns}
disabled={(result?.rows ?? []).length === 0}
- icon={<Settings2 />}
- tooltip="Result settings"
/>
<ExplorerToolbarAction
icon={showQuery ? <EyeOff /> : <Eye />}
@@ -152,12 +156,13 @@ export const QueryCell = ({ cell }: QueryCellProps) => {
<ExplorerQueryResults
className={cn(
- (result?.rows ?? []).length === 0
+ (result?.rows ?? []).length === 0 && view === 'table'
? 'flex items-center justify-center'
: 'overflow-x-auto'
)}
>
- <QueryResultTable result={result} />
+ {view === 'table' && <QueryResultTable result={result} />}
+ {view === 'chart' && <QueryResultChart cell={cell} result={result} />}
</ExplorerQueryResults>
<ExplorerQueryFooter className="flex items-center gap-x-2">
diff --git a/apps/studio/components/interfaces/Explorer/QueryResultTable.tsx b/apps/studio/components/interfaces/Explorer/QueryResultTable.tsx
index b3aab76c07a..ba88cb1d274 100644
--- a/apps/studio/components/interfaces/Explorer/QueryResultTable.tsx
+++ b/apps/studio/components/interfaces/Explorer/QueryResultTable.tsx
@@ -23,6 +23,8 @@ interface QueryResultTableProps {
// I'll eventually migrate the Results component over - just trying to avoid bloating
// changes wherever possible
+// [Joshen] Should be shifted into QueryCell folder
+
export const QueryResultTable = ({ result }: QueryResultTableProps) => {
const { rows, error, autoLimit } = result ?? {}
diff --git a/apps/studio/components/interfaces/Explorer/hooks.ts b/apps/studio/components/interfaces/Explorer/hooks.ts
index 4ddb6c9e012..d4eedf60c54 100644
--- a/apps/studio/components/interfaces/Explorer/hooks.ts
+++ b/apps/studio/components/interfaces/Explorer/hooks.ts
@@ -46,6 +46,8 @@ This is a sample paragraph to demonstrate the Markdown cells
{
_tag: 'database_cell',
id: generateUuid(),
+ view: 'table',
+ chart: undefined,
unchecked_sql: untrustedSql('select * from colors;'),
row_limit: 100,
},
diff --git a/apps/studio/components/ui/QueryBlock/QueryBlock.utils.ts b/apps/studio/components/ui/QueryBlock/QueryBlock.utils.ts
index 342f5b17a60..8a18bde4688 100644
--- a/apps/studio/components/ui/QueryBlock/QueryBlock.utils.ts
+++ b/apps/studio/components/ui/QueryBlock/QueryBlock.utils.ts
@@ -1,5 +1,3 @@
-import type { ChartConfig } from '@/components/interfaces/SQLEditor/UtilityPanel/ChartConfig'
-
export const checkHasNonPositiveValues = (data: Record<string, unknown>[], key: string): boolean =>
data.some((row) => (row[key] as number) <= 0)
@@ -47,7 +45,10 @@ export const formatLogTick = (value: number): string => {
return value.toLocaleString()
}
-export const getCumulativeResults = (results: { rows: readonly any[] }, config: ChartConfig) => {
+export const getCumulativeResults = (
+ results: { rows: readonly any[] },
+ config: { yKey: string }
+) => {
if (!results?.rows?.length) {
return []
}
diff --git a/apps/studio/data/content/notebooks/notebook-schema.ts b/apps/studio/data/content/notebooks/notebook-schema.ts
index ada1639c751..545267b75e9 100644
--- a/apps/studio/data/content/notebooks/notebook-schema.ts
+++ b/apps/studio/data/content/notebooks/notebook-schema.ts
@@ -14,9 +14,12 @@ const isoDateTimeSchema = z.string().transform((raw, ctx) => {
})
const chartConfigSchema = z.object({
+ type: z.enum(['bar', 'line']),
x_column: z.string(),
- y_column: z.string(),
+ y_columns: z.array(z.string()),
cumulative: z.boolean(),
+ scale: z.enum(['linear', 'log']).default('linear'),
+ show_labels: z.boolean(),
})
const absoluteTimeRangeSchema = z.object({
@@ -48,6 +51,7 @@ const databaseCellSchema = z.object({
title: z.string().optional(),
sql: z.string(),
row_limit: z.number(),
+ view: z.enum(['table', 'chart']).default('table').optional(),
chart: chartConfigSchema.optional(),
})
diff --git a/apps/studio/lib/ai/tools/mock-tools.ts b/apps/studio/lib/ai/tools/mock-tools.ts
index 2ceb1b452b2..a5fc459e814 100644
--- a/apps/studio/lib/ai/tools/mock-tools.ts
+++ b/apps/studio/lib/ai/tools/mock-tools.ts
@@ -187,7 +187,14 @@ export const MOCK_NOTEBOOKS_DATA: MockNotebook[] = [
title: 'Signups per day',
sql: "select date_trunc('day', created_at) as day, count(*) as signups\nfrom auth.users\ngroup by day\norder by day desc",
row_limit: 30,
- chart: { x_column: 'day', y_column: 'signups', cumulative: false },
+ chart: {
+ x_column: 'day',
+ y_columns: ['signups'],
+ cumulative: false,
+ type: 'line',
+ scale: 'log',
+ show_labels: false,
+ },
},
{
_tag: 'log_cell',
diff --git a/apps/studio/state/notebooks/notebooks-state.ts b/apps/studio/state/notebooks/notebooks-state.ts
index 3f713c147d7..f9f3054d934 100644
--- a/apps/studio/state/notebooks/notebooks-state.ts
+++ b/apps/studio/state/notebooks/notebooks-state.ts
@@ -1,6 +1,6 @@
import { useParams } from 'common'
import { useMemo } from 'react'
-import { proxy, snapshot, useSnapshot } from 'valtio'
+import { proxy, snapshot, useSnapshot, type Snapshot } from 'valtio'
import { proxyMap } from 'valtio/utils'
import type { Notebook, StateNotebook } from './types'
@@ -82,12 +82,12 @@ export const notebooksState = proxy({
skipSave,
}: {
id: string
- cells: Notebooks.Cell[]
+ cells: Snapshot<Notebooks.Cell>[]
skipSave?: boolean
}) => {
const stateNotebook = notebooksState.notebooks[id]
if (!stateNotebook?.notebook.content) return
- stateNotebook.notebook.content.cells = cells
+ stateNotebook.notebook.content.cells = cells as Notebooks.Cell[]
stateNotebook.status = statusOnEdit(stateNotebook.status)
if (!skipSave) notebooksState.needsSaving.set(id, false)
},
diff --git a/apps/studio/tests/components/ui/QueryBlock/QueryBlock.utils.test.ts b/apps/studio/tests/components/ui/QueryBlock/QueryBlock.utils.test.ts
index b48ad9aafaf..a5af0a97f54 100644
--- a/apps/studio/tests/components/ui/QueryBlock/QueryBlock.utils.test.ts
+++ b/apps/studio/tests/components/ui/QueryBlock/QueryBlock.utils.test.ts
@@ -78,25 +78,11 @@ describe('formatLogTick', () => {
describe('getCumulativeResults', () => {
it('returns empty array when results are empty', () => {
- expect(
- getCumulativeResults(
- { rows: [] },
- { type: 'bar', xKey: 'x', yKey: 'y', cumulative: false, showLabels: false, showGrid: false }
- )
- ).toEqual([])
+ expect(getCumulativeResults({ rows: [] }, { yKey: 'y' })).toEqual([])
})
it('returns empty array when results are undefined', () => {
- expect(
- getCumulativeResults(undefined as any, {
- type: 'bar',
- xKey: 'x',
- yKey: 'y',
- cumulative: false,
- showLabels: false,
- showGrid: false,
- })
- ).toEqual([])
+ expect(getCumulativeResults(undefined as any, { yKey: 'y' })).toEqual([])
})
it('accumulates yKey values across rows', () => {
diff --git a/packages/ui-patterns/src/Chart/charts/chart-bar.tsx b/packages/ui-patterns/src/Chart/charts/chart-bar.tsx
index c9de5ef6acf..79c0f16f512 100644
--- a/packages/ui-patterns/src/Chart/charts/chart-bar.tsx
+++ b/packages/ui-patterns/src/Chart/charts/chart-bar.tsx
@@ -22,10 +22,14 @@ const CHART_COLORS = {
BRAND_HOVER: 'hsl(var(--brand-500))',
}
-export type ChartBarTick = {
- timestamp: string
- [key: string]: string | number
-}
+export type ChartBarTick =
+ | {
+ timestamp: string
+ [key: string]: string | number
+ }
+ | {
+ [key: string]: string | number
+ }
export type ChartHighlight = {
handleMouseDown: (e: { activeLabel?: string; coordinates?: string }) => void
@@ -45,6 +49,7 @@ export type ChartHighlightAction = {
export interface ChartBarProps {
data: ChartBarTick[]
+ xKey?: string
dataKey: string
config?: ChartConfig
onBarClick?: (datum: ChartBarTick, tooltipData?: CategoricalChartState) => void
@@ -59,6 +64,7 @@ export interface ChartBarProps {
cursor?: string
showGrid?: boolean
showYAxis?: boolean
+ showXAxis?: boolean
YAxisProps?: {
tick?: boolean
tickFormatter?: (value: any) => string
@@ -69,6 +75,7 @@ export interface ChartBarProps {
export const ChartBar = ({
data,
+ xKey = 'timestamp',
dataKey,
config,
onBarClick,
@@ -83,6 +90,7 @@ export const ChartBar = ({
cursor,
showGrid = false,
showYAxis = false,
+ showXAxis = false,
YAxisProps,
}: ChartBarProps) => {
const [focusDataIndex, setFocusDataIndex] = useState<number | null>(null)
@@ -107,6 +115,18 @@ export const ChartBar = ({
const chartCursor = cursor || (chartHighlight ? 'crosshair' : 'default')
+ const xAxisConfig = {
+ angle: 0,
+ dataKey: xKey,
+ tick: showXAxis
+ ? { fill: 'var(--color-foreground-lighter)', fontSize: 10, fontFamily: 'var(--font-mono)' }
+ : false,
+ hide: !showXAxis,
+ interval: 'preserveStartEnd' as const,
+ axisLine: { stroke: CHART_COLORS.AXIS },
+ tickLine: { stroke: CHART_COLORS.AXIS },
+ }
+
const yAxisConfig = {
tick: showYAxis
? { fill: 'var(--color-foreground-lighter)', fontSize: 10, fontFamily: 'var(--font-mono)' }
@@ -143,7 +163,7 @@ export const ChartBar = ({
}
if (chartHighlight) {
- const activeTimestamp = data[e.activeTooltipIndex]?.timestamp
+ const activeTimestamp = data[e.activeTooltipIndex]?.[xKey]
chartHighlight.handleMouseMove({
activeLabel: activeTimestamp?.toString(),
coordinates: e.activeLabel,
@@ -152,7 +172,7 @@ export const ChartBar = ({
}}
onMouseDown={(e: any) => {
if (chartHighlight && e.activeTooltipIndex !== undefined) {
- const activeTimestamp = data[e.activeTooltipIndex]?.timestamp
+ const activeTimestamp = data[e.activeTooltipIndex]?.[xKey]
chartHighlight.handleMouseDown({
activeLabel: activeTimestamp?.toString(),
coordinates: e.activeLabel,
@@ -180,18 +200,14 @@ export const ChartBar = ({
>
{showGrid && <CartesianGrid vertical={false} stroke={CHART_COLORS.AXIS} />}
<YAxis {...yAxisConfig} />
- <XAxis
- dataKey="timestamp"
- interval={data.length - 2}
- tick={false}
- axisLine={{ stroke: CHART_COLORS.AXIS }}
- tickLine={{ stroke: CHART_COLORS.AXIS }}
- />
+ <XAxis {...xAxisConfig} />
<ChartTooltip
content={
<ChartTooltipContent
className="text-foreground-light -mt-5"
- labelFormatter={(v: string) => dayjs(v).format(DateTimeFormat)}
+ labelFormatter={(v: string) =>
+ xKey === 'timestamp' ? dayjs(v).format(DateTimeFormat) : 'Value'
+ }
/>
}
/>
@@ -217,10 +233,11 @@ export const ChartBar = ({
</Bar>
</RechartBarChart>
</ChartContainer>
- {data && data.length > 0 && (
+
+ {xKey === 'timestamp' && data && data.length > 0 && (
<div className="text-foreground-lighter -mt-6 flex items-center justify-between text-[10px] font-mono">
- <span>{dayjs(data[0]['timestamp']).format(DateTimeFormat)}</span>
- <span>{dayjs(data[data.length - 1]?.['timestamp']).format(DateTimeFormat)}</span>
+ <span>{dayjs(data[0][xKey]).format(DateTimeFormat)}</span>
+ <span>{dayjs(data[data.length - 1]?.[xKey]).format(DateTimeFormat)}</span>
</div>
)}
</div>
diff --git a/packages/ui-patterns/src/Chart/charts/chart-line.tsx b/packages/ui-patterns/src/Chart/charts/chart-line.tsx
index 2ecfa742474..1811933d845 100644
--- a/packages/ui-patterns/src/Chart/charts/chart-line.tsx
+++ b/packages/ui-patterns/src/Chart/charts/chart-line.tsx
@@ -22,10 +22,14 @@ const CHART_COLORS = {
BRAND_HOVER: 'hsl(var(--brand-500))',
}
-export type ChartLineTick = {
- timestamp: string
- [key: string]: string | number
-}
+export type ChartLineTick =
+ | {
+ timestamp: string
+ [key: string]: string | number
+ }
+ | {
+ [key: string]: string | number
+ }
export type ChartHighlight = {
handleMouseDown: (e: { activeLabel?: string; coordinates?: string }) => void
@@ -53,6 +57,7 @@ export type ChartReferenceLine = {
export interface ChartLineProps {
data: ChartLineTick[]
+ xKey?: string
dataKey: string
dataKeys?: string[]
config?: ChartConfig
@@ -67,6 +72,7 @@ export interface ChartLineProps {
showHighlightArea?: boolean
cursor?: string
showGrid?: boolean
+ showXAxis?: boolean
showYAxis?: boolean
YAxisProps?: {
tick?: boolean
@@ -80,6 +86,7 @@ export interface ChartLineProps {
export const ChartLine = ({
data,
+ xKey = 'timestamp',
dataKey,
dataKeys,
config,
@@ -94,6 +101,7 @@ export const ChartLine = ({
showHighlightArea = true,
cursor,
showGrid = false,
+ showXAxis = false,
showYAxis = false,
YAxisProps,
strokeWidth = 1.5,
@@ -124,6 +132,18 @@ export const ChartLine = ({
const chartCursor = cursor || (chartHighlight ? 'crosshair' : 'default')
+ const xAxisConfig = {
+ angle: 0,
+ dataKey: xKey,
+ tick: showXAxis
+ ? { fill: 'var(--color-foreground-lighter)', fontSize: 10, fontFamily: 'var(--font-mono)' }
+ : false,
+ hide: !showXAxis,
+ interval: 'preserveStartEnd' as const,
+ axisLine: { stroke: CHART_COLORS.AXIS },
+ tickLine: { stroke: CHART_COLORS.AXIS },
+ }
+
const yAxisConfig = {
tick: showYAxis
? { fill: 'var(--color-foreground-lighter)', fontSize: 10, fontFamily: 'var(--font-mono)' }
@@ -168,7 +188,7 @@ export const ChartLine = ({
}
if (chartHighlight) {
- const activeTimestamp = data[e.activeTooltipIndex]?.timestamp
+ const activeTimestamp = data[e.activeTooltipIndex]?.[xKey]
chartHighlight.handleMouseMove({
activeLabel: activeTimestamp?.toString(),
coordinates: e.activeLabel,
@@ -177,7 +197,7 @@ export const ChartLine = ({
}}
onMouseDown={(e: any) => {
if (chartHighlight && e.activeTooltipIndex !== undefined) {
- const activeTimestamp = data[e.activeTooltipIndex]?.timestamp
+ const activeTimestamp = data[e.activeTooltipIndex]?.[xKey]
chartHighlight.handleMouseDown({
activeLabel: activeTimestamp?.toString(),
coordinates: e.activeLabel,
@@ -205,18 +225,14 @@ export const ChartLine = ({
>
{showGrid && <CartesianGrid vertical={false} stroke={CHART_COLORS.AXIS} />}
<YAxis {...yAxisConfig} />
- <XAxis
- dataKey="timestamp"
- interval={data.length - 2}
- tick={false}
- axisLine={{ stroke: CHART_COLORS.AXIS }}
- tickLine={{ stroke: CHART_COLORS.AXIS }}
- />
+ <XAxis {...xAxisConfig} />
<ChartTooltip
content={
<ChartTooltipContent
className="text-foreground-light -mt-5"
- labelFormatter={(v: string) => dayjs(v).format(DateTimeFormat)}
+ labelFormatter={(v: string) =>
+ xKey === 'timestamp' ? dayjs(v).format(DateTimeFormat) : 'Value'
+ }
formatter={(value, name, item) => {
const key = String(item.dataKey || name || dataKey)
const itemConfig = chartConfig[key]
@@ -295,10 +311,11 @@ export const ChartLine = ({
})}
</RechartAreaChart>
</ChartContainer>
- {data && data.length > 0 && (
+
+ {xKey === 'timestamp' && data && data.length > 0 && (
<div className="text-foreground-lighter -mt-6 flex items-center justify-between text-[10px] font-mono">
- <span>{dayjs(data[0]['timestamp']).format(DateTimeFormat)}</span>
- <span>{dayjs(data[data.length - 1]?.['timestamp']).format(DateTimeFormat)}</span>
+ <span>{dayjs(data[0][xKey]).format(DateTimeFormat)}</span>
+ <span>{dayjs(data[data.length - 1]?.[xKey]).format(DateTimeFormat)}</span>
</div>
)}
</div>