Files
supabase/apps/studio/components/layouts/TableEditorLayout/EntityListItem.tsx
T
143f49414b Feat/tabs (#31071)
* init

* Update inner-side-menu.mdx

* chore: update SQL sidebar to use ui pattern components

* mor

* Update

* Update index.tsx

* init: merge table editor and sql editor and schema visualization together

* more

* move to valtio

* fix issue with Command+B shortcut

* now shows in treeviews if item is opened in tab

* Update ProjectLayout.tsx

* fix sidebar

* fix schema selector for non explorer version

* show schema name in tabs

* added schema names to tabs

* tabs have been updated to support preview tabs

* fix URL issue

* add empty state stuff

* Update SQLEditorNav.tsx

* preview tab works now

* more tabs stuff. 'new' tab also added

* new tab concept

* updates

* fix type errors

* remove unused files

* update test

* move back button, fix width issues on sidebar

* update sidebar logic

* Update ProjectLayout.tsx

* lots of updates. layouts now streamlined. localstorage for tabs in use

* moar

* bunch of new tab logic

* fix empty tab issue

* Update tabs.ts

* layouts switched

* new pages now have fixed layouts

* fix tabs

* fix code bg

* add tabs support for multiple project refs

* intialization issue

* update ID handling

* fixed isOpened state for SQL snippets

* remove old assistant because its bugging up panels

* preview style works in sql editor

* fix border

* removes preview tab if there is one

* fix background of loading skeleton

* lots of issues with types/icons/redirect

* new tab cards

* snippets in empty state now work

* moar stuff

* tabs now in feature flags

* Update tabs.ts

* Update tabs.ts

* moar

* add feature previews

* remove code not needed

* Update next-env.d.ts

* Delete FeaturePreviewModal.tsx

* fix typescript errors. remove more explorer stuff

* remove explorer files

* fixed issues with templates and quickstarts tab

* fixed active state when tabs are not opted in

* logic error

* fix open/highlight issue when opted out of tabs

* templates/quickstarts now displayed with new cards

* Update recent-items.tsx

* Update new-tab.tsx

* add icon back in

* add old empty state back in

* recent items updated to respect project ref

* localstorage cleanup on deletion

* moar

* overflow tabs now working

* correct tab names used for new sql templates/quickstarts

* ongoing queries fix

* cleanup

* update images

* Update RouteValidationWrapper.tsx

* Update AppLayout.tsx

* Update NavigationBar.tsx

* add headers back into side panels

* improve writing

* tabs now drag and drop a billion times better

* Update tabs.tsx

* Update tabs.tsx

* init issues on stores, which caused a race condition.

* fix hydration error

* fix new tab issue in sql

* Update ProjectLayout.tsx

* Update pnpm-lock.yaml

* Update new-tab.tsx

* move EditorMenuListSkeleton

* Fix type issues

* fixes: DESIGN-87

fixes: DESIGN-87

* refactor sort/filter components

* Update rules-set-button-text.tsx

* remove discussions for now

* small styling fixes

* Update FeaturePreviewModal.tsx

* Update FeaturePreviewModal.tsx

* Update RouteValidationWrapper.tsx

* revert

* revert

* revert

* revert

* revert

* more revert

* Update collapse-button.tsx

* Update SQLEditorTreeViewItem.tsx

* revert

* Update SchemaGraph.tsx

* Delete new-upcoming.tsx

* revert

* Update ProjectLayout.tsx

* fix home link

* Update table-editor.spec.ts

* test update

* Update table-editor.spec.ts

* Fix the playwright tests.

* layout fixes

* layout fix

* revert sort/filter

* Update LastSignInWrapper.tsx

* revert

* revert

* remove

* update file names

* revert

* revert

* revert

* Fix TreeView console error props

* Add guards in SQL Editor to ensure that feature preview tabs changes do not affect existing UI when flag is off

* Fix missing DefaultLayout in SQL editor templates + fix New tab

* Remove console log

* Remove DatabaseSelector for SQL editor on local

* Fix SQL editor shared favorites for local

* Fix test

* Ensure NewTab doesn't show up if flag is not toggled for SQL editor

* Decouple UI state changes from content-query and entity-types-infinite-query

* Fix tab closing unnecessary rerouting

* Beef up feature previews

* Fix create new table from table editor new tab

* Fix tabs getting incorrectly reset when going between table and SQL editors

* Fix last visited SQL snippet for both tabs and not tabs

* Fix last visited table for table editor tabs

* Clear dashboard history when closing last tab

* Fix loading dashboard history

* Add comment to refactor stores

* Ensure we only save up to 8 items for recent items for each type

* Remove unneccesary logic in tabs

* Smol style fix for DeleteAccountButton

* Smol fix

* Fix inability to close New tab

---------

Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
Co-authored-by: Alaister Young <a@alaisteryoung.com>
Co-authored-by: Ivan Vasilov <vasilov.ivan@gmail.com>
2025-03-27 17:46:57 +08:00

437 lines
14 KiB
TypeScript

import saveAs from 'file-saver'
import { Clipboard, Copy, Download, Edit, Lock, MoreHorizontal, Trash, Unlock } from 'lucide-react'
import Link from 'next/link'
import Papa from 'papaparse'
import { toast } from 'sonner'
import { useSnapshot } from 'valtio'
import { IS_PLATFORM } from 'common'
import {
MAX_EXPORT_ROW_COUNT,
MAX_EXPORT_ROW_COUNT_MESSAGE,
} from 'components/grid/components/header/Header'
import { parseSupaTable } from 'components/grid/SupabaseGrid.utils'
import { useIsTableEditorTabsEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'
import {
formatTableRowsToSQL,
getEntityLintDetails,
} from 'components/interfaces/TableGridEditor/TableEntity.utils'
import { EntityTypeIcon } from 'components/ui/EntityTypeIcon'
import type { ItemRenderer } from 'components/ui/InfiniteList'
import { ENTITY_TYPE } from 'data/entity-types/entity-type-constants'
import { Entity } from 'data/entity-types/entity-types-infinite-query'
import { useProjectLintsQuery } from 'data/lint/lint-query'
import { EditorTablePageLink } from 'data/prefetchers/project.$ref.editor.$id'
import { getTableEditor } from 'data/table-editor/table-editor-query'
import { isTableLike } from 'data/table-editor/table-editor-types'
import { fetchAllTableRows } from 'data/table-rows/table-rows-query'
import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'
import { copyToClipboard } from 'lib/helpers'
import { useTableEditorStateSnapshot } from 'state/table-editor'
import { createTabId, getTabsStore, makeTabPermanent } from 'state/tabs'
import {
cn,
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuTrigger,
Tooltip,
TooltipContent,
TooltipTrigger,
TreeViewItemVariant,
} from 'ui'
import { useProjectContext } from '../ProjectLayout/ProjectContext'
export interface EntityListItemProps {
id: number | string
projectRef: string
isLocked: boolean
isActive?: boolean
}
const EntityListItem: ItemRenderer<Entity, EntityListItemProps> = ({
id,
projectRef,
item: entity,
isLocked,
isActive: _isActive,
}) => {
const { project } = useProjectContext()
const snap = useTableEditorStateSnapshot()
const { selectedSchema } = useQuerySchemaState()
// For tabs preview flag logic
const isTableEditorTabsEnabled = useIsTableEditorTabsEnabled()
const tabId = createTabId(entity.type, { id: entity.id })
const tabStore = getTabsStore(projectRef)
const isPreview = isTableEditorTabsEnabled ? tabStore.previewTabId === tabId : false
const tabs = useSnapshot(tabStore)
const isOpened = Object.values(tabs.tabsMap).some((tab) => tab.metadata?.tableId === entity.id)
const isActive = Number(id) === entity.id
const canEdit = isActive && !isLocked
const { data: lints = [] } = useProjectLintsQuery({
projectRef: project?.ref,
})
const tableHasLints: boolean = getEntityLintDetails(
entity.name,
'rls_disabled_in_public',
['ERROR'],
lints,
selectedSchema
).hasLint
const viewHasLints: boolean = getEntityLintDetails(
entity.name,
'security_definer_view',
['ERROR', 'WARN'],
lints,
selectedSchema
).hasLint
const materializedViewHasLints: boolean = getEntityLintDetails(
entity.name,
'materialized_view_in_api',
['ERROR', 'WARN'],
lints,
selectedSchema
).hasLint
const formatTooltipText = (entityType: string) => {
return Object.entries(ENTITY_TYPE)
.find(([, value]) => value === entityType)?.[0]
?.toLowerCase()
?.split('_')
?.join(' ')
}
const exportTableAsCSV = async () => {
if (IS_PLATFORM && !project?.connectionString) {
return console.error('Connection string is required')
}
const toastId = toast.loading(`Exporting ${entity.name} as CSV...`)
try {
const table = await getTableEditor({
id: entity.id,
projectRef,
connectionString: project?.connectionString,
})
if (isTableLike(table) && table.live_rows_estimate > MAX_EXPORT_ROW_COUNT) {
return toast.error(
<div className="text-foreground prose text-sm">{MAX_EXPORT_ROW_COUNT_MESSAGE}</div>,
{ id: toastId }
)
}
const supaTable = table && parseSupaTable(table)
if (!supaTable) {
return toast.error(`Failed to export table: ${entity.name}`, { id: toastId })
}
const rows = await fetchAllTableRows({
projectRef,
connectionString: project?.connectionString,
table: supaTable,
})
const formattedRows = rows.map((row) => {
const formattedRow = row
Object.keys(row).map((column) => {
if (typeof row[column] === 'object' && row[column] !== null)
formattedRow[column] = JSON.stringify(formattedRow[column])
})
return formattedRow
})
if (formattedRows.length > 0) {
const csv = Papa.unparse(formattedRows, {
columns: supaTable.columns.map((column) => column.name),
})
const csvData = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
saveAs(csvData, `${entity!.name}_rows.csv`)
}
toast.success(`Successfully exported ${entity.name} as CSV`, { id: toastId })
} catch (error: any) {
toast.error(`Failed to export table: ${error.message}`, { id: toastId })
}
}
const exportTableAsSQL = async () => {
if (IS_PLATFORM && !project?.connectionString) {
return console.error('Connection string is required')
}
const toastId = toast.loading(`Exporting ${entity.name} as SQL...`)
try {
const table = await getTableEditor({
id: entity.id,
projectRef,
connectionString: project?.connectionString,
})
if (isTableLike(table) && table.live_rows_estimate > MAX_EXPORT_ROW_COUNT) {
return toast.error(
<div className="text-foreground prose text-sm">{MAX_EXPORT_ROW_COUNT_MESSAGE}</div>,
{ id: toastId }
)
}
const supaTable = table && parseSupaTable(table)
if (!supaTable) {
return toast.error(`Failed to export table: ${entity.name}`, { id: toastId })
}
const rows = await fetchAllTableRows({
projectRef,
connectionString: project?.connectionString,
table: supaTable,
})
const formattedRows = rows.map((row) => {
const formattedRow = row
Object.keys(row).map((column) => {
if (typeof row[column] === 'object' && row[column] !== null)
formattedRow[column] = JSON.stringify(formattedRow[column])
})
return formattedRow
})
if (formattedRows.length > 0) {
const sqlStatements = formatTableRowsToSQL(supaTable, formattedRows)
const sqlData = new Blob([sqlStatements], { type: 'text/sql;charset=utf-8;' })
saveAs(sqlData, `${entity!.name}_rows.sql`)
}
toast.success(`Successfully exported ${entity.name} as SQL`, { id: toastId })
} catch (error: any) {
toast.error(`Failed to export table: ${error.message}`, { id: toastId })
}
}
return (
<EditorTablePageLink
title={entity.name}
id={String(entity.id)}
href={`/project/${projectRef}/editor/${entity.id}?schema=${entity.schema}`}
role="button"
aria-label={`View ${entity.name}`}
className={cn(
TreeViewItemVariant({
isSelected: isActive && !isPreview,
isOpened: isOpened && !isPreview,
isPreview,
}),
'px-4'
)}
onDoubleClick={(e) => {
e.preventDefault()
const tabId = createTabId(entity.type, { id: entity.id })
makeTabPermanent(projectRef, tabId)
}}
>
<>
{isActive && <div className="absolute left-0 h-full w-0.5 bg-foreground" />}
<Tooltip disableHoverableContent={true}>
<TooltipTrigger className="min-w-4">
<EntityTypeIcon type={entity.type} isActive={isActive} />
</TooltipTrigger>
<TooltipContent side="bottom">{formatTooltipText(entity.type)}</TooltipContent>
</Tooltip>
<div
className={cn(
'truncate',
'overflow-hidden text-ellipsis whitespace-nowrap flex items-center gap-2 relative w-full',
isActive && 'text-foreground'
)}
>
<span
className={cn(
isActive ? 'text-foreground' : 'text-foreground-light group-hover:text-foreground',
'text-sm',
'transition',
'truncate'
)}
>
{entity.name}
</span>
<EntityTooltipTrigger
entity={entity}
isActive={isActive}
tableHasLints={tableHasLints}
viewHasLints={viewHasLints}
materializedViewHasLints={materializedViewHasLints}
/>
</div>
{canEdit && (
<DropdownMenu>
<DropdownMenuTrigger className="text-foreground-lighter transition-all text-transparent group-hover:text-foreground data-[state=open]:text-foreground">
<MoreHorizontal size={14} strokeWidth={2} />
</DropdownMenuTrigger>
<DropdownMenuContent side="bottom" align="start" className="w-44">
<DropdownMenuItem
key="copy-name"
className="space-x-2"
onClick={(e) => {
e.stopPropagation()
copyToClipboard(entity.name)
}}
>
<Clipboard size={12} />
<span>Copy name</span>
</DropdownMenuItem>
{entity.type === ENTITY_TYPE.TABLE && (
<>
<DropdownMenuSeparator />
<DropdownMenuItem
key="edit-table"
className="space-x-2"
onClick={(e) => {
e.stopPropagation()
snap.onEditTable()
}}
>
<Edit size={12} />
<span>Edit table</span>
</DropdownMenuItem>
<DropdownMenuItem
key="duplicate-table"
className="space-x-2"
onClick={(e) => {
e.stopPropagation()
snap.onDuplicateTable()
}}
>
<Copy size={12} />
<span>Duplicate table</span>
</DropdownMenuItem>
<DropdownMenuItem key="view-policies" className="space-x-2" asChild>
<Link
key="view-policies"
href={`/project/${projectRef}/auth/policies?schema=${selectedSchema}&search=${entity.id}`}
>
<Lock size={12} />
<span>View policies</span>
</Link>
</DropdownMenuItem>
<DropdownMenuSub>
<DropdownMenuSubTrigger className="gap-x-2">
<Download size={12} />
Export data
</DropdownMenuSubTrigger>
<DropdownMenuSubContent>
<DropdownMenuItem
key="download-table-csv"
className="space-x-2"
onClick={(e) => {
e.stopPropagation()
exportTableAsCSV()
}}
>
<span>Export table as CSV</span>
</DropdownMenuItem>
<DropdownMenuItem
key="download-table-sql"
className="gap-x-2"
onClick={(e) => {
e.stopPropagation()
exportTableAsSQL()
}}
>
<span>Export table as SQL</span>
</DropdownMenuItem>
</DropdownMenuSubContent>
</DropdownMenuSub>
<DropdownMenuSeparator />
<DropdownMenuItem
key="delete-table"
className="gap-x-2"
onClick={(e) => {
e.stopPropagation()
snap.onDeleteTable()
}}
>
<Trash size={12} />
<span>Delete table</span>
</DropdownMenuItem>
</>
)}
</DropdownMenuContent>
</DropdownMenu>
)}
</>
</EditorTablePageLink>
)
}
const EntityTooltipTrigger = ({
entity,
isActive,
tableHasLints,
viewHasLints,
materializedViewHasLints,
}: {
entity: Entity
isActive: boolean
tableHasLints: boolean
viewHasLints: boolean
materializedViewHasLints: boolean
}) => {
let tooltipContent = ''
switch (entity.type) {
case ENTITY_TYPE.TABLE:
if (tableHasLints) {
tooltipContent = 'RLS disabled'
}
break
case ENTITY_TYPE.VIEW:
if (viewHasLints) {
tooltipContent = 'Security definer view'
}
break
case ENTITY_TYPE.MATERIALIZED_VIEW:
if (materializedViewHasLints) {
tooltipContent = 'Security definer view'
}
break
case ENTITY_TYPE.FOREIGN_TABLE:
tooltipContent = 'RLS is not enforced on foreign tables'
break
default:
break
}
if (tooltipContent) {
return (
<Tooltip disableHoverableContent={true}>
<TooltipTrigger className="min-w-4">
<Unlock
size={14}
strokeWidth={2}
className={cn('min-w-4', isActive ? 'text-warning-600' : 'text-warning-500')}
/>
</TooltipTrigger>
<TooltipContent side="bottom">
<span>{tooltipContent}</span>
</TooltipContent>
</Tooltip>
)
}
return null
}
export default EntityListItem