mirror of
https://github.com/supabase/supabase.git
synced 2026-12-06 08:29:01 +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>
340 lines
12 KiB
TypeScript
340 lines
12 KiB
TypeScript
import { useParams } from 'common'
|
|
import {
|
|
AlertTriangleIcon,
|
|
BookOpenIcon,
|
|
ChartLineIcon,
|
|
ChevronDownIcon,
|
|
SparklesIcon,
|
|
WrenchIcon,
|
|
} from 'lucide-react'
|
|
import {
|
|
Alert,
|
|
AlertDescription,
|
|
AlertTitle,
|
|
Button,
|
|
cn,
|
|
DropdownMenu,
|
|
DropdownMenuContent,
|
|
DropdownMenuItem,
|
|
DropdownMenuTrigger,
|
|
} from 'ui'
|
|
|
|
import {
|
|
DISK_SPACE_EXHAUSTION_DESCRIPTION,
|
|
isResourceWarningMessageKey,
|
|
RESOURCE_WARNING_MESSAGES,
|
|
type ResourceWarningMessageKey,
|
|
} from './ResourceExhaustionWarningBanner.constants'
|
|
import {
|
|
applyResourceList,
|
|
getResourceWarningAiPrompt,
|
|
getResourceWarningCorrectionUrl,
|
|
getTroubleshootItems,
|
|
getWarningContent,
|
|
isComputeUpgradeWarning,
|
|
type TroubleshootItem,
|
|
} from './ResourceExhaustionWarningBanner.utils'
|
|
import { SIDEBAR_KEYS } from '@/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'
|
|
import { DynamicLink } from '@/components/ui/DynamicLink'
|
|
import { useResourceWarningsQuery } from '@/data/usage/resource-warnings-query'
|
|
import { useProjectDiskLimits } from '@/hooks/misc/useProjectDiskLimits'
|
|
import { useRoutePattern } from '@/hooks/misc/useRoutePattern'
|
|
import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
|
|
import { useShowDiskIOBurstBalanceChart } from '@/hooks/misc/useShowDiskIOBurstBalanceChart'
|
|
import { useTrack } from '@/lib/telemetry/track'
|
|
import { useAiAssistantStateSnapshot } from '@/state/ai-assistant-state'
|
|
import { useSidebarManagerSnapshot } from '@/state/sidebar-manager-state'
|
|
|
|
type LinkedTroubleshootItem = Extract<TroubleshootItem, { kind: 'metrics' | 'docs' }>
|
|
type ConfiguredResourceWarning = Exclude<ResourceWarningMessageKey, 'multiple_resource_warnings'>
|
|
|
|
const isConfiguredResourceWarning = (property: string): property is ConfiguredResourceWarning =>
|
|
isResourceWarningMessageKey(property) && property !== 'multiple_resource_warnings'
|
|
|
|
const MULTIPLE_RESOURCE_WARNING_NO_AI_DESCRIPTION =
|
|
'Use the Troubleshoot menu to review the affected resources and resolve these warnings.'
|
|
const MULTIPLE_RESOURCE_MIXED_SEVERITY_TITLE =
|
|
"Resource warnings for {resources} are affecting your project's performance"
|
|
|
|
const TroubleshootMenuItem = ({
|
|
item,
|
|
onTroubleshootClick,
|
|
onAskAI,
|
|
}: {
|
|
item: TroubleshootItem
|
|
onTroubleshootClick: (item: LinkedTroubleshootItem) => void
|
|
onAskAI: () => void
|
|
}) => {
|
|
if (item.kind === 'ai') {
|
|
return (
|
|
<DropdownMenuItem className="flex items-center gap-x-2 cursor-pointer" onClick={onAskAI}>
|
|
<SparklesIcon size={14} />
|
|
{item.menuLabel}
|
|
</DropdownMenuItem>
|
|
)
|
|
}
|
|
if (item.kind === 'metrics') {
|
|
return (
|
|
<DropdownMenuItem asChild onClick={() => onTroubleshootClick(item)}>
|
|
<DynamicLink href={item.href} className="flex items-center gap-x-2 cursor-pointer">
|
|
<ChartLineIcon size={14} />
|
|
{item.menuLabel}
|
|
</DynamicLink>
|
|
</DropdownMenuItem>
|
|
)
|
|
}
|
|
return (
|
|
<DropdownMenuItem asChild onClick={() => onTroubleshootClick(item)}>
|
|
<a
|
|
href={item.href}
|
|
target="_blank"
|
|
rel="noreferrer"
|
|
className="flex items-center gap-x-2 cursor-pointer"
|
|
>
|
|
<BookOpenIcon size={14} />
|
|
{item.menuLabel}
|
|
</a>
|
|
</DropdownMenuItem>
|
|
)
|
|
}
|
|
|
|
export const ResourceExhaustionWarningBanner = () => {
|
|
const { ref } = useParams()
|
|
const routePattern = useRoutePattern()
|
|
const { data: organization, isLoading: isOrgLoading } = useSelectedOrganizationQuery()
|
|
const { limits: diskLimits } = useProjectDiskLimits()
|
|
const diskIoBaselineLabel =
|
|
typeof diskLimits?.baselineThroughputMBps === 'number'
|
|
? `${diskLimits.baselineThroughputMBps} MB/s`
|
|
: 'its baseline'
|
|
const applyDiskIoBaseline = (text?: string) =>
|
|
text ? text.replace(/\{baseline\}/g, diskIoBaselineLabel) : text
|
|
const { openSidebar } = useSidebarManagerSnapshot()
|
|
const aiSnap = useAiAssistantStateSnapshot()
|
|
const track = useTrack()
|
|
const showBurstBalanceChart = useShowDiskIOBurstBalanceChart()
|
|
const { data: resourceWarnings } = useResourceWarningsQuery({ ref: ref })
|
|
// [Joshen Cleanup] JFYI this client side filtering can be cleaned up once BE changes are live which will only return the warnings based on the provided ref
|
|
const projectResourceWarnings = (resourceWarnings ?? [])?.find(
|
|
(warning) => warning.project === ref
|
|
)
|
|
|
|
// [Joshen] Read only takes higher precedence over multiple resource warnings
|
|
const activeWarnings: ConfiguredResourceWarning[] =
|
|
projectResourceWarnings !== undefined
|
|
? projectResourceWarnings.is_readonly_mode_enabled
|
|
? ['is_readonly_mode_enabled']
|
|
: Object.keys(projectResourceWarnings).filter(
|
|
(property): property is ConfiguredResourceWarning =>
|
|
property !== 'project' &&
|
|
property !== 'is_readonly_mode_enabled' &&
|
|
isConfiguredResourceWarning(property) &&
|
|
projectResourceWarnings[property] !== null
|
|
)
|
|
: []
|
|
|
|
const hasCriticalWarning =
|
|
projectResourceWarnings !== undefined
|
|
? activeWarnings.some((warningType) => projectResourceWarnings[warningType] === 'critical')
|
|
: false
|
|
const hasWarningSeverity =
|
|
projectResourceWarnings !== undefined
|
|
? activeWarnings.some((warningType) => projectResourceWarnings[warningType] === 'warning')
|
|
: false
|
|
const hasMixedWarningSeverities = hasCriticalWarning && hasWarningSeverity
|
|
const isCritical = activeWarnings.includes('is_readonly_mode_enabled') || hasCriticalWarning
|
|
|
|
const warningContent =
|
|
projectResourceWarnings !== undefined
|
|
? getWarningContent(projectResourceWarnings, activeWarnings[0], 'bannerContent')
|
|
: undefined
|
|
const aiPrompt = getResourceWarningAiPrompt(activeWarnings)
|
|
const multipleWarningDescription =
|
|
aiPrompt === undefined
|
|
? MULTIPLE_RESOURCE_WARNING_NO_AI_DESCRIPTION
|
|
: RESOURCE_WARNING_MESSAGES.multiple_resource_warnings.bannerContent[
|
|
hasCriticalWarning ? 'critical' : 'warning'
|
|
].description
|
|
const multipleWarningTitle = hasMixedWarningSeverities
|
|
? MULTIPLE_RESOURCE_MIXED_SEVERITY_TITLE
|
|
: RESOURCE_WARNING_MESSAGES.multiple_resource_warnings.bannerContent[
|
|
hasCriticalWarning ? 'critical' : 'warning'
|
|
].title
|
|
|
|
const title = applyDiskIoBaseline(
|
|
applyResourceList(
|
|
activeWarnings.length > 1 ? multipleWarningTitle : warningContent?.title,
|
|
activeWarnings
|
|
)
|
|
)
|
|
|
|
const isFreePlan = organization?.plan?.id === 'free'
|
|
const diskSpaceDescription = (() => {
|
|
if (organization === undefined) return warningContent?.description
|
|
return isFreePlan
|
|
? DISK_SPACE_EXHAUSTION_DESCRIPTION.free
|
|
: DISK_SPACE_EXHAUSTION_DESCRIPTION.paid
|
|
})()
|
|
const singleWarningDescription =
|
|
activeWarnings[0] === 'disk_space_exhaustion'
|
|
? diskSpaceDescription
|
|
: warningContent?.description
|
|
|
|
const description = applyDiskIoBaseline(
|
|
applyResourceList(
|
|
activeWarnings.length > 1 ? multipleWarningDescription : singleWarningDescription,
|
|
activeWarnings
|
|
)
|
|
)
|
|
|
|
const metric =
|
|
activeWarnings.length > 1
|
|
? RESOURCE_WARNING_MESSAGES.multiple_resource_warnings.metric
|
|
: RESOURCE_WARNING_MESSAGES[activeWarnings[0]]?.metric
|
|
|
|
// True for a single compute warning, or when all active warnings are compute-related
|
|
const isComputeUpgradeMetric = isComputeUpgradeWarning(metric, activeWarnings)
|
|
|
|
const correctionUrl = getResourceWarningCorrectionUrl({
|
|
metric,
|
|
activeWarnings,
|
|
projectRef: ref,
|
|
isFreePlan,
|
|
organizationSlug: organization?.slug,
|
|
})
|
|
|
|
const buttonText = (() => {
|
|
if (isComputeUpgradeMetric) return 'Upgrade compute'
|
|
return activeWarnings.length > 1
|
|
? RESOURCE_WARNING_MESSAGES.multiple_resource_warnings.buttonText
|
|
: RESOURCE_WARNING_MESSAGES[activeWarnings[0]]?.buttonText
|
|
})()
|
|
|
|
const troubleshootItems = getTroubleshootItems({
|
|
activeWarnings,
|
|
projectRef: ref ?? 'default',
|
|
aiPrompt,
|
|
showBurstBalanceChart,
|
|
})
|
|
const soleTroubleshootItem = troubleshootItems.length === 1 ? troubleshootItems[0] : undefined
|
|
|
|
const handleAskAI = () => {
|
|
track('resource_exhaustion_banner_ai_assistant_clicked', {
|
|
warningTypes: activeWarnings,
|
|
})
|
|
openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)
|
|
aiSnap.newChat({ initialInput: aiPrompt })
|
|
}
|
|
|
|
const handleTroubleshootClick = (item: LinkedTroubleshootItem) => {
|
|
track('resource_exhaustion_banner_troubleshoot_clicked', {
|
|
troubleshootAction: item.kind,
|
|
warningType: item.warningType,
|
|
warningTypes: activeWarnings,
|
|
destination: item.href,
|
|
})
|
|
}
|
|
|
|
const hasNoWarnings = activeWarnings.length === 0
|
|
const hasNoWarningContent =
|
|
warningContent === undefined || (!warningContent?.title && !warningContent?.description)
|
|
const isUsageOrInfraPage =
|
|
routePattern.endsWith('/usage') || routePattern.endsWith('/infrastructure')
|
|
// Compute warnings now link to infrastructure, so they should remain visible on usage.
|
|
const onUsageOrInfraAndNotInReadOnlyMode =
|
|
isUsageOrInfraPage &&
|
|
!activeWarnings.includes('is_readonly_mode_enabled') &&
|
|
!isComputeUpgradeMetric
|
|
// Suppress when already on the target page (no-op CTA). Paid-plan compute warnings link to
|
|
// infrastructure; free-plan links to billing instead, so we keep the banner visible for them.
|
|
const shouldSuppressOnInfrastructurePage =
|
|
routePattern.endsWith('settings/infrastructure') &&
|
|
(activeWarnings.includes('is_readonly_mode_enabled') || (isComputeUpgradeMetric && !isFreePlan))
|
|
|
|
if (
|
|
hasNoWarnings ||
|
|
hasNoWarningContent ||
|
|
onUsageOrInfraAndNotInReadOnlyMode ||
|
|
shouldSuppressOnInfrastructurePage
|
|
) {
|
|
return null
|
|
}
|
|
|
|
return (
|
|
<Alert
|
|
variant={isCritical ? 'destructive' : 'warning'}
|
|
className={cn(
|
|
'flex items-center justify-between',
|
|
'border-0 border-r-0 rounded-none [&>svg]:left-6 px-6 [&>svg]:w-[26px] [&>svg]:h-[26px]'
|
|
)}
|
|
>
|
|
<AlertTriangleIcon />
|
|
<div className="">
|
|
<AlertTitle>{title}</AlertTitle>
|
|
<AlertDescription>{description}</AlertDescription>
|
|
</div>
|
|
<div className="flex items-center gap-x-2">
|
|
{troubleshootItems.length >= 2 && (
|
|
<DropdownMenu>
|
|
<DropdownMenuTrigger asChild>
|
|
<Button icon={<WrenchIcon size={14} />} iconRight={<ChevronDownIcon size={14} />}>
|
|
Troubleshoot
|
|
</Button>
|
|
</DropdownMenuTrigger>
|
|
<DropdownMenuContent align="end">
|
|
{troubleshootItems.map((item) => (
|
|
<TroubleshootMenuItem
|
|
key={item.kind === 'ai' ? 'ai' : `${item.kind}-${item.warningType}`}
|
|
item={item}
|
|
onTroubleshootClick={handleTroubleshootClick}
|
|
onAskAI={handleAskAI}
|
|
/>
|
|
))}
|
|
</DropdownMenuContent>
|
|
</DropdownMenu>
|
|
)}
|
|
{soleTroubleshootItem?.kind === 'metrics' && (
|
|
<Button
|
|
asChild
|
|
icon={<ChartLineIcon size={14} />}
|
|
onClick={() => handleTroubleshootClick(soleTroubleshootItem)}
|
|
>
|
|
<DynamicLink href={soleTroubleshootItem.href}>
|
|
{soleTroubleshootItem.buttonLabel}
|
|
</DynamicLink>
|
|
</Button>
|
|
)}
|
|
{soleTroubleshootItem?.kind === 'docs' && (
|
|
<Button
|
|
asChild
|
|
icon={<BookOpenIcon size={14} />}
|
|
onClick={() => handleTroubleshootClick(soleTroubleshootItem)}
|
|
>
|
|
<a href={soleTroubleshootItem.href} target="_blank" rel="noreferrer">
|
|
{soleTroubleshootItem.buttonLabel}
|
|
</a>
|
|
</Button>
|
|
)}
|
|
{soleTroubleshootItem?.kind === 'ai' && (
|
|
<Button onClick={handleAskAI}>{soleTroubleshootItem.buttonLabel}</Button>
|
|
)}
|
|
{correctionUrl !== undefined && (
|
|
<Button
|
|
asChild
|
|
variant="primary"
|
|
disabled={isComputeUpgradeMetric && isOrgLoading}
|
|
onClick={() =>
|
|
track('resource_exhaustion_banner_upgrade_clicked', {
|
|
warningTypes: activeWarnings,
|
|
destination: correctionUrl,
|
|
})
|
|
}
|
|
>
|
|
<DynamicLink href={correctionUrl}>{buttonText ?? 'Check'}</DynamicLink>
|
|
</Button>
|
|
)}
|
|
</div>
|
|
</Alert>
|
|
)
|
|
}
|