Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Implement showing view definition and refactor API documentation side panel into a separate component

Joshen Lim4a73accf43a3
diff --git a/studio/components/grid/SupabaseGrid.tsx b/studio/components/grid/SupabaseGrid.tsx
index c579f2f5a2d..d24242229c9 100644
--- a/studio/components/grid/SupabaseGrid.tsx
+++ b/studio/components/grid/SupabaseGrid.tsx
@@ -197,6 +197,7 @@ const SupabaseGridLayout = forwardRef<SupabaseGridRef, SupabaseGridProps>((props
onAddRow={editable ? props.onAddRow : undefined}
onAddColumn={editable ? props.onAddColumn : undefined}
headerActions={headerActions}
+ showCustomChildren={showCustomChildren}
/>
{showCustomChildren && children !== undefined ? (
<>{children}</>
diff --git a/studio/components/grid/components/header/Header.tsx b/studio/components/grid/components/header/Header.tsx
index b5709eafc5c..34c09278692 100644
--- a/studio/components/grid/components/header/Header.tsx
+++ b/studio/components/grid/components/header/Header.tsx
@@ -31,19 +31,34 @@ export type HeaderProps = {
onAddColumn?: () => void
onAddRow?: () => void
headerActions?: ReactNode
+ showCustomChildren?: boolean
}
-const Header = ({ table, sorts, filters, onAddColumn, onAddRow, headerActions }: HeaderProps) => {
+const Header = ({
+ table,
+ sorts,
+ filters,
+ onAddColumn,
+ onAddRow,
+ headerActions,
+ showCustomChildren,
+}: HeaderProps) => {
const state = useTrackedState()
const { selectedRows } = state
return (
<div>
<div className="flex h-10 items-center justify-between bg-scale-100 px-5 py-1.5 dark:bg-scale-300">
- {selectedRows.size > 0 ? (
- <RowHeader table={table} sorts={sorts} filters={filters} />
+ {!showCustomChildren ? (
+ <>
+ {selectedRows.size > 0 ? (
+ <RowHeader table={table} sorts={sorts} filters={filters} />
+ ) : (
+ <DefaultHeader table={table} onAddColumn={onAddColumn} onAddRow={onAddRow} />
+ )}
+ </>
) : (
- <DefaultHeader table={table} onAddColumn={onAddColumn} onAddRow={onAddRow} />
+ <div></div>
)}
<div className="sb-grid-header__inner">{headerActions}</div>
</div>
diff --git a/studio/components/interfaces/TableGridEditor/APIDocumentationPanel.tsx b/studio/components/interfaces/TableGridEditor/APIDocumentationPanel.tsx
new file mode 100644
index 00000000000..0557b5e4d02
--- /dev/null
+++ b/studio/components/interfaces/TableGridEditor/APIDocumentationPanel.tsx
@@ -0,0 +1,142 @@
+import { useState } from 'react'
+import { SidePanel, IconBookOpen } from 'ui'
+
+import { useParams, useStore } from 'hooks'
+import { GeneralContent, ResourceContent } from '../Docs'
+import LangSelector from '../Docs/LangSelector'
+import GeneratingTypes from '../Docs/GeneratingTypes'
+import ActionBar from './SidePanelEditor/ActionBar'
+import { useProjectApiQuery } from 'data/config/project-api-query'
+import { useProjectJsonSchemaQuery } from 'data/docs/project-json-schema-query'
+import { snakeToCamel } from 'lib/helpers'
+
+interface APIDocumentationPanelProps {
+ visible: boolean
+ onClose: () => void
+}
+
+const APIDocumentationPanel = ({ visible, onClose }: APIDocumentationPanelProps) => {
+ const { meta } = useStore()
+ const { ref, page, id } = useParams()
+ const {
+ data: jsonSchema,
+ error: jsonSchemaError,
+ refetch,
+ } = useProjectJsonSchemaQuery({ projectRef: ref })
+ const { data: settings } = useProjectApiQuery({ projectRef: ref })
+
+ const DEFAULT_KEY = { name: 'hide', key: 'SUPABASE_KEY' }
+ const [selectedLang, setSelectedLang] = useState<any>('js')
+ const [showApiKey, setShowApiKey] = useState<any>(DEFAULT_KEY)
+
+ const tables = meta.tables.list()
+ const autoApiService = {
+ ...settings?.autoApiService,
+ endpoint: `${settings?.autoApiService.protocol ?? 'https'}://${
+ settings?.autoApiService.endpoint ?? '-'
+ }`,
+ }
+ const apiService = settings?.autoApiService
+ const anonKey = apiService?.service_api_keys.find((x) => x.name === 'anon key')
+ ? apiService.defaultApiKey
+ : undefined
+ const resources = getResourcesFromJsonSchema(jsonSchema)
+
+ function getResourcesFromJsonSchema(value: any) {
+ const { paths } = value || {}
+ const functionPath = 'rpc/'
+ let resources: any = {}
+
+ Object.entries(paths || []).forEach(([name, val]) => {
+ let trimmed = name.slice(1)
+ let id = trimmed.replace(functionPath, '')
+ let displayName = id.replace(/_/g, ' ')
+ let camelCase = snakeToCamel(id)
+ let enriched = { id, displayName, camelCase }
+ if (!trimmed.length) return
+ else resources[id] = enriched
+ })
+
+ return resources
+ }
+
+ return (
+ <SidePanel
+ key="WrapperTableEditor"
+ size="xxlarge"
+ visible={visible}
+ onCancel={() => onClose()}
+ header={
+ <span className="flex items-center gap-2">
+ <IconBookOpen size="tiny" />
+ API
+ </span>
+ }
+ customFooter={
+ <ActionBar
+ backButtonLabel="Close"
+ hideApply={true}
+ formId="wrapper-table-editor-form"
+ closePanel={() => onClose()}
+ />
+ }
+ >
+ <div className="Docs Docs--table-editor">
+ <SidePanel.Content>
+ {jsonSchemaError ? (
+ <div className="p-6 mx-auto text-center sm:w-full md:w-3/4">
+ <div className="text-scale-1000">
+ <p>Error connecting to API</p>
+ <p>{`${jsonSchemaError}`}</p>
+ </div>
+ </div>
+ ) : (
+ <>
+ {jsonSchema ? (
+ <>
+ <div className="sticky top-0 z-10 bg-scale-100 dark:bg-scale-300">
+ <LangSelector
+ selectedLang={selectedLang}
+ setSelectedLang={setSelectedLang}
+ showApiKey={showApiKey}
+ setShowApiKey={setShowApiKey}
+ apiKey={anonKey}
+ autoApiService={autoApiService}
+ />
+ </div>
+ <GeneralContent
+ autoApiService={autoApiService}
+ selectedLang={selectedLang}
+ showApiKey={true}
+ page={page}
+ />
+
+ <GeneratingTypes selectedLang={selectedLang} />
+
+ {jsonSchema?.definitions && (
+ <ResourceContent
+ autoApiService={autoApiService}
+ selectedLang={selectedLang}
+ resourceId={tables.find((table) => table.id === Number(id))?.name}
+ resources={resources}
+ definitions={jsonSchema.definitions}
+ paths={jsonSchema.paths}
+ showApiKey={showApiKey.key}
+ refreshDocs={async () => await refetch()}
+ />
+ )}
+ </>
+ ) : (
+ <div className="p-6 mx-auto text-center sm:w-full md:w-3/4">
+ <h3 className="text-lg">Building docs ...</h3>
+ </div>
+ )}
+ </>
+ )}
+ </SidePanel.Content>
+ </div>
+ </SidePanel>
+ )
+}
+
+export default APIDocumentationPanel
diff --git a/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx b/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx
index f595551f68c..2e4776cfb0f 100644
--- a/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx
+++ b/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx
@@ -18,17 +18,10 @@ import {
SupabaseGridRef,
SupaTable,
} from 'components/grid'
-import { IconBookOpen, SidePanel } from 'ui'
-import ActionBar from './SidePanelEditor/ActionBar'
-import { GeneralContent, ResourceContent } from '../Docs'
import { sqlKeys } from 'data/sql/keys'
-import { useProjectApiQuery } from 'data/config/project-api-query'
import { useProjectJsonSchemaQuery } from 'data/docs/project-json-schema-query'
import { useTableRowUpdateMutation } from 'data/table-rows/table-row-update-mutation'
-import { snakeToCamel } from 'lib/helpers'
import { JsonEditValue } from './SidePanelEditor/RowEditor/RowEditor.types'
-import LangSelector from '../Docs/LangSelector'
-import GeneratingTypes from '../Docs/GeneratingTypes'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import {
ForeignKeyConstraint,
@@ -38,6 +31,7 @@ import { FOREIGN_KEY_DELETION_ACTION } from 'data/database/database-query-consta
import { ForeignRowSelectorProps } from './SidePanelEditor/RowEditor/ForeignRowSelector/ForeignRowSelector'
import TwoOptionToggle from 'components/ui/TwoOptionToggle'
import ViewDefinition from './ViewDefinition'
+import APIDocumentationPanel from './APIDocumentationPanel'
export interface TableGridEditorProps {
/** Theme for the editor */
@@ -97,31 +91,16 @@ const TableGridEditor = ({
onEditForeignKeyColumnValue = noop,
onClosePanel = noop,
}: TableGridEditorProps) => {
- const { project } = useProjectContext()
const { meta, ui, vault } = useStore()
const router = useRouter()
- const { ref: projectRef, page, id } = useParams()
+ const { ref: projectRef, id } = useParams()
const gridRef = useRef<SupabaseGridRef>(null)
- const tables = meta.tables.list()
-
- const { data: settings } = useProjectApiQuery({ projectRef: projectRef })
-
- const autoApiService = {
- ...settings?.autoApiService,
- endpoint: `${settings?.autoApiService.protocol ?? 'https'}://${
- settings?.autoApiService.endpoint ?? '-'
- }`,
- }
- const DEFAULT_KEY = { name: 'hide', key: 'SUPABASE_KEY' }
-
+ const { project } = useProjectContext()
const isVaultEnabled = useFlag('vaultExtension')
const [encryptedColumns, setEncryptedColumns] = useState([])
const [apiPreviewPanelOpen, setApiPreviewPanelOpen] = useState(false)
- const [selectedLang, setSelectedLang] = useState<any>('js')
- const [showApiKey, setShowApiKey] = useState<any>(DEFAULT_KEY)
-
// When rendering a view in the grid
const [selectedView, setSelectedView] = useState<'data' | 'definition'>('data')
@@ -193,37 +172,7 @@ const TableGridEditor = ({
},
})
- function getResourcesFromJsonSchema(value: any) {
- const { paths } = value || {}
- const functionPath = 'rpc/'
- let resources: any = {}
-
- Object.entries(paths || []).forEach(([name, val]) => {
- let trimmed = name.slice(1)
- let id = trimmed.replace(functionPath, '')
- let displayName = id.replace(/_/g, ' ')
- let camelCase = snakeToCamel(id)
- let enriched = { id, displayName, camelCase }
- if (!trimmed.length) return
- else resources[id] = enriched
- })
-
- return resources
- }
-
- const apiService = settings?.autoApiService
- const anonKey = apiService?.service_api_keys.find((x) => x.name === 'anon key')
- ? apiService.defaultApiKey
- : undefined
-
- const {
- data: jsonSchema,
- error: jsonSchemaError,
- refetch,
- } = useProjectJsonSchemaQuery({ projectRef })
- if (jsonSchemaError) console.error('jsonSchemaError', jsonSchemaError)
-
- const resources = getResourcesFromJsonSchema(jsonSchema)
+ const { refetch } = useProjectJsonSchemaQuery({ projectRef })
const refreshDocs = async () => await refetch()
const { data } = useForeignKeyConstraintsQuery({
@@ -377,7 +326,6 @@ const TableGridEditor = ({
theme={theme}
gridProps={{ height: '100%' }}
storageRef={projectRef}
- showCustomChildren={isViewSelected && selectedView === 'definition'}
editable={!isReadOnly && canUpdateTables && canEditViaTableEditor}
schema={selectedTable.schema}
table={gridTable}
@@ -412,9 +360,11 @@ const TableGridEditor = ({
onSqlQuery={onSqlQuery}
onExpandJSONEditor={onExpandJSONEditor}
onEditForeignKeyColumnValue={onEditForeignKeyColumnValue}
+ showCustomChildren={isViewSelected && selectedView === 'definition'}
>
- <ViewDefinition />
+ {isViewSelected && <ViewDefinition name={selectedTable.name} />}
</SupabaseGrid>
+
{!isUndefined(selectedSchema) && (
<SidePanelEditor
selectedSchema={selectedSchema}
@@ -434,81 +384,10 @@ const TableGridEditor = ({
/>
)}
- <SidePanel
- key="WrapperTableEditor"
- size="xxlarge"
+ <APIDocumentationPanel
visible={apiPreviewPanelOpen}
- onCancel={() => setApiPreviewPanelOpen(false)}
- header={
- <span className="flex items-center gap-2">
- <IconBookOpen size="tiny" />
- API
- </span>
- }
- customFooter={
- <ActionBar
- backButtonLabel="Close"
- hideApply={true}
- formId="wrapper-table-editor-form"
- closePanel={() => setApiPreviewPanelOpen(false)}
- />
- }
- >
- <div className="Docs Docs--table-editor">
- <SidePanel.Content>
- {jsonSchemaError ? (
- <div className="p-6 mx-auto text-center sm:w-full md:w-3/4">
- <div className="text-scale-1000">
- <p>Error connecting to API</p>
- <p>{`${jsonSchemaError}`}</p>
- </div>
- </div>
- ) : (
- <>
- {jsonSchema ? (
- <>
- <div className="sticky top-0 z-10 bg-scale-100 dark:bg-scale-300">
- <LangSelector
- selectedLang={selectedLang}
- setSelectedLang={setSelectedLang}
- showApiKey={showApiKey}
- setShowApiKey={setShowApiKey}
- apiKey={anonKey}
- autoApiService={autoApiService}
- />
- </div>
- <GeneralContent
- autoApiService={autoApiService}
- selectedLang={selectedLang}
- showApiKey={true}
- page={page}
- />
-
- <GeneratingTypes selectedLang={selectedLang} />
-
- {jsonSchema?.definitions && (
- <ResourceContent
- autoApiService={autoApiService}
- selectedLang={selectedLang}
- resourceId={tables.find((table) => table.id === Number(id))?.name}
- resources={resources}
- definitions={jsonSchema.definitions}
- paths={jsonSchema.paths}
- showApiKey={showApiKey.key}
- refreshDocs={refreshDocs}
- />
- )}
- </>
- ) : (
- <div className="p-6 mx-auto text-center sm:w-full md:w-3/4">
- <h3 className="text-lg">Building docs ...</h3>
- </div>
- )}
- </>
- )}
- </SidePanel.Content>
- </div>
- </SidePanel>
+ onClose={() => setApiPreviewPanelOpen(false)}
+ />
</>
)
}
diff --git a/studio/components/interfaces/TableGridEditor/ViewDefinition.tsx b/studio/components/interfaces/TableGridEditor/ViewDefinition.tsx
index c3bec258a71..60bf2e111f3 100644
--- a/studio/components/interfaces/TableGridEditor/ViewDefinition.tsx
+++ b/studio/components/interfaces/TableGridEditor/ViewDefinition.tsx
@@ -2,14 +2,28 @@ import { useRef } from 'react'
import Editor from '@monaco-editor/react'
import { timeout } from 'lib/helpers'
import { useStore } from 'hooks'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { useViewDefinitionQuery } from 'data/database/view-definition-query'
+import ShimmeringLoader from 'components/ui/ShimmeringLoader'
-const ViewDefinition = () => {
+export interface ViewDefinitionProps {
+ name: string
+}
+
+const ViewDefinition = ({ name }: ViewDefinitionProps) => {
const editorRef = useRef(null)
const monacoRef = useRef(null)
const { ui } = useStore()
const { isDarkTheme } = ui
+ const { project } = useProjectContext()
+ const { data: definition, isLoading } = useViewDefinitionQuery({
+ name,
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ })
+
const handleEditorOnMount = async (editor: any, monaco: any) => {
editorRef.current = editor
monacoRef.current = monaco
@@ -28,17 +42,24 @@ const ViewDefinition = () => {
editor?.focus()
}
- return (
+ return isLoading ? (
+ <div className="py-4 space-y-2">
+ <ShimmeringLoader />
+ <ShimmeringLoader className="w-3/4" />
+ <ShimmeringLoader className="w-1/2" />
+ </div>
+ ) : (
<div className="flex-grow overflow-y-auto border-t border-scale-400">
<Editor
className="monaco-editor"
theme={isDarkTheme ? 'vs-dark' : 'vs'}
onMount={handleEditorOnMount}
defaultLanguage="pgsql"
- defaultValue={'Hello'}
+ defaultValue={definition}
path={''}
options={{
domReadOnly: true,
+ readOnly: true,
tabSize: 2,
fontSize: 13,
minimap: { enabled: false },
diff --git a/studio/data/database/view-definition-query.ts b/studio/data/database/view-definition-query.ts
index e69de29bb2d..c9f6cb1c2de 100644
--- a/studio/data/database/view-definition-query.ts
+++ b/studio/data/database/view-definition-query.ts
@@ -0,0 +1,71 @@
+import { UseQueryOptions } from '@tanstack/react-query'
+import { useCallback } from 'react'
+import { ExecuteSqlData, useExecuteSqlPrefetch, useExecuteSqlQuery } from '../sql/execute-sql-query'
+
+type getViewDefinition = {
+ name?: string
+}
+
+type ViewDefinition = {
+ id: number
+ constraint_name: string
+ deletion_action: string
+ source_id: string
+ source_schema: string
+ source_table: string
+ source_columns: string
+ target_id: string
+ target_schema: string
+ target_table: string
+ target_columns: string
+}
+
+export const getViewDefinitionQuery = ({ name }: getViewDefinition) => {
+ const sql = /* SQL */ `
+select pg_get_viewdef('${name}', true) as definition
+`.trim()
+ return sql
+}
+
+export type ViewDefinitionVariables = getViewDefinition & {
+ projectRef?: string
+ connectionString?: string
+}
+
+export type ViewDefinitionData = any
+export type ViewDefinitionError = unknown
+
+export const useViewDefinitionQuery = <TData extends ViewDefinitionData = ViewDefinitionData>(
+ { projectRef, connectionString, name }: ViewDefinitionVariables,
+ options: UseQueryOptions<ExecuteSqlData, ViewDefinitionError, TData> = {}
+) => {
+ return useExecuteSqlQuery(
+ {
+ projectRef,
+ connectionString,
+ sql: getViewDefinitionQuery({ name }),
+ queryKey: [`view-definition-${name}`],
+ },
+ {
+ select(data) {
+ return data.result[0].definition.trim()
+ },
+ ...options,
+ }
+ )
+}
+
+export const useViewDefinitionQueryPrefetch = () => {
+ const prefetch = useExecuteSqlPrefetch()
+
+ return useCallback(
+ ({ projectRef, connectionString, name }: ViewDefinitionVariables) =>
+ prefetch({
+ projectRef,
+ connectionString,
+ sql: getViewDefinitionQuery({ name }),
+ queryKey: [`view-definition-${name}`],
+ }),
+ [prefetch]
+ )
+}