Files
Danny White 5f50338a2f fix(studio): keep region flags visible on light surfaces (#49517)
## What kind of change does this PR introduce?

Studio interface fix.

## What is the current behavior?

Region flags with light backgrounds, such as Japan, can disappear
against light Studio surfaces. Flag rendering is also repeated across
region selectors and infrastructure views.

## What is the new behavior?

Region flags use a shared `RegionFlag` component with the existing small
radius and a subtle 1px border. The treatment is applied consistently
across project creation, replication, read replicas, infrastructure, and
Edge Function observability.

| Before | After |
| --- | --- |
| <img width="746" height="246" alt="CleanShot 2026-08-25 at 14 01
07@2x"
src="https://github.com/user-attachments/assets/5ccffccd-f253-47ca-a587-e97d1e8306a8"
/> | <img width="746" height="234" alt="CleanShot 2026-08-25 at 14 09
20@2x"
src="https://github.com/user-attachments/assets/9d59f7f6-4364-4c2c-8b97-a9673616736a"
/> |

## To test

- Open the new project flow and inspect the selected region and region
menu. Confirm light flags remain visible without changing size or aspect
ratio.
- Open Database Replication and inspect region flags in the diagram and
destination form.
- Open `/project/<ref>/settings/infrastructure` and inspect flags in the
topology, map, and read replica details.
- Open Edge Function observability and inspect the region filter
options.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **UI Improvements**
* Standardized region flag displays across project creation,
replication, infrastructure, read replica, and observability views.
* Region flags now use consistent styling, rounded borders, and
rendering throughout the Studio interface.
* Improved visual consistency for selected regions, database nodes,
tooltips, and region options.
* Decorative flags in observability views are handled appropriately for
assistive technologies.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-08-25 16:25:12 +10:00

443 lines
17 KiB
TypeScript

import { Handle, Node, NodeProps, Position } from '@xyflow/react'
import { useParams } from 'common'
import dayjs from 'dayjs'
import { Database, DatabaseBackup, HelpCircle, Loader2, MoreVertical } from 'lucide-react'
import Link from 'next/link'
import { parseAsBoolean, parseAsString, useQueryStates } from 'nuqs'
import { toast } from 'sonner'
import {
Badge,
Button,
cn,
copyToClipboard,
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
Tooltip,
TooltipContent,
TooltipTrigger,
} from 'ui'
import { TimestampInfo } from 'ui-patterns/TimestampInfo'
import {
ERROR_STATES,
INIT_PROGRESS,
LoadBalancerData,
NODE_SEP,
NODE_WIDTH,
PrimaryNodeData,
REGION_NODE_HEIGHT,
ReplicaNodeData,
} from './InstanceConfiguration.constants'
import { formatSeconds } from './InstanceConfiguration.utils'
import { metricColor } from './InstanceNode.utils'
import { getReadReplicaPath } from '@/components/interfaces/Settings/Infrastructure/Infrastructure.utils'
import { REPLICA_STATUS } from '@/components/interfaces/Settings/Infrastructure/ReadReplicas/ReadReplicas.constants'
import { RegionFlag } from '@/components/ui/RegionFlag'
import { SparkBar } from '@/components/ui/SparkBar'
import {
DatabaseInitEstimations,
ReplicaInitializationStatus,
useReadReplicasStatusesQuery,
} from '@/data/read-replicas/replicas-status-query'
import { formatDatabaseID } from '@/data/read-replicas/replicas.utils'
import { useComputeMetrics } from '@/hooks/analytics/useComputeMetrics'
import { useIsFeatureEnabled } from '@/hooks/misc/useIsFeatureEnabled'
import { useDatabaseSelectorStateSnapshot } from '@/state/database-selector'
export const LoadBalancerNode = ({ data }: NodeProps<Node<LoadBalancerData>>) => {
const { ref } = useParams()
const { numDatabases } = data
return (
<>
<div className="flex flex-col rounded-sm bg-surface-100 border border-default">
<div
className="flex items-start justify-between p-3 gap-x-4"
style={{ width: NODE_WIDTH / 2 - 10 }}
>
<div className="flex gap-x-3">
<div className="min-w-8 h-8 bg-blue-600 border border-blue-800 rounded-md flex items-center justify-center">
<Database size={16} />
</div>
<div className="flex flex-col gap-y-0.5">
<p className="text-sm">API Load Balancer</p>
<p className="text-sm text-foreground-light">
Distributes incoming API requests across{' '}
<span className="text-foreground">{numDatabases} databases</span>
</p>
</div>
</div>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="text" icon={<MoreVertical />} className="px-1" />
</DropdownMenuTrigger>
<DropdownMenuContent className="w-40" side="bottom" align="end">
<DropdownMenuItem asChild className="gap-x-2">
<Link href={`/project/${ref}/integrations/data_api/overview?source=load-balancer`}>
View API URL
</Link>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
<Handle type="source" position={Position.Bottom} style={{ background: 'transparent' }} />
</>
)
}
export const PrimaryNode = ({ data }: NodeProps<Node<PrimaryNodeData>>) => {
// [Joshen] Just FYI Handles cannot be conditionally rendered
const { region, computeSize, numReplicas, numRegions, hasLoadBalancer } = data
const { ref } = useParams()
const { projectHomepageShowInstanceSize } = useIsFeatureEnabled([
'project_homepage:show_instance_size',
])
const {
cpu,
disk,
memory,
connections,
isLoading: metricsLoading,
isError: metricsError,
} = useComputeMetrics({
projectRef: ref,
})
const observabilityUrl = `/project/${ref}/observability/database`
return (
<>
<Handle
type="target"
position={Position.Top}
className={!hasLoadBalancer ? 'opacity-0' : ''}
style={{ background: 'transparent' }}
/>
<div className="flex flex-col rounded-sm bg-surface-100 border border-default">
<div
className="flex items-start justify-between p-3"
style={{ width: NODE_WIDTH / 2 - 10 }}
>
<div className="flex gap-x-3">
<div className="w-8 h-8 bg-brand-500 border border-brand-600 rounded-md flex items-center justify-center">
<Database size={16} />
</div>
<div className="flex flex-col gap-y-0.5">
<p className="text-sm">Primary Database</p>
<p className="flex items-center gap-x-1">
<span className="text-sm text-foreground-light">{region.name}</span>
</p>
<p className="flex items-center gap-x-1">
<Tooltip>
<TooltipTrigger asChild>
<span
className="text-sm transition text-foreground-light hover:text-foreground"
onClick={async () =>
await copyToClipboard(region.region, () => toast('Copied project region'))
}
>
{region.region}
</span>
</TooltipTrigger>
<TooltipContent side="bottom">Click to copy</TooltipContent>
</Tooltip>
{projectHomepageShowInstanceSize && (
<>
<span className="text-sm text-foreground-lighter">·</span>
<span className="text-sm text-foreground-light">{computeSize}</span>
</>
)}
</p>
</div>
</div>
<RegionFlag className="mt-0.5 w-8" region={region.region} />
</div>
{numReplicas > 0 && (
<div className="border-t p-3 py-2">
<p className="text-sm text-foreground-light">
<span className="text-foreground">
{numReplicas} replica{numReplicas > 1 ? 's' : ''}
</span>{' '}
deployed across{' '}
<span className="text-foreground">
{numRegions} region{numRegions > 1 ? 's' : ''}
</span>
</p>
</div>
)}
<Tooltip>
<TooltipTrigger asChild>
<Link
href={observabilityUrl}
className="border-t px-3 py-2 hover:bg-surface-200 transition flex items-center gap-x-3 text-xs"
>
{metricsLoading ? (
<div className="h-3 w-44 rounded-sm bg-surface-300 animate-pulse" />
) : metricsError ? (
<span className="text-foreground-lighter">Metrics unavailable</span>
) : (
<>
<span>
CPU <span className={metricColor(cpu)}>{cpu.toFixed(0)}%</span>
</span>
<span className="text-foreground-lighter">·</span>
<span>
Disk <span className={metricColor(disk)}>{disk.toFixed(0)}%</span>
</span>
<span className="text-foreground-lighter">·</span>
<span>
RAM <span className={metricColor(memory)}>{memory.toFixed(0)}%</span>
</span>
{connections.max > 0 && (
<>
<span className="text-foreground-lighter">·</span>
<span className="text-foreground-light">
{connections.peak}/{connections.max} conns
</span>
</>
)}
</>
)}
</Link>
</TooltipTrigger>
<TooltipContent side="bottom">Go to Database Report</TooltipContent>
</Tooltip>
</div>
<Handle
type="source"
position={Position.Bottom}
className={numReplicas === 0 ? 'opacity-0' : ''}
style={{ background: 'transparent' }}
/>
</>
)
}
export const ReplicaNode = ({ data }: NodeProps<Node<ReplicaNodeData>>) => {
const { ref } = useParams()
const { id, region, computeSize, status, inserted_at } = data
const { projectHomepageShowInstanceSize } = useIsFeatureEnabled([
'project_homepage:show_instance_size',
])
const state = useDatabaseSelectorStateSnapshot()
const [, setConnect] = useQueryStates({
showConnect: parseAsBoolean.withDefault(false),
source: parseAsString,
})
const { data: databaseStatuses } = useReadReplicasStatusesQuery({ projectRef: ref })
const { replicaInitializationStatus } =
(databaseStatuses ?? []).find((db) => db.identifier === id) || {}
const {
status: initStatus,
progress,
estimations,
error,
} = (replicaInitializationStatus as {
status?: string
progress?: string
estimations?: DatabaseInitEstimations
error?: string
}) ?? { status: undefined, progress: undefined, estimations: undefined, error: undefined }
const created = dayjs(inserted_at).format('DD MMM YYYY')
const stage = progress !== undefined ? Number(progress.split('_')[0]) : 0
const stagePercent = stage / (Object.keys(INIT_PROGRESS).length - 1)
const isInTransition =
(
[
REPLICA_STATUS.UNKNOWN,
REPLICA_STATUS.COMING_UP,
REPLICA_STATUS.GOING_DOWN,
REPLICA_STATUS.RESTORING,
REPLICA_STATUS.RESTARTING,
REPLICA_STATUS.RESIZING,
REPLICA_STATUS.INIT_READ_REPLICA,
] as string[]
).includes(status) || initStatus === ReplicaInitializationStatus.InProgress
return (
<>
<Handle type="target" position={Position.Top} style={{ background: 'transparent' }} />
<div
className="flex justify-between items-start rounded-sm bg-surface-100 border border-default p-3"
style={{ width: NODE_WIDTH / 2 - 10 }}
>
<div className="flex gap-x-3">
<div
className={cn(
'w-8 h-8 border rounded-md flex items-center justify-center',
status === REPLICA_STATUS.ACTIVE_HEALTHY &&
initStatus === ReplicaInitializationStatus.Completed
? 'bg-brand-400 border-brand-500'
: 'bg-surface-100 border-foreground/20'
)}
>
{isInTransition ? (
<Loader2 className="animate-spin" size={16} />
) : (
<DatabaseBackup size={16} />
)}
</div>
<div className="flex flex-col gap-y-0.5">
<div className="flex items-center gap-x-2">
<p className="text-sm truncate">
Replica {id.length > 0 && `(ID: ${formatDatabaseID(id)})`}
</p>
{initStatus === ReplicaInitializationStatus.InProgress ||
status === REPLICA_STATUS.COMING_UP ||
status === REPLICA_STATUS.UNKNOWN ||
status === REPLICA_STATUS.INIT_READ_REPLICA ? (
<Badge>Coming up</Badge>
) : initStatus === ReplicaInitializationStatus.Failed ||
status === REPLICA_STATUS.INIT_READ_REPLICA_FAILED ? (
<>
<Badge variant="destructive">Init failed</Badge>
<Tooltip>
<TooltipTrigger>
<HelpCircle size={16} />
</TooltipTrigger>
<TooltipContent
side="bottom"
align="end"
alignOffset={-70}
className="w-60 text-center"
>
Replica failed to initialize. Please drop this replica and spin up a new one.
</TooltipContent>
</Tooltip>
</>
) : status === REPLICA_STATUS.GOING_DOWN ? (
<Badge>Going down</Badge>
) : status === REPLICA_STATUS.RESTARTING ? (
<Badge>Restarting</Badge>
) : status === REPLICA_STATUS.RESIZING ? (
<Badge>Resizing</Badge>
) : status === REPLICA_STATUS.ACTIVE_HEALTHY ? (
<Badge variant="success">Healthy</Badge>
) : (
<Badge variant="warning">Unhealthy</Badge>
)}
</div>
<div className="my-0.5">
<p className="text-sm text-foreground-light">{region.name}</p>
<p className="flex text-sm text-foreground-light items-center gap-x-1">
<Tooltip>
<TooltipTrigger asChild>
<span
className="text-sm transition text-foreground-light hover:text-foreground"
onClick={async () =>
await copyToClipboard(region.region, () => toast('Copied replica region'))
}
>
{region.region}
</span>
</TooltipTrigger>
<TooltipContent side="bottom">Click to copy</TooltipContent>
</Tooltip>
{projectHomepageShowInstanceSize && !!computeSize && (
<>
<span className="text-foreground-lighter">·</span>
<span>{computeSize}</span>
</>
)}
</p>
</div>
{initStatus === ReplicaInitializationStatus.InProgress && progress !== undefined ? (
<Tooltip>
<TooltipTrigger asChild>
<div className="w-56">
<SparkBar
labelBottom={INIT_PROGRESS[progress as keyof typeof INIT_PROGRESS]}
labelBottomClass="text-xs normal-nums! text-foreground-light"
type="horizontal"
value={stagePercent * 100}
max={100}
barClass="bg-brand"
/>
</div>
</TooltipTrigger>
{estimations !== undefined && (
<TooltipContent asChild side="bottom">
<div className="w-56">
<p className="text-foreground-light mb-0.5">Duration estimates:</p>
{estimations.baseBackupDownloadEstimateSeconds !== undefined && (
<p>
Base backup download:{' '}
{formatSeconds(estimations.baseBackupDownloadEstimateSeconds)}
</p>
)}
{estimations.walArchiveReplayEstimateSeconds !== undefined && (
<p>
WAL archive replay:{' '}
{formatSeconds(estimations.walArchiveReplayEstimateSeconds)}
</p>
)}
</div>
</TooltipContent>
)}
</Tooltip>
) : error !== undefined ? (
<p className="text-sm text-foreground-light">
Error: {ERROR_STATES[error as keyof typeof ERROR_STATES]}
</p>
) : (
<p className="text-sm text-foreground-light">
Created:{' '}
<TimestampInfo className="text-sm" utcTimestamp={inserted_at} label={created} />
</p>
)}
</div>
</div>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="text" icon={<MoreVertical />} className="px-1" />
</DropdownMenuTrigger>
<DropdownMenuContent className="w-40" side="bottom" align="end">
<DropdownMenuItem
className="gap-x-2"
onClick={() => {
setConnect({ showConnect: true, source: id })
state.setSelectedDatabaseId(id)
}}
>
View connection string
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem className="gap-x-2">
<Link href={getReadReplicaPath(ref, id)}>Manage replica</Link>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</>
)
}
export const RegionNode = ({ data }: any) => {
const { region, numReplicas } = data
const regionNodeWidth =
20 + (NODE_WIDTH / 2 - 10) * numReplicas + (numReplicas - 1) * (NODE_SEP + 10)
return (
<div
className="relative flex justify-between rounded-sm bg-black/10 border border-default border-white/10 border-2 p-3"
style={{ width: regionNodeWidth, height: REGION_NODE_HEIGHT }}
>
<div className="absolute bottom-2 flex items-center justify-between gap-x-2">
<RegionFlag className="w-5" region={region.region} />
<p className="text-sm">{region.name}</p>
</div>
</div>
)
}