Files
supabase/studio/components/layouts/TableEditorLayout/TableEditorMenu.tsx
T

360 lines
12 KiB
TypeScript

import { useMemo, useState } from 'react'
import Link from 'next/link'
import { noop, partition } from 'lodash'
import { observer } from 'mobx-react-lite'
import {
Button,
Dropdown,
IconChevronDown,
IconCopy,
IconEdit,
IconLoader,
IconLock,
IconRefreshCw,
IconSearch,
IconTrash,
IconX,
Input,
Listbox,
Menu,
} from 'ui'
import * as Tooltip from '@radix-ui/react-tooltip'
import { PermissionAction } from '@supabase/shared-types/out/constants'
import type { PostgresSchema } from '@supabase/postgres-meta'
import { checkPermissions, useStore, useParams } from 'hooks'
import ProductMenuItem from 'components/ui/ProductMenu/ProductMenuItem'
import { useEntityTypesQuery } from 'data/entity-types/entity-types-infinite-query'
import { Entity } from 'data/entity-types/entity-type-query'
import { useProjectContext } from '../ProjectLayout/ProjectContext'
import InfiniteList from 'components/ui/InfiniteList'
export interface TableEditorMenuProps {
selectedSchema?: string
onSelectSchema: (schema: string) => void
onAddTable: () => void
onEditTable: (table: Entity) => void
onDeleteTable: (table: Entity) => void
onDuplicateTable: (table: Entity) => void
}
const TableEditorMenu = ({
selectedSchema,
onSelectSchema = noop,
onAddTable = noop,
onEditTable = noop,
onDeleteTable = noop,
onDuplicateTable = noop,
}: TableEditorMenuProps) => {
const { meta } = useStore()
const { id } = useParams()
const [searchText, setSearchText] = useState<string>('')
const { project } = useProjectContext()
const { data, isLoading, refetch, isRefetching, hasNextPage, isFetchingNextPage, fetchNextPage } =
useEntityTypesQuery({
projectRef: project?.ref,
connectionString: project?.connectionString,
schema: selectedSchema,
// search: searchText.trim().toLowerCase()
})
const totalCount = data?.pages?.[0].data.count
const entityTypes = useMemo(
() => data?.pages.flatMap((page) => page.data.entities),
[data?.pages]
)
const schemas: PostgresSchema[] = meta.schemas.list()
const schema = schemas.find((schema) => schema.name === selectedSchema)
const canCreateTables = checkPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'tables')
const isLoadingTableMetadata = id ? !meta.tables.byId(id) : true
const refreshTables = async () => {
await refetch()
}
const [protectedSchemas, openSchemas] = partition(schemas, (schema) =>
meta.excludedSchemas.includes(schema?.name ?? '')
)
const isLocked = protectedSchemas.some((s) => s.id === schema?.id)
return (
<div
className="pt-6 flex flex-col flex-grow space-y-6 h-full"
style={{ maxHeight: 'calc(100vh - 48px)' }}
>
{/* Schema selection dropdown */}
<div className="px-3 mx-4">
{!meta.schemas.isInitialized ? (
<div className="flex h-[26px] items-center space-x-3 rounded border border-gray-500 px-3">
<IconLoader className="animate-spin" size={12} />
<span className="text-xs text-scale-900">Loading schemas...</span>
</div>
) : (
<Listbox
size="tiny"
value={selectedSchema}
onChange={(name: string) => {
setSearchText('')
onSelectSchema(name)
}}
>
<Listbox.Option disabled key="normal-schemas" value="normal-schemas" label="Schemas">
<p className="text-xs text-scale-1100">Schemas</p>
</Listbox.Option>
{openSchemas.map((schema) => (
<Listbox.Option
key={schema.id}
value={schema.name}
label={schema.name}
addOnBefore={() => <span className="text-scale-900 text-xs">schema</span>}
>
<span className="text-scale-1200 text-xs">{schema.name}</span>
</Listbox.Option>
))}
<Listbox.Option
disabled
key="protected-schemas"
value="protected-schemas"
label="Protected schemas"
>
<p className="text-xs text-scale-1100">Protected schemas</p>
</Listbox.Option>
{protectedSchemas.map((schema) => (
<Listbox.Option
key={schema.id}
value={schema.name}
label={schema.name}
addOnBefore={() => <span className="text-scale-900 text-xs">schema</span>}
>
<span className="text-scale-1200 text-xs">{schema.name}</span>
</Listbox.Option>
))}
</Listbox>
)}
</div>
<div className="space-y-1 mx-4">
{!isLocked && (
<div className="px-3">
{/* Add new table button */}
<Tooltip.Root delayDuration={0}>
<Tooltip.Trigger className="w-full">
<Button
block
as="span"
disabled={!canCreateTables}
size="tiny"
icon={
<div className="text-scale-900">
<IconEdit size={14} strokeWidth={1.5} />
</div>
}
type="default"
style={{ justifyContent: 'start' }}
onClick={onAddTable}
>
New table
</Button>
</Tooltip.Trigger>
{!canCreateTables && (
<Tooltip.Content side="bottom">
<Tooltip.Arrow className="radix-tooltip-arrow" />
<div
className={[
'rounded bg-scale-100 py-1 px-2 leading-none shadow',
'border border-scale-200',
].join(' ')}
>
<span className="text-xs text-scale-1200">
You need additional permissions to create tables
</span>
</div>
</Tooltip.Content>
)}
</Tooltip.Root>
</div>
)}
{/* Table search input */}
<div className="mb-2 block px-3">
<Input
className="table-editor-search border-none"
icon={<IconSearch className="text-scale-900" size={12} strokeWidth={1.5} />}
placeholder="Search tables"
onChange={(e) => setSearchText(e.target.value)}
value={searchText}
size="tiny"
actions={
searchText && (
<Button size="tiny" type="text" onClick={() => setSearchText('')}>
<IconX size={12} strokeWidth={2} />
</Button>
)
}
/>
</div>
</div>
{isLoading ? (
<div className="mx-7 flex items-center space-x-2">
<IconLoader className="animate-spin" size={14} strokeWidth={1.5} />
<p className="text-sm text-scale-1000">Loading entities...</p>
</div>
) : searchText.length === 0 && (entityTypes?.length ?? 0) === 0 ? (
<div className="mx-7 space-y-1 rounded-md border border-scale-400 bg-scale-300 py-3 px-4">
<p className="text-xs">No entities available</p>
<p className="text-xs text-scale-1100">This schema has no entities available yet</p>
</div>
) : (
<Menu
type="pills"
className="flex flex-auto px-4 space-y-6 pb-4"
ulClassName="flex flex-auto flex-col"
>
<Menu.Group
// @ts-ignore
title={
<>
<div className="flex w-full items-center justify-between">
<div className="flex items-center space-x-1">
<p>Tables</p>
{totalCount !== undefined && (
<p style={{ fontVariantNumeric: 'tabular-nums' }}>({totalCount})</p>
)}
</div>
<button className="cursor-pointer" onClick={refreshTables}>
<IconRefreshCw className={isRefetching ? 'animate-spin' : ''} size={14} />
</button>
</div>
</>
}
/>
<div className="flex flex-1">
<InfiniteList
items={entityTypes}
ItemComponent={EntityListItem}
itemProps={{
projectRef: project?.ref,
id: Number(id),
onEditTable,
onDeleteTable,
onDuplicateTable,
isLoadingTableMetadata,
}}
getItemSize={() => 28}
hasNextPage={hasNextPage}
isLoadingNextPage={isFetchingNextPage}
onLoadNextPage={() => fetchNextPage()}
/>
</div>
</Menu>
)}
{searchText.length > 0 && (entityTypes?.length ?? 0) === 0 && (
<div className="!mt-0 mx-7 space-y-1 rounded-md border border-scale-400 bg-scale-300 py-3 px-4">
<p className="text-xs">No results found</p>
<p className="text-xs text-scale-1100">There are no entities that match your search</p>
</div>
)}
</div>
)
}
export default observer(TableEditorMenu)
export interface EntityListItemProps {
id: number
projectRef: string
item: Entity
isLocked: boolean
onEditTable: (table: Entity) => void
onDeleteTable: (table: Entity) => void
onDuplicateTable: (table: Entity) => void
isLoadingTableMetadata?: boolean
}
const EntityListItem = ({
id,
projectRef,
item: entity,
isLocked,
onEditTable,
onDeleteTable,
onDuplicateTable,
isLoadingTableMetadata = false,
}: EntityListItemProps) => {
const isActive = Number(id) === entity.id
return (
<ProductMenuItem
url={`/project/${projectRef}/editor/${entity.id}`}
name={entity.name}
hoverText={entity.comment ? entity.comment : entity.name}
isActive={isActive}
icon={
<div className="flex items-center justify-center text-xs h-4 w-4 rounded-[2px] bg-scale-800">
{entity.type[0]?.toUpperCase()}
</div>
}
action={
entity.type === 'table' &&
isActive &&
!isLocked && (
<Dropdown
size="small"
side="bottom"
align="start"
overlay={
entity.type === 'table'
? [
<Dropdown.Item
key="edit-table"
icon={<IconEdit size="tiny" />}
onClick={() => onEditTable(entity)}
disabled={isLoadingTableMetadata}
>
Edit Table
</Dropdown.Item>,
<Dropdown.Item
key="duplicate-table"
icon={<IconCopy size="tiny" />}
onClick={() => onDuplicateTable(entity)}
disabled={isLoadingTableMetadata}
>
Duplicate Table
</Dropdown.Item>,
<Link href={`/project/${projectRef}/auth/policies?search=${entity.id}`}>
<a>
<Dropdown.Item key="delete-table" icon={<IconLock size="tiny" />}>
View Policies
</Dropdown.Item>
</a>
</Link>,
<Dropdown.Separator key="separator" />,
<Dropdown.Item
key="delete-table"
icon={<IconTrash size="tiny" />}
onClick={() => onDeleteTable(entity)}
disabled={isLoadingTableMetadata}
>
Delete Table
</Dropdown.Item>,
]
: null
}
>
<div className="text-scale-900 transition-colors hover:text-scale-1200">
<IconChevronDown size={14} strokeWidth={2} />
</div>
</Dropdown>
)
}
/>
)
}