mirror of
https://github.com/supabase/supabase.git
synced 2026-12-04 07:29:16 +00:00
Part 1 of a 6-PR stack migrating all `next/link` imports in `apps/studio` onto TanStack Router's `Link` (or plain `<a>` for known external URLs) and removing `compat/next/link.tsx`. | Part | PR | Scope | | --- | --- | --- | | **1** | **#54304 ← this PR** | **`data/prefetchers/PrefetchableLink.tsx` and `components/ui/**`** | | 2 | #54305 | `components/layouts/**` and top-level shell components | | 3 | #54306 | Database, TableGridEditor, Storage, SQLEditor, BranchManagement, Branching, Functions, Realtime | | 4 | #54307 | Integrations, Settings, Observability, LogDrains, Issues, Linter, Reports, QueryPerformance, QuerySources, ConfigDrift, DiskManagement, Compute | | 5 | #54308 | Remaining `components/interfaces/**` (Org, Billing, Auth, Support, Home, SignIn, ConnectSheet, etc.) | | 6 | #54309 | Remove `compat/next/link.tsx` shim, Vite alias, and update basePath tests/docs | Migrates `data/prefetchers/PrefetchableLink.tsx` and all shared `components/ui/**` components off `next/link`. **Added:** - `apps/studio/components/ui/DynamicLink.tsx` (with unit tests) — shared `forwardRef` link wrapper for dynamic URL strings that runs `splitInternalUrl` and renders a plain `<a>` for external URLs (or same-origin URLs outside the app's `basePath`) vs TanStack `<Link>` for internal paths **Changed:** - Replaced `next/link` in `apps/studio/data/prefetchers/PrefetchableLink.tsx` and all 30 importing components under `apps/studio/components/ui/**` (`InlineLink`, `CardButton`, `CommandItemLink`, `ObservabilityLink`, `ProductMenuItem`, `ResourceItem`, `UpgradePlanButton`, `ToggleSpendCapButton`, banners, AI assistant panel links, etc.) - Used typed `<Link to="..." params={...} search={...} hash="..." />` for known internal routes, `<DynamicLink href={...} />` for dynamic/untyped URL strings (whether internal with query/hash or external), and plain `<a>` for known external links - Updated `apps/studio/routes/index.tsx` `validateSearch` return type to `{ next?: string }` so `<Link to="/">` compiles without requiring `search={{ next: undefined }}` - Updated `hooks/misc/__tests__/useTableEditorFiltersSort.navigation.test.tsx`, `PolicyTableRow.utils.test.ts`, `SupportAssistantSuccessCard.test.tsx`, and `useOrganizationRestrictions.test.tsx` to render inside a TanStack Router context (`customRender` / `RouterContextProvider`) Addresses [FE-5108](https://linear.app/supabase/issue/FE-5108/replace-the-nextlink-shim-with-tanstack-link) ## To test - [ ] Click internal and external `InlineLink`, `CardButton`, `ProductMenuItem`, and `PrefetchableLink` targets and verify client-side navigation vs external anchors - [ ] Verify banner links (upgrade, resource exhaustion, queue operations) preserve query params and hashes - [ ] Confirm Studio typecheck, lint, and unit tests pass --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
413 lines
13 KiB
TypeScript
413 lines
13 KiB
TypeScript
import { Link } from '@tanstack/react-router'
|
|
import { useParams } from 'common'
|
|
import {
|
|
ActivityIcon,
|
|
BarChartIcon,
|
|
GitCommitHorizontalIcon,
|
|
InfoIcon,
|
|
SquareTerminalIcon,
|
|
} from 'lucide-react'
|
|
import { useEffect, useState } from 'react'
|
|
import { Badge, cn, Tooltip, TooltipContent, TooltipTrigger } from 'ui'
|
|
|
|
import { formatPercentage, numberFormatter } from './Charts.utils'
|
|
import { useChartHoverState } from './useChartHoverState'
|
|
import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
|
|
import { formatDateTime, useFormatDateTime } from '@/lib/datetime'
|
|
import { formatBytes, formatBytesMinMB } from '@/lib/helpers'
|
|
|
|
export interface ChartHeaderStat {
|
|
label: string
|
|
value: number
|
|
/** Colors the dot next to the label */
|
|
tone: 'warning' | 'destructive'
|
|
}
|
|
|
|
export interface ChartHeaderProps {
|
|
title?: string
|
|
format?: string | ((value: unknown) => string)
|
|
customDateFormat?: string
|
|
minimalHeader?: boolean
|
|
displayDateInUtc?: boolean
|
|
highlightedLabel?: number | string | any | null
|
|
highlightedValue?: number | string | any | null
|
|
hideHighlightedValue?: boolean
|
|
hideHighlightedLabel?: boolean
|
|
hideHighlightArea?: boolean
|
|
hideChartType?: boolean
|
|
chartStyle?: string
|
|
onChartStyleChange?: (style: string) => void
|
|
showMaxValue?: boolean
|
|
setShowMaxValue?: (value: boolean) => void
|
|
docsUrl?: string
|
|
syncId?: string
|
|
data?: any[]
|
|
xAxisKey?: string
|
|
yAxisKey?: string
|
|
thresholdZoneAttribute?: string
|
|
thresholdZoneWarning?: {
|
|
label: string
|
|
color: string
|
|
textColor?: string
|
|
badgeLabel?: string
|
|
tooltip: string
|
|
}
|
|
xAxisIsDate?: boolean
|
|
valuePrecision?: number
|
|
shouldFormatBytes?: boolean
|
|
isNetworkChart?: boolean
|
|
isMemoryChart?: boolean
|
|
attributes?: any[]
|
|
sql?: string
|
|
titleTooltip?: string
|
|
showNewBadge?: boolean
|
|
/**
|
|
* Extra stats shown on the right of the header. Receives all chart rows, or only the hovered
|
|
* row while a point is hovered.
|
|
*/
|
|
getHeaderStats?: (rows: Record<string, unknown>[]) => ChartHeaderStat[]
|
|
/**
|
|
* Index of the point hovered on this chart. Used for `getHeaderStats` when hover isn't synced
|
|
* across charts, in which case the shared hover state doesn't reach the header.
|
|
*/
|
|
focusedIndex?: number | null
|
|
}
|
|
|
|
export const ChartHeader = ({
|
|
format,
|
|
highlightedValue,
|
|
highlightedLabel,
|
|
hideHighlightedValue = false,
|
|
hideHighlightedLabel = false,
|
|
hideHighlightArea = false,
|
|
title,
|
|
minimalHeader = false,
|
|
hideChartType = false,
|
|
chartStyle = 'bar',
|
|
onChartStyleChange,
|
|
showMaxValue = false,
|
|
setShowMaxValue,
|
|
docsUrl,
|
|
syncId,
|
|
data,
|
|
xAxisKey,
|
|
yAxisKey,
|
|
thresholdZoneAttribute,
|
|
thresholdZoneWarning,
|
|
xAxisIsDate = true,
|
|
displayDateInUtc,
|
|
customDateFormat,
|
|
valuePrecision = 2,
|
|
shouldFormatBytes = false,
|
|
isNetworkChart = false,
|
|
attributes,
|
|
sql,
|
|
titleTooltip,
|
|
showNewBadge,
|
|
isMemoryChart,
|
|
getHeaderStats,
|
|
focusedIndex,
|
|
}: ChartHeaderProps) => {
|
|
const { ref } = useParams()
|
|
const { hoveredIndex, isHovered } = useChartHoverState(syncId || 'default')
|
|
const [localHighlightedValue, setLocalHighlightedValue] = useState(highlightedValue)
|
|
const [localHighlightedLabel, setLocalHighlightedLabel] = useState(highlightedLabel)
|
|
|
|
// When `displayDateInUtc` is set the chart explicitly wants UTC labels.
|
|
// Otherwise honour the user's selected timezone via the picker.
|
|
const formatPickerDate = useFormatDateTime()
|
|
|
|
const formatHighlightedValue = (value: any) => {
|
|
if (typeof value !== 'number') {
|
|
return value
|
|
}
|
|
|
|
if (typeof format === 'function') {
|
|
return format(value)
|
|
}
|
|
|
|
if (shouldFormatBytes) {
|
|
const bytesValue = isNetworkChart ? Math.abs(value) : value
|
|
return isMemoryChart
|
|
? formatBytesMinMB(bytesValue, valuePrecision)
|
|
: formatBytes(bytesValue, valuePrecision)
|
|
}
|
|
|
|
if (format === '%') {
|
|
return formatPercentage(value, valuePrecision)
|
|
}
|
|
|
|
const formattedValue = numberFormatter(value, valuePrecision)
|
|
|
|
if (typeof format === 'string' && format) {
|
|
return `${formattedValue} ${format}`
|
|
}
|
|
|
|
return formattedValue
|
|
}
|
|
|
|
useEffect(() => {
|
|
if (syncId && hoveredIndex !== null && isHovered && data && xAxisKey && yAxisKey) {
|
|
const activeDataPoint = data[hoveredIndex]
|
|
if (activeDataPoint) {
|
|
// For stacked charts, we need to calculate the total of all attributes
|
|
// that should be included in the total (excluding reference lines, max values, etc.)
|
|
const isThresholdValueMissing =
|
|
thresholdZoneAttribute !== undefined &&
|
|
!Number.isFinite(activeDataPoint[thresholdZoneAttribute])
|
|
let newValue = isThresholdValueMissing ? 'Unavailable' : activeDataPoint[yAxisKey]
|
|
|
|
// If this is a stacked chart with multiple attributes, calculate the total
|
|
if (!isThresholdValueMissing && attributes && attributes.length > 1) {
|
|
const attributesToIgnore =
|
|
attributes
|
|
?.filter((a) => a.omitFromTotal || a.isMaxValue || a.provider === 'reference-line')
|
|
?.map((a) => a.attribute) ?? []
|
|
|
|
const totalValue = Object.entries(activeDataPoint)
|
|
.filter(([key, value]) => {
|
|
// Include only numeric values that are not in the ignore list
|
|
return (
|
|
typeof value === 'number' &&
|
|
key !== 'timestamp' &&
|
|
key !== 'period_start' &&
|
|
!attributesToIgnore.includes(key) &&
|
|
attributes.some((attr) => attr.attribute === key && attr.enabled !== false)
|
|
)
|
|
})
|
|
.reduce((sum, [_, value]) => sum + (value as number), 0)
|
|
|
|
newValue = totalValue
|
|
}
|
|
|
|
setLocalHighlightedValue(newValue)
|
|
|
|
// Update highlighted label based on sync state
|
|
let newLabel = highlightedLabel
|
|
if (xAxisIsDate && activeDataPoint[xAxisKey]) {
|
|
const value = activeDataPoint[xAxisKey] as number | string
|
|
const fmt = customDateFormat || 'YYYY-MM-DD HH:mm:ss'
|
|
newLabel = displayDateInUtc
|
|
? formatDateTime(value, { tz: 'UTC', format: fmt })
|
|
: formatPickerDate(value, fmt)
|
|
} else if (activeDataPoint[xAxisKey]) {
|
|
newLabel = activeDataPoint[xAxisKey]
|
|
}
|
|
setLocalHighlightedLabel(newLabel)
|
|
}
|
|
} else {
|
|
// Reset to original values when not syncing
|
|
setLocalHighlightedValue(highlightedValue)
|
|
setLocalHighlightedLabel(highlightedLabel)
|
|
}
|
|
}, [
|
|
hoveredIndex,
|
|
isHovered,
|
|
syncId,
|
|
data,
|
|
xAxisKey,
|
|
yAxisKey,
|
|
thresholdZoneAttribute,
|
|
xAxisIsDate,
|
|
displayDateInUtc,
|
|
customDateFormat,
|
|
highlightedValue,
|
|
highlightedLabel,
|
|
attributes,
|
|
formatPickerDate,
|
|
])
|
|
|
|
const chartTitle = (
|
|
<div className="flex flex-row items-center gap-x-2">
|
|
<div className="flex flex-row items-center gap-x-2">
|
|
<h3 className={'text-foreground-lighter ' + (minimalHeader ? 'text-xs' : 'text-sm')}>
|
|
{title}
|
|
</h3>
|
|
{titleTooltip && (
|
|
<Tooltip>
|
|
<TooltipTrigger asChild>
|
|
<InfoIcon className="w-4 h-4 text-foreground-lighter" />
|
|
</TooltipTrigger>
|
|
<TooltipContent side="bottom" className="max-w-xs">
|
|
{titleTooltip}
|
|
{docsUrl && (
|
|
<>
|
|
{' '}
|
|
<a
|
|
href={docsUrl}
|
|
target="_blank"
|
|
rel="noreferrer"
|
|
className="underline text-foreground hover:text-foreground-light"
|
|
>
|
|
Read docs
|
|
</a>
|
|
</>
|
|
)}
|
|
</TooltipContent>
|
|
</Tooltip>
|
|
)}
|
|
</div>
|
|
{!titleTooltip && docsUrl && (
|
|
<ButtonTooltip
|
|
variant="text"
|
|
className="px-1"
|
|
asChild
|
|
tooltip={{
|
|
content: {
|
|
side: 'top',
|
|
text: 'Read docs',
|
|
},
|
|
}}
|
|
>
|
|
<a href={docsUrl} target="_blank" rel="noreferrer">
|
|
<InfoIcon className="w-4 h-4 text-foreground-lighter" />
|
|
</a>
|
|
</ButtonTooltip>
|
|
)}
|
|
</div>
|
|
)
|
|
|
|
const syncedIndex = syncId && isHovered ? hoveredIndex : null
|
|
const statsIndex = syncedIndex ?? focusedIndex ?? null
|
|
const hoveredRow = statsIndex !== null ? data?.[statsIndex] : undefined
|
|
const headerStats = getHeaderStats?.(hoveredRow ? [hoveredRow] : (data ?? []))
|
|
|
|
const highlighted = (
|
|
<h4
|
|
className={`text-foreground text-xl font-normal ${minimalHeader ? 'text-base' : 'text-2xl'}`}
|
|
>
|
|
{localHighlightedValue !== undefined && formatHighlightedValue(localHighlightedValue)}
|
|
</h4>
|
|
)
|
|
const label = <h4 className="text-foreground-lighter text-xs">{localHighlightedLabel}</h4>
|
|
|
|
if (minimalHeader) {
|
|
return (
|
|
<div
|
|
className={cn('flex flex-row items-center gap-x-4', hideHighlightArea && 'hidden')}
|
|
style={{ minHeight: '1.8rem' }}
|
|
>
|
|
{title && chartTitle}
|
|
<div className="flex flex-row items-baseline gap-x-2">
|
|
{highlightedValue !== undefined && !hideHighlightedValue && highlighted}
|
|
{!hideHighlightedLabel && label}
|
|
</div>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
const hasHighlightedValue = highlightedValue !== undefined && !hideHighlightedValue
|
|
|
|
return (
|
|
<div
|
|
className={cn(
|
|
'grow flex justify-between items-start min-h-16',
|
|
hideHighlightArea && 'hidden'
|
|
)}
|
|
>
|
|
<div className="flex flex-col">
|
|
<div className="flex items-center gap-2">
|
|
{title && chartTitle}
|
|
{showNewBadge && <Badge variant="success">New</Badge>}
|
|
</div>
|
|
<div className="h-4">
|
|
{hasHighlightedValue && highlighted}
|
|
{!hideHighlightedLabel && label}
|
|
</div>
|
|
</div>
|
|
<div className="flex items-center gap-2">
|
|
{headerStats && headerStats.length > 0 && (
|
|
<div className="flex items-end gap-4 mr-2 text-foreground-light">
|
|
{headerStats.map((stat) => (
|
|
<div key={stat.label} className="flex flex-col items-end">
|
|
<div className="flex items-center gap-2">
|
|
<div
|
|
className={cn(
|
|
'w-1.5 h-1.5 rounded-full',
|
|
stat.tone === 'warning' ? 'bg-warning' : 'bg-destructive'
|
|
)}
|
|
/>
|
|
<span className="heading-meta">{stat.label}</span>
|
|
</div>
|
|
<span className="text-foreground text-base">{stat.value.toLocaleString()}</span>
|
|
</div>
|
|
))}
|
|
</div>
|
|
)}
|
|
{sql ? (
|
|
<ButtonTooltip
|
|
className="px-1.5"
|
|
asChild
|
|
tooltip={{
|
|
content: {
|
|
side: 'top',
|
|
text: 'Open in Log Explorer',
|
|
},
|
|
}}
|
|
>
|
|
<Link to="/project/$ref/logs/explorer" params={{ ref: ref ?? '_' }} search={{ q: sql }}>
|
|
<SquareTerminalIcon className="w-4 h-4 text-foreground-lighter" />
|
|
</Link>
|
|
</ButtonTooltip>
|
|
) : null}
|
|
|
|
{thresholdZoneWarning && (
|
|
<Tooltip>
|
|
<TooltipTrigger asChild>
|
|
<Badge
|
|
tabIndex={0}
|
|
className="cursor-default focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
|
aria-label={`Warning: ${thresholdZoneWarning.label}`}
|
|
style={{
|
|
color: thresholdZoneWarning.textColor ?? thresholdZoneWarning.color,
|
|
borderColor: thresholdZoneWarning.color,
|
|
backgroundColor: `color-mix(in srgb, ${thresholdZoneWarning.color} 10%, transparent)`,
|
|
}}
|
|
>
|
|
{thresholdZoneWarning.badgeLabel ?? 'Warning'}
|
|
</Badge>
|
|
</TooltipTrigger>
|
|
<TooltipContent className="max-w-xs" side="top">
|
|
<p className="font-medium">
|
|
{thresholdZoneWarning.label} threshold crossed in this time range.
|
|
</p>
|
|
<p>{thresholdZoneWarning.tooltip}</p>
|
|
</TooltipContent>
|
|
</Tooltip>
|
|
)}
|
|
{!hideChartType && onChartStyleChange && (
|
|
<ButtonTooltip
|
|
className="px-1.5"
|
|
icon={chartStyle === 'bar' ? <ActivityIcon /> : <BarChartIcon />}
|
|
onClick={() => onChartStyleChange(chartStyle === 'bar' ? 'line' : 'bar')}
|
|
tooltip={{
|
|
content: {
|
|
side: 'top',
|
|
text: `View as ${chartStyle === 'bar' ? 'line chart' : 'bar chart'}`,
|
|
},
|
|
}}
|
|
/>
|
|
)}
|
|
{setShowMaxValue && (
|
|
<ButtonTooltip
|
|
variant={showMaxValue ? 'default' : 'dashed'}
|
|
className="px-1.5"
|
|
icon={
|
|
<GitCommitHorizontalIcon
|
|
className={showMaxValue ? 'text-foreground-light' : 'text-foreground-lighter'}
|
|
/>
|
|
}
|
|
onClick={() => setShowMaxValue(!showMaxValue)}
|
|
tooltip={{
|
|
content: {
|
|
side: 'top',
|
|
text: `${showMaxValue ? 'Hide' : 'Show'} limit`,
|
|
},
|
|
}}
|
|
/>
|
|
)}
|
|
</div>
|
|
</div>
|
|
)
|
|
}
|