Files
supabase/apps/studio/components/ui/SchemaSelector.tsx
Ali Waseem e6f779ea30 feat(studio): add keyboard shortcuts to the schema visualizer (#45386)
## Summary

Adds the first batch of keyboard shortcuts for the Database → Schema
Visualizer page, following the registry pattern established for the SQL
editor and table editor.

Fixes [FE-3115](https://linear.app/supabase/issue/FE-3115).

## Shortcuts

| Shortcut | Action |
| --- | --- |
| `Mod+Shift+C` | Copy schema as SQL |
| `Mod+Shift+M` | Copy schema as Markdown |
| `D` then `P` | Download schema as PNG |
| `D` then `S` | Download schema as SVG |
| `O` then `A` | Open the auto-layout confirmation dialog |
| `O` then `S` | Open the schema selector |

All six entries appear in the Cmd+K command menu under "Shortcuts" and
in the global shortcuts sheet (`Mod+/`) under a new "Schema Visualizer"
group while the page is mounted. None are surfaced in Account →
Preferences yet (`showInSettings: false`), matching how the SQL/table
editor batches shipped.

The schema selector and auto-layout button are wrapped in the unified
`Shortcut` component so the keybind is shown on hover (Linear-style).
The dropdown items for copy/download don't get hover hints since
tooltips on dropdown items don't make sense — they're discoverable via
Cmd+K instead.

## Toasts

Each user-visible action now confirms via a sonner toast:

- `Successfully copied as SQL` — fires on Copy as SQL (button or
`Mod+Shift+C`).
- `Successfully copied as Markdown` — fires on Copy as Markdown
(dropdown or `Mod+Shift+M`).
- `Successfully downloaded as PNG` / `Successfully downloaded as SVG` —
already present in `useExportSchemaToImage`; fires on click or `D → P` /
`D → S`.
- `Failed to download current view: …` — error toast on download failure
(also pre-existing).

## Notes

- `Mod+Shift+C` and `Mod+Shift+M` collide with the SQL editor's
`results.copy-csv` / `results.copy-markdown` shortcuts. They coexist
cleanly because `useShortcut` only fires while the hook is mounted, and
the two pages live on different routes. Both labels appear in the global
shortcuts sheet honestly scoped per surface.
- `SchemaSelector` was promoted to a `forwardRef` component that spreads
extra props onto its outer `<div>`. This was needed for `<TooltipTrigger
asChild>` to attach event handlers and the ref properly — previously
they were silently dropped and the hover tooltip didn't render.
- `SchemaSelector` and the auto-layout `AlertDialog` accept controlled
`open` props now so the shortcuts can drive them and the tooltip can be
suppressed while the popover/dialog is open (`Shortcut` gained a
`tooltipOpen` passthrough for this).
- Auto-layout still pops the existing confirmation dialog rather than
running directly — destructive enough to keep the guardrail.

## Test plan

- [x] On the Schema Visualizer page, each of the six shortcuts fires the
corresponding action.
- [x] Hover the schema selector and the Auto layout button — tooltip
shows the action label and keybind badge.
- [x] Open the schema selector popover (click or `O → S`) — hover
tooltip is suppressed while open.
- [x] Open the auto-layout confirm dialog (click or `O → A`) — hover
tooltip is suppressed while open.
- [x] Cmd+K shows all six entries under "Shortcuts" while on the page;
navigating away unregisters them.
- [x] `Mod+/` shortcuts sheet has a "Schema Visualizer" group listing
all six.
- [x] Copy as SQL / Markdown each fire a confirmation toast; PNG / SVG
downloads each fire a confirmation toast.
- [x] On the SQL editor results page, `Mod+Shift+M` / `Mod+Shift+C`
still copy results (no regression from the duplicate keybinds).
- [x] The download dropdown items still work via click; PNG/SVG
downloads succeed.
- [x] All other consumers of `SchemaSelector` (~15 callsites) render
unchanged after the `forwardRef` promotion.

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

* **New Features**
* Keyboard shortcuts for schema visualizer: copy as SQL/Markdown,
download PNG/SVG, auto-layout, and focus selector
  * Success toasts when copying content to clipboard

* **Improvements**
* Schema selector and auto-layout dialog can be opened/closed via
keyboard and programmatically
* Shortcut tooltips can be suppressed when related overlays/dialogs are
open
  * Schema Visualizer added to the shortcuts reference sheet

* **Tests**
  * E2E tests dismiss transient toasts to avoid UI interference
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-05-01 07:13:37 -06:00

236 lines
8.4 KiB
TypeScript

import { PermissionAction } from '@supabase/shared-types/out/constants'
import { Check, ChevronsUpDown, Plus } from 'lucide-react'
import { ComponentPropsWithoutRef, forwardRef, useState } from 'react'
import {
Alert_Shadcn_,
AlertDescription_Shadcn_,
AlertTitle_Shadcn_,
Button,
Command_Shadcn_,
CommandEmpty_Shadcn_,
CommandGroup_Shadcn_,
CommandInput_Shadcn_,
CommandItem_Shadcn_,
CommandList_Shadcn_,
CommandSeparator_Shadcn_,
Popover_Shadcn_,
PopoverContent_Shadcn_,
PopoverTrigger_Shadcn_,
ScrollArea,
Skeleton,
} from 'ui'
import { useSchemasQuery } from '@/data/database/schemas-query'
import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
type SchemaSelectorProps = Omit<ComponentPropsWithoutRef<'div'>, 'onSelect'> & {
disabled?: boolean
size?: 'tiny' | 'small'
showError?: boolean
selectedSchemaName?: string
placeholderLabel?: string
supportSelectAll?: boolean
excludedSchemas?: string[]
stopScrollPropagation?: boolean
onSelectSchema: (name: string) => void
onSelectCreateSchema?: () => void
align?: 'start' | 'end'
open?: boolean
onOpenChange?: (open: boolean) => void
}
export const SchemaSelector = forwardRef<HTMLDivElement, SchemaSelectorProps>(
(
{
className,
disabled = false,
size = 'tiny',
showError = true,
selectedSchemaName,
placeholderLabel = 'Choose a schema...',
supportSelectAll = false,
excludedSchemas = [],
stopScrollPropagation = false,
onSelectSchema,
onSelectCreateSchema,
align = 'start',
open: openProp,
onOpenChange,
...rest
},
ref
) => {
const [internalOpen, setInternalOpen] = useState(false)
const isControlled = openProp !== undefined
const open = isControlled ? openProp : internalOpen
const setOpen = (next: boolean) => {
if (!isControlled) setInternalOpen(next)
onOpenChange?.(next)
}
const { can: canCreateSchemas } = useAsyncCheckPermissions(
PermissionAction.TENANT_SQL_ADMIN_WRITE,
'schemas'
)
const { data: project } = useSelectedProjectQuery()
const {
data,
isPending: isSchemasLoading,
isSuccess: isSchemasSuccess,
isError: isSchemasError,
error: schemasError,
refetch: refetchSchemas,
} = useSchemasQuery({
projectRef: project?.ref,
connectionString: project?.connectionString,
})
const schemas = (data || [])
.filter((schema) => !excludedSchemas.includes(schema.name))
.sort((a, b) => a.name.localeCompare(b.name))
return (
<div ref={ref} className={className} {...rest}>
{isSchemasLoading && (
<Button
type="default"
key="schema-selector-skeleton"
className="w-full [&>span]:w-full"
size={size}
disabled
>
<Skeleton className="w-full h-3 bg-foreground-muted" />
</Button>
)}
{showError && isSchemasError && (
<Alert_Shadcn_ variant="warning" className="px-3! py-3!">
<AlertTitle_Shadcn_ className="text-xs text-amber-900">
Failed to load schemas
</AlertTitle_Shadcn_>
<AlertDescription_Shadcn_ className="text-xs mb-2 wrap-break-word">
Error: {(schemasError as any)?.message}
</AlertDescription_Shadcn_>
<Button type="default" size="tiny" onClick={() => refetchSchemas()}>
Reload schemas
</Button>
</Alert_Shadcn_>
)}
{isSchemasSuccess && (
<Popover_Shadcn_ open={open} onOpenChange={setOpen} modal={false}>
<PopoverTrigger_Shadcn_ asChild>
<Button
size={size}
disabled={disabled}
type="default"
data-testid="schema-selector"
className={`w-full [&>span]:w-full pr-1! space-x-1`}
iconRight={
<ChevronsUpDown className="text-foreground-muted" strokeWidth={2} size={14} />
}
>
{selectedSchemaName ? (
<div className="w-full flex gap-1">
<p className="text-foreground-lighter">schema</p>
<p className="text-foreground">
{selectedSchemaName === '*' ? 'All schemas' : selectedSchemaName}
</p>
</div>
) : (
<div className="w-full flex gap-1">
<p className="text-foreground-lighter">{placeholderLabel}</p>
</div>
)}
</Button>
</PopoverTrigger_Shadcn_>
<PopoverContent_Shadcn_
className="p-0 min-w-[200px] pointer-events-auto"
side="bottom"
align={align}
sameWidthAsTrigger
>
<Command_Shadcn_>
<CommandInput_Shadcn_ className="text-xs" placeholder="Find schema..." />
<CommandList_Shadcn_
onWheel={stopScrollPropagation ? (event) => event.stopPropagation() : undefined}
>
<CommandEmpty_Shadcn_>No schemas found</CommandEmpty_Shadcn_>
<CommandGroup_Shadcn_>
<ScrollArea className={(schemas || []).length > 7 ? 'h-[210px]' : ''}>
{supportSelectAll && (
<CommandItem_Shadcn_
key="select-all"
className="cursor-pointer flex items-center justify-between space-x-2 w-full"
onSelect={() => {
onSelectSchema('*')
setOpen(false)
}}
onClick={() => {
onSelectSchema('*')
setOpen(false)
}}
>
<span>All schemas</span>
{selectedSchemaName === '*' && (
<Check className="text-brand" strokeWidth={2} size={16} />
)}
</CommandItem_Shadcn_>
)}
{schemas.map((schema) => (
<CommandItem_Shadcn_
key={schema.id}
className="cursor-pointer flex items-center justify-between space-x-2 w-full"
onSelect={() => {
onSelectSchema(schema.name)
setOpen(false)
}}
onClick={() => {
onSelectSchema(schema.name)
setOpen(false)
}}
>
<span>{schema.name}</span>
{selectedSchemaName === schema.name && (
<Check className="text-brand" strokeWidth={2} size={16} />
)}
</CommandItem_Shadcn_>
))}
</ScrollArea>
</CommandGroup_Shadcn_>
{onSelectCreateSchema !== undefined && canCreateSchemas && (
<>
<CommandSeparator_Shadcn_ />
<CommandGroup_Shadcn_>
<CommandItem_Shadcn_
className="cursor-pointer flex items-center gap-x-2 w-full"
onSelect={() => {
onSelectCreateSchema()
setOpen(false)
}}
onClick={() => {
onSelectCreateSchema()
setOpen(false)
}}
>
<Plus size={12} />
Create a new schema
</CommandItem_Shadcn_>
</CommandGroup_Shadcn_>
</>
)}
</CommandList_Shadcn_>
</Command_Shadcn_>
</PopoverContent_Shadcn_>
</Popover_Shadcn_>
)}
</div>
)
}
)
SchemaSelector.displayName = 'SchemaSelector'
export default SchemaSelector