Skip to content

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

Support click drag to highlight time range in timeline chart unified logs (#46149)

Joshen Limc8e1eb183628
diff --git a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.tsx b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.tsx
index a06406666aa..36d30b07916 100644
--- a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.tsx
+++ b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.tsx
@@ -428,6 +428,7 @@ export const UnifiedLogs = () => {
isFetchingCharts && 'opacity-60 transition-opacity duration-150'
)}
columnId="timestamp"
+ filterColumnId="date"
chartConfig={filteredChartConfig}
/>
</div>
diff --git a/apps/studio/components/ui/Charts/ChartHighlightActions.tsx b/apps/studio/components/ui/Charts/ChartHighlightActions.tsx
index 2babb10d0f6..ddc0460555e 100644
--- a/apps/studio/components/ui/Charts/ChartHighlightActions.tsx
+++ b/apps/studio/components/ui/Charts/ChartHighlightActions.tsx
@@ -90,7 +90,17 @@ export const ChartHighlightActions = ({
top: chartHighlight?.popoverPosition?.y + 'px' || 0,
}}
/>
- <DropdownMenuContent className="flex flex-col gap-1 p-1 w-fit text-left">
+ <DropdownMenuContent
+ className="flex flex-col gap-1 p-1 w-fit text-left"
+ onEscapeKeyDown={() => clearHighlight?.()}
+ onInteractOutside={(e) => {
+ const target = e.target as Element | null
+ // If the user clicked on a chart, handleMouseDown will manage the new selection.
+ // Calling clearHighlight here would race with it and clobber the new state.
+ if (target?.closest('.recharts-wrapper')) return
+ clearHighlight?.()
+ }}
+ >
<DropdownMenuLabel className="flex items-center justify-center text-foreground-light font-mono gap-x-2 text-xs">
<span>{formatChartDate(selectedRangeStart!, 'MMM D, H:mm')}</span>
<ArrowRight size={10} />
diff --git a/apps/studio/components/ui/DataTable/TimelineChart.tsx b/apps/studio/components/ui/DataTable/TimelineChart.tsx
index fb28fc44fc0..64524e9cc1d 100644
--- a/apps/studio/components/ui/DataTable/TimelineChart.tsx
+++ b/apps/studio/components/ui/DataTable/TimelineChart.tsx
@@ -1,10 +1,16 @@
import { format } from 'date-fns'
-import { useMemo, useState } from 'react'
+import { SearchIcon } from 'lucide-react'
+import { useTheme } from 'next-themes'
+import { useMemo } from 'react'
import { Bar, BarChart, CartesianGrid, ReferenceArea, XAxis } from 'recharts'
-import type { CategoricalChartFunc } from 'recharts/types/chart/generateCategoricalChart'
import { ChartConfig, ChartContainer, ChartTooltip, ChartTooltipContent, cn } from 'ui'
import { useDataTable } from './providers/DataTableProvider'
+import {
+ ChartHighlightAction,
+ ChartHighlightActions,
+} from '@/components/ui/Charts/ChartHighlightActions'
+import { useChartHighlight } from '@/components/ui/Charts/useChartHighlight'
export type BaseChartSchema = { timestamp: number; [key: string]: number }
export const description = 'A stacked bar chart'
@@ -16,6 +22,11 @@ interface TimelineChartProps<TChart extends BaseChartSchema> {
* TBD: if using keyof TData to be closer to the data table props
*/
columnId: string
+ /**
+ * Optional override for the column id used when applying the time range filter.
+ * Defaults to `columnId` if not provided.
+ */
+ filterColumnId?: string
/**
* Same data as of the InfiniteQueryMeta.
*/
@@ -27,12 +38,18 @@ export function TimelineChart<TChart extends BaseChartSchema>({
data,
className,
columnId,
+ filterColumnId,
chartConfig,
}: TimelineChartProps<TChart>) {
+ const resolvedFilterColumnId = filterColumnId ?? columnId
+ const { resolvedTheme } = useTheme()
+ const isDarkMode = resolvedTheme?.includes('dark')
+
const { table } = useDataTable()
- const [refAreaLeft, setRefAreaLeft] = useState<string | null>(null)
- const [refAreaRight, setRefAreaRight] = useState<string | null>(null)
- const [isSelecting, setIsSelecting] = useState(false)
+ const chartHighlight = useChartHighlight()
+
+ const showHighlight =
+ chartHighlight?.left && chartHighlight?.right && chartHighlight?.left !== chartHighlight?.right
// REMINDER: date has to be a string for tooltip label to work - don't ask me why
const chart = useMemo(
@@ -52,101 +69,102 @@ export function TimelineChart<TChart extends BaseChartSchema>({
return { interval, period: calculatePeriod(interval) }
}, [data])
- const handleMouseDown: CategoricalChartFunc = (e) => {
- if (e.activeLabel) {
- setRefAreaLeft(e.activeLabel)
- setIsSelecting(true)
- }
- }
-
- const handleMouseMove: CategoricalChartFunc = (e) => {
- if (isSelecting && e.activeLabel) {
- setRefAreaRight(e.activeLabel)
- }
- }
-
- const handleMouseUp: CategoricalChartFunc = () => {
- if (refAreaLeft && refAreaRight) {
- const [left, right] = [refAreaLeft, refAreaRight].sort(
- (a, b) => new Date(a).getTime() - new Date(b).getTime()
- )
- table.getColumn(columnId)?.setFilterValue([new Date(left), new Date(right)])
- }
- setRefAreaLeft(null)
- setRefAreaRight(null)
- setIsSelecting(false)
- }
+ const highlightActions: ChartHighlightAction[] = useMemo(
+ () => [
+ {
+ id: 'zoom-in',
+ label: 'Filter logs to selected range',
+ icon: <SearchIcon className="text-foreground-lighter" size={12} />,
+ onSelect: ({ start, end, clear }) => {
+ const [left, right] = [start, end].sort(
+ (a, b) => new Date(a).getTime() - new Date(b).getTime()
+ )
+ table.getColumn(resolvedFilterColumnId)?.setFilterValue([new Date(left), new Date(right)])
+ clear()
+ },
+ },
+ ],
+ [table, resolvedFilterColumnId]
+ )
return (
- <ChartContainer
- config={chartConfig}
- className={cn(
- 'aspect-auto h-[60px] w-full px-2',
- '[&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted/50', // otherwise same color as 200
- 'select-none', // disable text selection
- className
- )}
- >
- <BarChart
- accessibilityLayer
- data={chart}
- margin={{ top: 0, left: 0, right: 0, bottom: 0 }}
- onMouseDown={handleMouseDown}
- onMouseMove={handleMouseMove}
- onMouseUp={handleMouseUp}
- onMouseLeave={handleMouseUp}
- style={{ cursor: 'crosshair' }}
+ <div className="relative w-full">
+ <ChartContainer
+ config={chartConfig}
+ className={cn(
+ 'aspect-auto h-[60px] w-full px-2',
+ '[&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted/50', // otherwise same color as 200
+ 'select-none', // disable text selection
+ className
+ )}
>
- <CartesianGrid vertical={false} horizontal={false} />
- <XAxis
- dataKey={columnId}
- tickLine={false}
- minTickGap={32}
- axisLine={false}
- interval="preserveStartEnd"
- tickFormatter={(value) => {
- const date = new Date(value)
- if (isNaN(date.getTime())) return 'N/A'
- if (timerange.period === '10m') {
- return format(date, 'HH:mm:ss')
- } else if (timerange.period === '1d') {
- return format(date, 'HH:mm')
- } else if (timerange.period === '1w') {
- return format(date, 'LLL dd HH:mm')
- }
- return format(date, 'LLL dd, y')
+ <BarChart
+ data={chart}
+ margin={{ top: 0, left: 0, right: 0, bottom: 0 }}
+ onMouseDown={({ activeLabel, activeTooltipIndex }) => {
+ if (activeTooltipIndex === undefined || activeTooltipIndex === null) return
+ chartHighlight.handleMouseDown({ activeLabel, coordinates: activeLabel })
}}
- />
- <ChartTooltip
- // defaultIndex={10}
- content={
- <ChartTooltipContent
- labelFormatter={(value) => {
- const date = new Date(value)
- if (isNaN(date.getTime())) return 'N/A'
- if (timerange.period === '10m') {
- return format(date, 'LLL dd, HH:mm:ss')
- }
- return format(date, 'LLL dd, y HH:mm')
- }}
- />
- }
- />
- {/* TODO: we could use the `{timestamp, ...rest} = data[0]` to dynamically create the bars but that would mean the order can be very much random */}
- <Bar dataKey="error" stackId="a" fill="var(--color-error)" />
- <Bar dataKey="warning" stackId="a" fill="var(--color-warning)" />
- <Bar dataKey="success" stackId="a" fill="var(--color-success)" />
- {refAreaLeft && refAreaRight && (
- <ReferenceArea
- x1={refAreaLeft}
- x2={refAreaRight}
- strokeOpacity={0.3}
- fill="hsl(var(--foreground))"
- fillOpacity={0.08}
+ onMouseMove={({ activeLabel, activeTooltipIndex }) => {
+ if (activeTooltipIndex === undefined || activeTooltipIndex === null) return
+ chartHighlight.handleMouseMove({ activeLabel, coordinates: activeLabel })
+ }}
+ onMouseUp={chartHighlight.handleMouseUp}
+ style={{ cursor: 'crosshair' }}
+ >
+ <CartesianGrid vertical={false} horizontal={false} />
+ <XAxis
+ dataKey={columnId}
+ tickLine={false}
+ minTickGap={32}
+ axisLine={false}
+ tickFormatter={(value) => {
+ const date = new Date(value)
+ if (isNaN(date.getTime())) return 'N/A'
+ if (timerange.period === '10m') {
+ return format(date, 'HH:mm:ss')
+ } else if (timerange.period === '1d') {
+ return format(date, 'HH:mm')
+ } else if (timerange.period === '1w') {
+ return format(date, 'LLL dd HH:mm')
+ }
+ return format(date, 'LLL dd, y')
+ }}
/>
- )}
- </BarChart>
- </ChartContainer>
+ {!chartHighlight.popoverPosition && (
+ <ChartTooltip
+ content={
+ <ChartTooltipContent
+ labelFormatter={(value) => {
+ const date = new Date(value)
+ if (isNaN(date.getTime())) return 'N/A'
+ if (timerange.period === '10m') {
+ return format(date, 'LLL dd, HH:mm:ss')
+ }
+ return format(date, 'LLL dd, y HH:mm')
+ }}
+ />
+ }
+ />
+ )}
+ {/* TODO: we could use the `{timestamp, ...rest} = data[0]` to dynamically create the bars but that would mean the order can be very much random */}
+ <Bar dataKey="error" stackId="a" fill="var(--color-error)" />
+ <Bar dataKey="warning" stackId="a" fill="var(--color-warning)" />
+ <Bar dataKey="success" stackId="a" fill="var(--color-success)" />
+ {showHighlight && (
+ <ReferenceArea
+ x1={chartHighlight.left}
+ x2={chartHighlight.right}
+ strokeOpacity={0.5}
+ stroke={isDarkMode ? '#FFFFFF' : '#0C3925'}
+ fill={isDarkMode ? '#FFFFFF' : '#0C3925'}
+ fillOpacity={0.2}
+ />
+ )}
+ </BarChart>
+ </ChartContainer>
+ <ChartHighlightActions chartHighlight={chartHighlight} actions={highlightActions} />
+ </div>
)
}