Skip to content

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

Chore/make api docs permanent (#18749)

Joshen Lim9bc6b8e2ce95
diff --git a/packages/ui/src/components/Modal/Modal.tsx b/packages/ui/src/components/Modal/Modal.tsx
index 2dde90265c7..5752f01a973 100644
--- a/packages/ui/src/components/Modal/Modal.tsx
+++ b/packages/ui/src/components/Modal/Modal.tsx
@@ -7,7 +7,6 @@ import { AnimationTailwindClasses } from '../../types'
import * as Dialog from '@radix-ui/react-dialog'
-import { Transition } from '@headlessui/react'
import styleHandler from '../../lib/theme/styleHandler'
// import { Transition } from '@tailwindui/react'
@@ -28,7 +27,6 @@ interface RadixProps
interface Props {
children?: React.ReactNode
customFooter?: React.ReactNode
- closable?: boolean
description?: string
hideFooter?: boolean
alignFooter?: 'right' | 'left'
@@ -39,7 +37,12 @@ interface Props {
cancelText?: string
onConfirm?: any
confirmText?: string
+ /**
+ * @deprecated This prop is no longer being used in the Modal component
+ */
+ closable?: boolean
showIcon?: boolean
+ showCloseButton?: boolean
footerBackground?: boolean
title?: string | React.ReactNode
variant?: 'danger' | 'warning' | 'success'
@@ -59,7 +62,6 @@ interface Props {
const Modal = ({
children,
customFooter = undefined,
- closable,
description,
hideFooter = false,
alignFooter = 'left',
@@ -69,7 +71,9 @@ const Modal = ({
onConfirm = () => {},
onCancel = () => {},
confirmText = 'Confirm',
+ closable = false,
showIcon = false,
+ showCloseButton = false,
title,
footerBackground,
icon,
@@ -86,32 +90,12 @@ const Modal = ({
...props
}: ModalProps) => {
const [open, setOpen] = React.useState(visible ? visible : false)
-
const __styles = styleHandler('modal')
useEffect(() => {
setOpen(visible)
}, [visible])
- function stopPropagation(e: React.MouseEvent) {
- e.stopPropagation()
- }
-
- // let footerClasses = [ModalStyles['sbui-modal-footer']]
- if (footerBackground) {
- // footerClasses.push(ModalStyles['sbui-modal-footer--with-bg'])
- }
-
- let modalClasses = [
- __styles.base,
- // ModalStyles[`sbui-modal`],
- // ModalStyles[`sbui-modal--${size}`],
- ]
- // if (className) modalClasses.push(className)
-
- // let overlayClasses = [ModalStyles['sbui-modal-overlay']]
- // if (overlayClassName) overlayClasses.push(overlayClassName)
-
const footerContent = customFooter ? (
customFooter
) : (
@@ -149,13 +133,7 @@ const Modal = ({
return (
<Dialog.Root open={open} onOpenChange={handleOpenChange}>
- {triggerElement && (
- <Dialog.Trigger
- // className={ModalStyles[`sbui-modal__trigger`]}
- >
- {triggerElement}
- </Dialog.Trigger>
- )}
+ {triggerElement && <Dialog.Trigger>{triggerElement}</Dialog.Trigger>}
<Dialog.Portal>
<Dialog.Overlay className={__styles.overlay} />
<Dialog.Overlay className={__styles.scroll_overlay}>
@@ -164,24 +142,21 @@ const Modal = ({
onInteractOutside={props.onInteractOutside}
onEscapeKeyDown={props.onEscapeKeyDown}
>
- {header && <div className={__styles.header}>{header}</div>}
- {/* <div
- className={ModalStyles['sbui-modal-content']}
- style={contentStyle}
- > */}
+ {header && (
+ <div className={__styles.header}>
+ {header}
+ {showCloseButton && (
+ <Button
+ onClick={onCancel}
+ type="text"
+ icon={<IconX size="medium" />}
+ className="px-1"
+ />
+ )}
+ </div>
+ )}
{children}
- {/* </div> */}
{!hideFooter && <div className={__styles.footer}>{footerContent}</div>}
- {/* {closable && (
- <div className={ModalStyles['sbui-modal-close-container']}>
- <Button
- onClick={onCancel}
- type="text"
- shadow={false}
- icon={<IconX size="medium" />}
- />
- </div>
- )} */}
</Dialog.Content>
</Dialog.Overlay>
</Dialog.Portal>
diff --git a/studio/components/grid/types/grid.ts b/studio/components/grid/types/grid.ts
index 76517a3c5de..66777ad9821 100644
--- a/studio/components/grid/types/grid.ts
+++ b/studio/components/grid/types/grid.ts
@@ -65,15 +65,6 @@ export interface SupabaseGridProps {
*/
onEditRow?: (row: SupaRow) => void
onError?: (error: any) => void
- /**
- * Toggle api preview panel open
- */
- apiPreviewPanelOpen?: boolean
- setApiPreviewPanelOpen?: () => void
- /**
- * Refresh the docs after a change is made to the table
- */
- refreshDocs: () => void
onExpandJSONEditor: (column: string, row: SupaRow) => void
updateTableRow: (previousRow: any, updatedData: any) => void
onEditForeignKeyColumnValue: (args: {
diff --git a/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsx b/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsx
index 9963867ad69..a8a6d8bfea0 100644
--- a/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsx
+++ b/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsx
@@ -21,7 +21,6 @@ export const useFeaturePreviewContext = () => useContext(FeaturePreviewContext)
export const FeaturePreviewContextProvider = ({ children }: PropsWithChildren<{}>) => {
const [flags, setFlags] = useState({
[LOCAL_STORAGE_KEYS.UI_PREVIEW_NAVIGATION_LAYOUT]: false,
- [LOCAL_STORAGE_KEYS.UI_PREVIEW_API_SIDE_PANEL]: false,
})
useEffect(() => {
@@ -29,8 +28,6 @@ export const FeaturePreviewContextProvider = ({ children }: PropsWithChildren<{}
setFlags({
[LOCAL_STORAGE_KEYS.UI_PREVIEW_NAVIGATION_LAYOUT]:
localStorage.getItem(LOCAL_STORAGE_KEYS.UI_PREVIEW_NAVIGATION_LAYOUT) === 'true',
- [LOCAL_STORAGE_KEYS.UI_PREVIEW_API_SIDE_PANEL]:
- localStorage.getItem(LOCAL_STORAGE_KEYS.UI_PREVIEW_API_SIDE_PANEL) === 'true',
})
}
}, [])
@@ -54,8 +51,3 @@ export const useIsNavigationPreviewEnabled = () => {
const { flags } = useFeaturePreviewContext()
return flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_NAVIGATION_LAYOUT]
}
-
-export const useIsAPIDocsSidePanelEnabled = () => {
- const { flags } = useFeaturePreviewContext()
- return flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_API_SIDE_PANEL]
-}
diff --git a/studio/components/interfaces/App/FeaturePreview/FeaturePreviewModal.tsx b/studio/components/interfaces/App/FeaturePreview/FeaturePreviewModal.tsx
index 0b40b2ad043..56840088487 100644
--- a/studio/components/interfaces/App/FeaturePreview/FeaturePreviewModal.tsx
+++ b/studio/components/interfaces/App/FeaturePreview/FeaturePreviewModal.tsx
@@ -3,27 +3,20 @@ import { useRouter } from 'next/router'
import { useState } from 'react'
import { Button, IconExternalLink, IconEye, IconEyeOff, Modal, ScrollArea, cn } from 'ui'
-import { LOCAL_STORAGE_KEYS } from 'lib/constants'
import Telemetry from 'lib/telemetry'
+import { FlaskConical } from 'lucide-react'
+import Link from 'next/link'
import { useAppStateSnapshot } from 'state/app-state'
-import APISidePanelPreview from './APISidePanelPreview'
import { useFeaturePreviewContext } from './FeaturePreviewContext'
-import Link from 'next/link'
// [Ivan] We should probably move this to a separate file, together with LOCAL_STORAGE_KEYS. We should make adding new feature previews as simple as possible.
-const FEATURE_PREVIEWS = [
+const FEATURE_PREVIEWS: { key: string; name: string; content: any; discussionsUrl?: string }[] = [
// {
// key: LOCAL_STORAGE_KEYS.UI_PREVIEW_NAVIGATION_LAYOUT,
// name: 'Global navigation update',
- // content: null
+ // content: null,
// },
- {
- key: LOCAL_STORAGE_KEYS.UI_PREVIEW_API_SIDE_PANEL,
- name: 'Project API documentation',
- content: <APISidePanelPreview />,
- discussionsUrl: 'https://github.com/orgs/supabase/discussions/18038',
- },
]
const FeaturePreviewModal = () => {
@@ -31,7 +24,7 @@ const FeaturePreviewModal = () => {
const snap = useAppStateSnapshot()
const telemetryProps = useTelemetryProps()
const featurePreviewContext = useFeaturePreviewContext()
- const [selectedFeatureKey, setSelectedFeatureKey] = useState<string>(FEATURE_PREVIEWS[0].key)
+ const [selectedFeatureKey, setSelectedFeatureKey] = useState<string>(FEATURE_PREVIEWS?.[0]?.key)
const { flags, onUpdateFlag } = featurePreviewContext
const selectedFeature = FEATURE_PREVIEWS.find((preview) => preview.key === selectedFeatureKey)
@@ -53,57 +46,79 @@ const FeaturePreviewModal = () => {
return (
<Modal
hideFooter
+ showCloseButton
size="xlarge"
className="max-w-4xl"
header="Dashboard feature previews"
visible={snap.showFeaturePreviewModal}
onCancel={() => snap.setShowFeaturePreviewModal(false)}
>
- <div className="flex">
- <div>
- <ScrollArea className="h-[550px] w-[240px] border-r">
- {FEATURE_PREVIEWS.map((feature) => {
- const isEnabled = flags[feature.key] ?? false
+ {FEATURE_PREVIEWS.length > 0 ? (
+ <div className="flex">
+ <div>
+ <ScrollArea className="h-[550px] w-[240px] border-r">
+ {FEATURE_PREVIEWS.map((feature) => {
+ const isEnabled = flags[feature.key] ?? false
- return (
- <div
- key={feature.key}
- onClick={() => setSelectedFeatureKey(feature.key)}
- className={cn(
- 'flex items-center space-x-3 p-4 border-b cursor-pointer bg transition',
- selectedFeatureKey === feature.key ? 'bg-surface-200' : ''
- )}
- >
- {isEnabled ? (
- <IconEye size={14} strokeWidth={2} className="text-brand" />
- ) : (
- <IconEyeOff size={14} strokeWidth={1.5} className="text-foreground-light" />
- )}
- <p className="text-sm">{feature.name}</p>
- </div>
- )
- })}
- </ScrollArea>
- </div>
- <div className="flex-grow max-h-[550px] p-4 space-y-3 overflow-y-auto">
- <div className="flex items-center justify-between">
- <p>{selectedFeature?.name}</p>
- <div className="flex items-center space-x-2">
- {selectedFeature?.discussionsUrl !== undefined && (
- <Button asChild type="default" icon={<IconExternalLink strokeWidth={1.5} />}>
- <Link href={selectedFeature.discussionsUrl} target="_blank" rel="noreferrer">
- Give feedback
- </Link>
+ return (
+ <div
+ key={feature.key}
+ onClick={() => setSelectedFeatureKey(feature.key)}
+ className={cn(
+ 'flex items-center space-x-3 p-4 border-b cursor-pointer bg transition',
+ selectedFeatureKey === feature.key ? 'bg-surface-200' : ''
+ )}
+ >
+ {isEnabled ? (
+ <IconEye size={14} strokeWidth={2} className="text-brand" />
+ ) : (
+ <IconEyeOff size={14} strokeWidth={1.5} className="text-foreground-light" />
+ )}
+ <p className="text-sm">{feature.name}</p>
+ </div>
+ )
+ })}
+ </ScrollArea>
+ </div>
+ <div className="flex-grow max-h-[550px] p-4 space-y-3 overflow-y-auto">
+ <div className="flex items-center justify-between">
+ <p>{selectedFeature?.name}</p>
+ <div className="flex items-center space-x-2">
+ {selectedFeature?.discussionsUrl !== undefined && (
+ <Button asChild type="default" icon={<IconExternalLink strokeWidth={1.5} />}>
+ <Link href={selectedFeature.discussionsUrl} target="_blank" rel="noreferrer">
+ Give feedback
+ </Link>
+ </Button>
+ )}
+ <Button type="default" onClick={() => toggleFeature()}>
+ {isSelectedFeatureEnabled ? 'Disable' : 'Enable'} feature
</Button>
- )}
- <Button type="default" onClick={() => toggleFeature()}>
- {isSelectedFeatureEnabled ? 'Disable' : 'Enable'} feature
- </Button>
+ </div>
</div>
+ {selectedFeature?.content}
+ </div>
+ </div>
+ ) : (
+ <div className="h-[550px] flex flex-col items-center justify-center">
+ <FlaskConical size={30} strokeWidth={1.5} className="text-foreground-light" />
+ <div className="mt-1 mb-3 flex flex-col items-center gap-y-0.5">
+ <p className="text-sm">No feature previews available</p>
+ <p className="text-sm text-foreground-light">
+ Have an idea for the dashboard? Let us know via Github Discussions!
+ </p>
</div>
- {selectedFeature?.content}
+ <Button asChild type="default" icon={<IconExternalLink strokeWidth={1.5} />}>
+ <Link
+ href="https://github.com/orgs/supabase/discussions/categories/feature-requests"
+ target="_blank"
+ rel="noreferrer"
+ >
+ Github Discussions
+ </Link>
+ </Button>
</div>
- </div>
+ )}
</Modal>
)
}
diff --git a/studio/components/interfaces/Auth/Users/Users.tsx b/studio/components/interfaces/Auth/Users/Users.tsx
index 1c810380a13..0bba6d0cdf7 100644
--- a/studio/components/interfaces/Auth/Users/Users.tsx
+++ b/studio/components/interfaces/Auth/Users/Users.tsx
@@ -1,19 +1,16 @@
import { useParams } from 'common'
import { useState } from 'react'
-import { Button, IconCode, IconRefreshCw, IconSearch, IconX, Input, Listbox } from 'ui'
+import { Button, IconRefreshCw, IconSearch, IconX, Input, Listbox } from 'ui'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import APIDocsButton from 'components/ui/APIDocsButton'
import { useUsersQuery } from 'data/auth/users-query'
import AddUserDropdown from './AddUserDropdown'
import UsersList from './UsersList'
-import { useAppStateSnapshot } from 'state/app-state'
-import { useIsAPIDocsSidePanelEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'
const Users = () => {
const { project } = useProjectContext()
const { ref: projectRef } = useParams()
- const snap = useAppStateSnapshot()
- const isNewAPIDocsEnabled = useIsAPIDocsSidePanelEnabled()
const [page, setPage] = useState(1)
const [search, setSearch] = useState('')
@@ -84,19 +81,7 @@ const Users = () => {
</Listbox>
</div>
<div className="mt-4 flex items-center gap-2 md:mt-0">
- {isNewAPIDocsEnabled && (
- <Button
- size="tiny"
- type="default"
- icon={<IconCode size={14} strokeWidth={2} />}
- onClick={() => {
- snap.setActiveDocsSection(['user-management'])
- snap.setShowProjectApiDocs(true)
- }}
- >
- API
- </Button>
- )}
+ <APIDocsButton section={['user-management']} />
<Button
size="tiny"
icon={<IconRefreshCw />}
diff --git a/studio/components/interfaces/Docs/Authentication.tsx b/studio/components/interfaces/Docs/Authentication.tsx
deleted file mode 100644
index 296584ac070..00000000000
--- a/studio/components/interfaces/Docs/Authentication.tsx
+++ /dev/null
@@ -1,109 +0,0 @@
-import Link from 'next/link'
-
-import { AutoApiService } from 'data/config/project-api-query'
-import CodeSnippet from './CodeSnippet'
-import Snippets from './Snippets'
-
-interface AuthenticationProps {
- autoApiService: AutoApiService
- selectedLang: 'bash' | 'js'
- showApiKey: string
-}
-
-const Authentication = ({ autoApiService, selectedLang, showApiKey }: AuthenticationProps) => {
- // [Joshen] ShowApiKey should really be a boolean, its confusing
- const defaultApiKey =
- showApiKey !== 'SUPABASE_KEY'
- ? autoApiService?.defaultApiKey ?? 'SUPABASE_CLIENT_API_KEY'
- : 'SUPABASE_CLIENT_API_KEY'
- const serviceApiKey =
- showApiKey !== 'SUPABASE_KEY'
- ? autoApiService?.serviceApiKey ?? 'SUPABASE_SERVICE_KEY'
- : 'SUPABASE_SERVICE_KEY'
-
- return (
- <>
- <h2 className="doc-heading">Authentication</h2>
- <div className="doc-section">
- <article className="code-column text-foreground">
- <p>Supabase works through a mixture of JWT and Key auth.</p>
- <p>
- If no <code>Authorization</code> header is included, the API will assume that you are
- making a request with an anonymous user.
- </p>
- <p>
- If an <code>Authorization</code> header is included, the API will "switch" to the role
- of the user making the request. See the User Management section for more details.
- </p>
- <p>We recommend setting your keys as Environment Variables.</p>
- </article>
- </div>
-
- <h2 className="doc-heading">Client API Keys</h2>
- <div className="doc-section ">
- <article className="code-column text-foreground">
- <p>
- Client keys allow "anonymous access" to your database, until the user has logged in.
- After logging in the keys will switch to the user's own login token.
- </p>
- <p>
- In this documentation, we will refer to the key using the name <code>SUPABASE_KEY</code>
- .
- </p>
- <p>
- We have provided you a Client Key to get started. You will soon be able to add as many
- keys as you like. You can find the <code>anon</code> key in the{' '}
- <Link href={`/project/${autoApiService.project.ref}/settings/api`}>API Settings</Link>{' '}
- page.
- </p>
- </article>
- <article className="code">
- <CodeSnippet
- selectedLang={selectedLang}
- snippet={Snippets.authKey('CLIENT API KEY', 'SUPABASE_KEY', defaultApiKey)}
- />
- <CodeSnippet
- selectedLang={selectedLang}
- snippet={Snippets.authKeyExample(defaultApiKey, autoApiService.endpoint, {
- showBearer: false,
- })}
- />
- </article>
- </div>
-
- <h2 className="doc-heading">Service Keys</h2>
- <div className="doc-section ">
- <article className="code-column text-foreground">
- <p>
- Service keys have FULL access to your data, bypassing any security policies. Be VERY
- careful where you expose these keys. They should only be used on a server and never on a
- client or browser.
- </p>
- <p>
- In this documentation, we will refer to the key using the name <code>SERVICE_KEY</code>.
- </p>
- <p>
- We have provided you with a Service Key to get started. Soon you will be able to add as
- many keys as you like. You can find the <code>service_role</code> in the{' '}
- <Link href={`/project/${autoApiService.project.ref}/settings/api`}>API Settings</Link>{' '}
- page.
- </p>
- </article>
- <article className="code">
- <CodeSnippet
- selectedLang={selectedLang}
- snippet={Snippets.authKey('SERVICE KEY', 'SERVICE_KEY', serviceApiKey)}
- />
- <CodeSnippet
- selectedLang={selectedLang}
- snippet={Snippets.authKeyExample(serviceApiKey, autoApiService.endpoint, {
- keyName: 'SERVICE_KEY',
- })}
- />
- </article>
- </div>
- </>
- )
-}
-
-export default Authentication
diff --git a/studio/components/interfaces/Docs/CodeSnippet.tsx b/studio/components/interfaces/Docs/CodeSnippet.tsx
deleted file mode 100644
index 9bb0b831f29..00000000000
--- a/studio/components/interfaces/Docs/CodeSnippet.tsx
+++ /dev/null
@@ -1,23 +0,0 @@
-import SimpleCodeBlock from 'components/to-be-cleaned/SimpleCodeBlock'
-
-interface CodeSnippetProps {
- selectedLang: 'bash' | 'js'
- snippet: {
- title?: string
- bash: { language?: string; code: string }
- js?: { language?: string; code: string }
- }
-}
-
-const CodeSnippet = ({ selectedLang, snippet }: CodeSnippetProps) => {
- if (!snippet[selectedLang]) return null
- return (
- <div className="codeblock-container">
- <h4>{snippet.title}</h4>
- <SimpleCodeBlock className={snippet[selectedLang]?.language}>
- {snippet[selectedLang]?.code}
- </SimpleCodeBlock>
- </div>
- )
-}
-export default CodeSnippet
diff --git a/studio/components/interfaces/Docs/Description.tsx b/studio/components/interfaces/Docs/Description.tsx
deleted file mode 100644
index e308488d9b4..00000000000
--- a/studio/components/interfaces/Docs/Description.tsx
+++ /dev/null
@@ -1,120 +0,0 @@
-import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { noop } from 'lodash'
-import { useState } from 'react'
-import { Button, IconLoader } from 'ui'
-
-import AutoTextArea from 'components/to-be-cleaned/forms/AutoTextArea'
-import { useCheckPermissions, useStore } from 'hooks'
-import { timeout } from 'lib/helpers'
-
-// Removes some auto-generated Postgrest text
-// Ideally PostgREST wouldn't add this if there is already a comment
-const temp_removePostgrestText = (content: string) => {
- const postgrestTextPk = `Note:\nThis is a Primary Key.<pk/>`
- const postgrestTextFk = `Note:\nThis is a Foreign Key to`
- const pkTextPos = content.lastIndexOf(postgrestTextPk)
- const fkTextPos = content.lastIndexOf(postgrestTextFk)
-
- let cleansed = content
- if (pkTextPos >= 0) cleansed = cleansed.substring(0, pkTextPos)
- if (fkTextPos >= 0) cleansed = cleansed.substring(0, fkTextPos)
- return cleansed
-}
-
-interface DescrptionProps {
- content: string
- metadata: { table?: string; column?: string; rpc?: string }
- onChange: (value: string) => void
-}
-
-const Description = ({ content, metadata, onChange = noop }: DescrptionProps) => {
- const { meta, ui } = useStore()
-
- const contentText = temp_removePostgrestText(content || '').trim()
- const [value, setValue] = useState(contentText)
- const [isUpdating, setIsUpdating] = useState(false)
-
- const { table, column, rpc } = metadata
-
- const hasChanged = value != contentText
- const animateCss = `transition duration-150`
-
- const canUpdateDescription = useCheckPermissions(PermissionAction.TENANT_SQL_QUERY, '*')
-
- const updateDescription = async () => {
- if (isUpdating || !canUpdateDescription) return false
-
- setIsUpdating(true)
- let query = ''
- let description = value.replaceAll("'", "''")
- if (table && column)
- query = `comment on column public."${table}"."${column}" is '${description}';`
- if (table && !column) query = `comment on table public."${table}" is '${description}';`
- if (rpc) query = `comment on function "${rpc}" is '${description}';`
-
- if (query) {
- const res = await meta.query(query)
-
- // [Joshen] Temp fix, immediately refreshing the docs fetches stale state
- await timeout(500)
-
- if (res.error) {
- ui.setNotification({
- error: res.error,
- category: 'error',
- message: `Failed to update description: ${res.error.message}`,
- })
- } else {
- ui.setNotification({
- category: 'success',
- message: `Successfully updated description`,
- })
- }
- }
-
- onChange(value)
- setIsUpdating(false)
- }
-
- if (!canUpdateDescription) {
- return (
- <span className={`block ${value ? 'text-foreground' : ''}`}>{value || 'No description'}</span>
- )
- }
-
- return (
- <div className="space-y-2">
- <AutoTextArea
- className="w-full"
- placeholder="Click to edit."
- value={value}
- onChange={(e: any) => setValue(e.target.value)}
- />
- <div
- className={`flex items-center gap-2 ${
- hasChanged ? 'opacity-100' : 'h-0 cursor-default opacity-0'
- } ${animateCss}`}
- >
- <Button
- type="default"
- disabled={!hasChanged}
- onClick={() => {
- setValue(contentText)
- setIsUpdating(false)
- }}
- >
- Cancel
- </Button>
- <Button disabled={!hasChanged} onClick={updateDescription}>
- {isUpdating ? (
- <IconLoader className="mx-auto animate-spin" size={14} strokeWidth={2} />
- ) : (
- <span>Save</span>
- )}
- </Button>
- </div>
- </div>
- )
-}
-
-export default Description
diff --git a/studio/components/interfaces/Docs/Docs.types.ts b/studio/components/interfaces/Docs/Docs.types.ts
deleted file mode 100644
index 7ea36375c90..00000000000
--- a/studio/components/interfaces/Docs/Docs.types.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-export type showApiKey = {
- key: string
- name: string
-}
diff --git a/studio/components/interfaces/Docs/GeneralContent.tsx b/studio/components/interfaces/Docs/GeneralContent.tsx
deleted file mode 100644
index cb336120919..00000000000
--- a/studio/components/interfaces/Docs/GeneralContent.tsx
+++ /dev/null
@@ -1,38 +0,0 @@
-import Introduction from 'components/interfaces/Docs/Introduction'
-import Authentication from 'components/interfaces/Docs/Authentication'
-import TablesIntroduction from 'components/interfaces/Docs/Pages/Tables/Introduction'
-import UserManagement from 'components/interfaces/Docs/Pages/UserManagement'
-import RpcIntroduction from 'components/interfaces/Docs/Pages/Rpc/Introduction'
-
-const GeneralContent = ({ autoApiService, selectedLang, page, showApiKey }: any) => {
- let selected = page?.toLowerCase()
- if (selected == 'intro' || selected == null)
- return <Introduction autoApiService={autoApiService} selectedLang={selectedLang} />
- if (selected == 'auth')
- return (
- <Authentication
- autoApiService={autoApiService}
- selectedLang={selectedLang}
- showApiKey={showApiKey}
- />
- )
- if (selected == 'users')
- return (
- <UserManagement
- autoApiService={autoApiService}
- selectedLang={selectedLang}
- showApiKey={showApiKey}
- />
- )
- if (selected == 'tables-intro') return <TablesIntroduction selectedLang={selectedLang} />
- if (selected == 'rpc-intro') return <RpcIntroduction />
- else
- return (
- <div>
- <h2 className="m-4">Not found</h2>
- <p className="m-4"> Looks like you went somewhere that nobody knows.</p>
- </div>
- )
-}
-
-export default GeneralContent
diff --git a/studio/components/interfaces/Docs/GeneratingTypes.tsx b/studio/components/interfaces/Docs/GeneratingTypes.tsx
deleted file mode 100644
index 97e8df27e3a..00000000000
--- a/studio/components/interfaces/Docs/GeneratingTypes.tsx
+++ /dev/null
@@ -1,123 +0,0 @@
-import Link from 'next/link'
-import { useState } from 'react'
-import { Button, IconDownload, IconExternalLink } from 'ui'
-
-import { useParams } from 'common/hooks'
-import CodeSnippet from 'components/interfaces/Docs/CodeSnippet'
-import { generateTypes } from 'data/projects/project-type-generation-query'
-import { useStore } from 'hooks'
-
-interface Props {
- selectedLang: 'bash' | 'js'
-}
-
-export default function GeneratingTypes({ selectedLang }: Props) {
- const { ref } = useParams()
- const { ui } = useStore()
- const [isGeneratingTypes, setIsGeneratingTypes] = useState(false)
-
- const onClickGenerateTypes = async () => {
- try {
- setIsGeneratingTypes(true)
- const res = await generateTypes({ ref })
- let element = document.createElement('a')
- element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(res.types))
- element.setAttribute('download', 'supabase.ts')
- element.style.display = 'none'
- document.body.appendChild(element)
- element.click()
- document.body.removeChild(element)
- ui.setNotification({
- category: 'success',
- message: `Successfully generated types! File is being downloaded`,
- })
- } catch (error: any) {
- ui.setNotification({
- error,
- category: 'error',
- message: `Failed to generate types: ${error.message}`,
- })
- } finally {
- setIsGeneratingTypes(false)
- }
- }
-
- return (
- <>
- <h2 className="doc-heading flex items-center justify-between">
- <span>Generating types</span>
- <Button asChild type="default" icon={<IconExternalLink />}>
- <Link
- href="https://supabase.com/docs/guides/database/api/generating-types"
- target="_blank"
- rel="noreferrer"
- >
- Documentation
- </Link>
- </Button>
- </h2>
- <div className="doc-section">
- <article className="code-column text-foreground">
- <p>
- Supabase APIs are generated from your database, which means that we can use database
- introspection to generate type-safe API definitions.
- </p>
- <p>
- You can generate types from your database either through the{' '}
- <Link href="https://supabase.com/docs/guides/database/api/generating-types">
- Supabase CLI
- </Link>
- , or by downloading the types file via the button on the right and importing it in your
- application within <code>src/index.ts</code>.
- </p>
- </article>
- <article
- className={`code ${selectedLang === 'js' ? 'flex items-center justify-center' : ''}`}
- >
- <div className="grid gap-2">
- <p className="text-center">
- {selectedLang === 'js' && (
- <Button
- type="default"
- disabled={isGeneratingTypes}
- loading={isGeneratingTypes}
- icon={<IconDownload strokeWidth={1.5} />}
- onClick={onClickGenerateTypes}
- >
- Generate and download types
- </Button>
- )}
- </p>
- <p className="text-xs text-center text-foreground-light bg-background p-4">
- Remember to re-generate and download this file as you make changes to your tables.
- </p>
- </div>
- <CodeSnippet selectedLang={selectedLang} snippet={localSnippets.cliLogin()} />
- <CodeSnippet
- selectedLang={selectedLang}
- snippet={localSnippets.generateTypes(ref ?? '')}
- />
- </article>
- </div>
- </>
- )
-}
-
-const localSnippets = {
- cliLogin: () => ({
- title: 'Login via the CLI with your Personal Access Token',
- bash: {
- code: `
-npx supabase login
-`,
- },
- }),
- generateTypes: (ref: string) => ({
- title: 'Generate types',
- bash: {
- code: `
-npx supabase gen types typescript --project-id "${ref}" --schema public > types/supabase.ts
-`,
- },
- }),
-}
diff --git a/studio/components/interfaces/Docs/Introduction.tsx b/studio/components/interfaces/Docs/Introduction.tsx
deleted file mode 100644
index fcdd3f48e13..00000000000
--- a/studio/components/interfaces/Docs/Introduction.tsx
+++ /dev/null
@@ -1,23 +0,0 @@
-import { AutoApiService } from 'data/config/project-api-query'
-import Snippets from 'components/interfaces/Docs/Snippets'
-import CodeSnippet from './CodeSnippet'
-
-interface Props {
- autoApiService: AutoApiService
- selectedLang: 'bash' | 'js'
-}
-
-export default function Introduction({ autoApiService, selectedLang }: Props) {
- return (
- <>
- <div className="doc-section doc-section--client-libraries">
- <article className="code">
- <CodeSnippet
- selectedLang={selectedLang}
- snippet={Snippets.init(autoApiService.endpoint)}
- />
- </article>
- </div>
- </>
- )
-}
diff --git a/studio/components/interfaces/Docs/LangSelector.tsx b/studio/components/interfaces/Docs/LangSelector.tsx
deleted file mode 100644
index becbd171fce..00000000000
--- a/studio/components/interfaces/Docs/LangSelector.tsx
+++ /dev/null
@@ -1,114 +0,0 @@
-import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { useCheckPermissions } from 'hooks'
-import {
- Button,
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
- IconKey,
-} from 'ui'
-
-import { showApiKey } from 'components/interfaces/Docs/Docs.types'
-
-const DEFAULT_KEY = { name: 'hide', key: 'SUPABASE_KEY' }
-
-interface LangSelectorProps {
- selectedLang: string
- setSelectedLang: (selectedLang: string) => void
- showApiKey: showApiKey
- setShowApiKey: (showApiKey: showApiKey) => void
- apiKey: string | undefined
- autoApiService: any
-}
-
-const LangSelector = ({
- selectedLang,
- setSelectedLang,
- showApiKey,
- setShowApiKey,
- apiKey,
- autoApiService,
-}: LangSelectorProps) => {
- const canReadServiceKey = useCheckPermissions(
- PermissionAction.READ,
- 'service_api_keys.service_role_key'
- )
-
- return (
- <div className="p-1 w-1/2 ml-auto">
- <div className="z-0 flex justify-end">
- <button
- type="button"
- onClick={() => setSelectedLang('js')}
- className={`${
- selectedLang == 'js'
- ? 'bg-surface-100 font-medium text-foreground'
- : 'bg-alternative text-foreground-lighter'
- } relative inline-flex items-center border-r border-background p-1 px-2 text-sm transition hover:text-foreground focus:outline-none`}
- >
- JavaScript
- </button>
- <button
- type="button"
- onClick={() => setSelectedLang('bash')}
- className={`${
- selectedLang == 'bash'
- ? 'bg-surface-100 font-medium text-foreground'
- : 'bg-alternative text-foreground-lighter'
- } relative inline-flex items-center border-r border-background p-1 px-2 text-sm transition hover:text-foreground focus:outline-none`}
- >
- Bash
- </button>
- {selectedLang == 'bash' && (
- <div className="flex">
- <div className="flex items-center gap-2 p-1 pl-2 text-xs text-foreground-lighter">
- <IconKey size={12} strokeWidth={1.5} />
- <span>Project API key :</span>
- </div>
- <DropdownMenu>
- <DropdownMenuTrigger>
- <Button type="default">{showApiKey.name}</Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" side="bottom">
- <>
- <DropdownMenuItem key="hide" onClick={() => setShowApiKey(DEFAULT_KEY)}>
- hide
- </DropdownMenuItem>
- {apiKey && (
- <DropdownMenuItem
- key="anon"
- onClick={() =>
- setShowApiKey({
- key: apiKey,
- name: 'anon (public)',
- })
- }
- >
- <p>anon (public)</p>
- </DropdownMenuItem>
- )}
- {canReadServiceKey && (
- <DropdownMenuItem
- key="service"
- onClick={() =>
- setShowApiKey({
- key: autoApiService.serviceApiKey,
- name: 'service_role (secret)',
- })
- }
- >
- <p>service_role (secret)</p>
- </DropdownMenuItem>
- )}
- </>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- )}
- </div>
- </div>
- )
-}
-
-export default LangSelector
diff --git a/studio/components/interfaces/Docs/NoDescription.tsx b/studio/components/interfaces/Docs/NoDescription.tsx
deleted file mode 100644
index 7ffb0f43a26..00000000000
--- a/studio/components/interfaces/Docs/NoDescription.tsx
+++ /dev/null
@@ -1,11 +0,0 @@
-const NoDescription = () => {
- return (
- <p className="text-gray-300 text-sm">
- No description provided.
- <br />
- Hint: you can create a custom description by adding a "comment" to this item in your database.
- </p>
- )
-}
-
-export default NoDescription
diff --git a/studio/components/interfaces/Docs/Pages/Rpc/Introduction.tsx b/studio/components/interfaces/Docs/Pages/Rpc/Introduction.tsx
deleted file mode 100644
index bc78b7ef7b6..00000000000
--- a/studio/components/interfaces/Docs/Pages/Rpc/Introduction.tsx
+++ /dev/null
@@ -1,18 +0,0 @@
-const Introduction = () => {
- return (
- <>
- <h2 className="doc-heading">Introduction</h2>
- <div className="doc-section">
- <article className="code-column text-foreground">
- <p>
- All of your database stored procedures are available on your API. This means you can
- build your logic directly into the database (if you're brave enough)!
- </p>
- <p>The API endpoint supports POST (and in some cases GET) to execute the function.</p>
- </article>
- </div>
- </>
- )
-}
-
-export default Introduction
diff --git a/studio/components/interfaces/Docs/Pages/Tables/Introduction.tsx b/studio/components/interfaces/Docs/Pages/Tables/Introduction.tsx
deleted file mode 100644
index 499b9709810..00000000000
--- a/studio/components/interfaces/Docs/Pages/Tables/Introduction.tsx
+++ /dev/null
@@ -1,134 +0,0 @@
-import { useParams } from 'common'
-import Link from 'next/link'
-
-import CodeSnippet from 'components/interfaces/Docs/CodeSnippet'
-import GeneratingTypes from 'components/interfaces/Docs/GeneratingTypes'
-
-interface IntroductionProps {
- selectedLang: 'bash' | 'js'
-}
-
-const Introduction = ({ selectedLang }: IntroductionProps) => {
- const { ref } = useParams()
-
- return (
- <>
- <h2 className="doc-heading">Introduction</h2>
- <div className="doc-section">
- <article className="code-column text-foreground">
- <p>
- All views and tables in the <code>public</code> schema and accessible by the active
- database role for a request are available for querying.
- </p>
- </article>
- </div>
-
- <h2 className="doc-heading">Non-exposed tables</h2>
- <div className="doc-section">
- <article className="code-column text-foreground">
- <p>
- If you don't want to expose tables in your API, simply add them to a different schema
- (not the <code>public</code> schema).
- </p>
- </article>
- <article className="code"></article>
- </div>
-
- <GeneratingTypes selectedLang={selectedLang} />
-
- <h2 className="doc-heading">
- GraphQL <span className="lowercase">vs</span> Supabase
- </h2>
- <div className="doc-section">
- <article className="code-column text-foreground">
- <p>
- If you have a GraphQL background, you might be wondering if you can fetch your data in a
- single round-trip. The answer is yes!
- </p>
- <p>
- The syntax is very similar. This example shows how you might achieve the same thing with
- Apollo GraphQL and Supabase.
- <br />
- <br />
- </p>
- <h4>Still want GraphQL?</h4>
- <p>
- If you still want to use GraphQL, you can. Supabase provides you with a full Postgres
- database, so as long as your middleware can connect to the database then you can still
- use the tools you love. You can find the database connection details{' '}
- <Link href={`/project/${ref}/settings/database`}>in the settings.</Link>
- </p>
- </article>
- <article className="code">
- <CodeSnippet selectedLang={selectedLang} snippet={localSnippets.withApollo()} />
- <CodeSnippet selectedLang={selectedLang} snippet={localSnippets.withSupabase()} />
- </article>
- </div>
- </>
- )
-}
-
-const localSnippets = {
- withApollo: () => ({
- title: 'With Apollo GraphQL',
- bash: {
- language: 'js',
- code: `
-const { loading, error, data } = useQuery(gql\`
- query GetDogs {
- dogs {
- id
- breed
- owner {
- id
- name
- }
- }
- }
-\`)`,
- },
- js: {
- language: 'js',
- code: `
-const { loading, error, data } = useQuery(gql\`
- query GetDogs {
- dogs {
- id
- breed
- owner {
- id
- name
- }
- }
- }
-\`)`,
- },
- }),
- withSupabase: () => ({
- title: 'With Supabase',
- bash: {
- language: 'js',
- code: `
-const { data, error } = await supabase
- .from('dogs')
- .select(\`
- id, breed,
- owner (id, name)
- \`)
-`,
- },
- js: {
- language: 'js',
- code: `
-const { data, error } = await supabase
- .from('dogs')
- .select(\`
- id, breed,
- owner (id, name)
- \`)
-`,
- },
- }),
-}
-
-export default Introduction
diff --git a/studio/components/interfaces/Docs/Pages/UserManagement.tsx b/studio/components/interfaces/Docs/Pages/UserManagement.tsx
deleted file mode 100644
index 7184b7e8002..00000000000
--- a/studio/components/interfaces/Docs/Pages/UserManagement.tsx
+++ /dev/null
@@ -1,306 +0,0 @@
-import Link from 'next/link'
-import { useRouter } from 'next/router'
-
-import { AutoApiService } from 'data/config/project-api-query'
-import { makeRandomString } from 'lib/helpers'
-import CodeSnippet from '../CodeSnippet'
-import Snippets from '../Snippets'
-
-const randomPassword = makeRandomString(20)
-
-interface UserManagementProps {
- autoApiService: AutoApiService
- selectedLang: 'bash' | 'js'
- showApiKey: string
-}
-
-export default function UserManagement({
- autoApiService,
- selectedLang,
- showApiKey,
-}: UserManagementProps) {
- const router = useRouter()
-
- const keyToShow = showApiKey ? showApiKey : 'SUPABASE_KEY'
-
- return (
- <>
- <h2 className="doc-heading">User Management</h2>
- <div className="doc-section">
- <article className="code-column text-foreground">
- <p>Supabase makes it easy to manage your users.</p>
- <p>
- Supabase assigns each user a unique ID. You can reference this ID anywhere in your
- database. For example, you might create a <code>profiles</code> table references the
- user using a <code>user_id</code> field.
- </p>
- <p>
- Supabase already has built in the routes to sign up, login, and log out for managing
- users in your apps and websites.
- </p>
- </article>
- </div>
-
- <h2 className="doc-heading">Sign up</h2>
- <div className="doc-section ">
- <article className="code-column text-foreground">
- <p>Allow your users to sign up and create a new account.</p>
- <p>
- After they have signed up, all interactions using the Supabase JS client will be
- performed as "that user".
- </p>
- </article>
- <article className="code">
- <CodeSnippet
- selectedLang={selectedLang}
- snippet={Snippets.authSignup(autoApiService.endpoint, keyToShow, randomPassword)}
- />
- </article>
- </div>
-
- <h2 className="doc-heading">Log in with Email/Password</h2>
- <div className="doc-section ">
- <article className="code-column text-foreground">
- <p>If an account is created, users can login to your app.</p>
- <p>
- After they have logged in, all interactions using the Supabase JS client will be
- performed as "that user".
- </p>
- </article>
- <article className="code">
- <CodeSnippet
- selectedLang={selectedLang}
- snippet={Snippets.authLogin(autoApiService.endpoint, keyToShow, randomPassword)}
- />
- </article>
- </div>
-
- <h2 className="doc-heading">Log in with Magic Link via Email</h2>
- <div className="doc-section ">
- <article className="code-column text-foreground">
- <p>Send a user a passwordless link which they can use to redeem an access_token.</p>
- <p>
- After they have clicked the link, all interactions using the Supabase JS client will be
- performed as "that user".
- </p>
- </article>
- <article className="code">
- <CodeSnippet
- selectedLang={selectedLang}
- snippet={Snippets.authMagicLink(autoApiService.endpoint, keyToShow)}
- />
- </article>
- </div>
-
- <h2 className="doc-heading">Sign Up with Phone/Password</h2>
- <div className="doc-section ">
- <article className="code-column text-foreground">
- <p>
- A phone number can be used instead of an email as a primary account confirmation
- mechanism.
- </p>
- <p>
- The user will receive a mobile OTP via sms with which they can verify that they control
- the phone number.
- </p>
- <p>
- You must enter your own twilio credentials on the auth settings page to enable sms
- confirmations.
- </p>
- </article>
- <article className="code">
- <CodeSnippet
- selectedLang={selectedLang}
- snippet={Snippets.authPhoneSignUp(autoApiService.endpoint, keyToShow)}
- />
- </article>
- </div>
-
- <h2 className="doc-heading">Login via SMS OTP</h2>
- <div className="doc-section ">
- <article className="code-column text-foreground">
- <p>
- SMS OTPs work like magic links, except you have to provide an interface for the user to
- verify the 6 digit number they receive.
- </p>
- <p>
- You must enter your own twilio credentials on the auth settings page to enable SMS-based
- Logins.
- </p>
- </article>
- <article className="code">
- <CodeSnippet
- selectedLang={selectedLang}
- snippet={Snippets.authMobileOTPLogin(autoApiService.endpoint, keyToShow)}
- />
- </article>
- </div>
-
- <h2 className="doc-heading">Verify an SMS OTP</h2>
- <div className="doc-section ">
- <article className="code-column text-foreground">
- <p>
- Once the user has received the OTP, have them enter it in a form and send it for
- verification
- </p>
- <p>
- You must enter your own twilio credentials on the auth settings page to enable SMS-based
- OTP verification.
- </p>
- </article>
- <article className="code">
- <CodeSnippet
- selectedLang={selectedLang}
- snippet={Snippets.authMobileOTPVerify(autoApiService.endpoint, keyToShow)}
- />
- </article>
- </div>
-
- <h2 className="doc-heading">Log in with Third Party OAuth</h2>
- <div className="doc-section ">
- <article className="code-column text-foreground">
- <p>
- Users can log in with Third Party OAuth like Google, Facebook, GitHub, and more. You
- must first enable each of these in the Auth Providers settings{' '}
- <span className="text-green-500">
- <Link key={'AUTH'} href={`/project/${router.query.ref}/auth/providers`}>
- here
- </Link>
- </span>{' '}
- .
- </p>
- <p>
- View all the available{' '}
- <a
- href="https://supabase.com/docs/guides/auth#providers"
- target="_blank"
- rel="noreferrer"
- >
- Third Party OAuth providers
- </a>
- </p>
- <p>
- After they have logged in, all interactions using the Supabase JS client will be
- performed as "that user".
- </p>
- <p>
- Generate your Client ID and secret from:{` `}
- <a
- href="https://console.developers.google.com/apis/credentials"
- target="_blank"
- rel="noreferrer"
- >
- Google
- </a>
- ,{` `}
- <a href="https://github.com/settings/applications/new" target="_blank" rel="noreferrer">
- GitHub
- </a>
- ,{` `}
- <a href="https://gitlab.com/oauth/applications" target="_blank" rel="noreferrer">
- GitLab
- </a>
- ,{` `}
- <a href="https://developers.facebook.com/apps/" target="_blank" rel="noreferrer">
- Facebook
- </a>
- ,{` `}
- <a
- href="https://support.atlassian.com/bitbucket-cloud/docs/use-oauth-on-bitbucket-cloud/"
- target="_blank"
- rel="noreferrer"
- >
- Bitbucket
- </a>
- .
- </p>
- </article>
- <article className="code">
- <CodeSnippet selectedLang={selectedLang} snippet={Snippets.authThirdPartyLogin()} />
- </article>
- </div>
-
- <h2 className="doc-heading">User</h2>
- <div className="doc-section ">
- <article className="code-column text-foreground">
- <p>Get the JSON object for the logged in user.</p>
- </article>
- <article className="code">
- <CodeSnippet
- selectedLang={selectedLang}
- snippet={Snippets.authUser(autoApiService.endpoint, keyToShow)}
- />
- </article>
- </div>
-
- <h2 className="doc-heading">Forgotten Password Email</h2>
- <div className="doc-section ">
- <article className="code-column text-foreground">
- <p>
- Sends the user a log in link via email. Once logged in you should direct the user to a
- new password form. And use "Update User" below to save the new password.
- </p>
- </article>
- <article className="code">
- <CodeSnippet
- selectedLang={selectedLang}
- snippet={Snippets.authRecover(autoApiService.endpoint, keyToShow)}
- />
- </article>
- </div>
-
- <h2 className="doc-heading">Update User</h2>
- <div className="doc-section ">
- <article className="code-column text-foreground">
- <p>
- Update the user with a new email or password. Each key (email, password, and data) is
- optional
- </p>
- </article>
- <article className="code">
- <CodeSnippet
- selectedLang={selectedLang}
- snippet={Snippets.authUpdate(autoApiService.endpoint, keyToShow)}
- />
- </article>
- </div>
-
- <h2 className="doc-heading">Log out</h2>
- <div className="doc-section ">
- <article className="code-column text-foreground">
- <p>
- After calling log out, all interactions using the Supabase JS client will be
- "anonymous".
- </p>
- </article>
- <article className="code">
- <CodeSnippet
- selectedLang={selectedLang}
- snippet={Snippets.authLogout(autoApiService.endpoint, keyToShow)}
- />
- </article>
- </div>
-
- <h2 className="doc-heading">Send a User an Invite over Email</h2>
- <div className="doc-section ">
- <article className="code-column text-foreground">
- <p>Send a user a passwordless link which they can use to sign up and log in.</p>
- <p>
- After they have clicked the link, all interactions using the Supabase JS client will be
- performed as "that user".
- </p>
- <p>
- This endpoint requires you use the <code>service_role_key</code> when initializing the
- client, and should only be invoked from the server, never from the client.
- </p>
- </article>
- <article className="code">
- <CodeSnippet
- selectedLang={selectedLang}
- snippet={Snippets.authInvite(autoApiService.endpoint, keyToShow)}
- />
- </article>
- </div>
- </>
- )
-}
diff --git a/studio/components/interfaces/Docs/Param.tsx b/studio/components/interfaces/Docs/Param.tsx
deleted file mode 100644
index 4a97f170848..00000000000
--- a/studio/components/interfaces/Docs/Param.tsx
+++ /dev/null
@@ -1,104 +0,0 @@
-import { noop } from 'lodash'
-import { Badge, IconCode, IconDatabase } from 'ui'
-
-import Description from 'components/interfaces/Docs/Description'
-
-function getColumnType(type: string, format: string) {
- // json and jsonb both have type=undefined, so check format instead
- if (type === undefined && (format === 'jsonb' || format === 'json')) return 'json'
-
- switch (type) {
- case 'string':
- return 'string'
- case 'integer':
- return 'number'
- case 'json':
- return 'json'
- case 'number':
- return 'number'
- case 'boolean':
- return 'boolean'
- default:
- return ''
- }
-}
-
-interface ParamProps {
- name: string
- type: string
- format: string
- required: boolean
- description: boolean
- metadata?: any
- onDesciptionUpdated?: () => void
-}
-const Param = ({
- name,
- type,
- format,
- required,
- description,
- metadata = {},
- onDesciptionUpdated = noop,
-}: ParamProps) => {
- return (
- <>
- <div className="mb-4 flex items-center justify-between ">
- <div className="flex gap-2 items-center">
- <div className="flex items-center gap-2">
- <label className="font-mono text-xs uppercase text-foreground-lighter min-w-[55px]">
- Column
- </label>
-
- <div className="flex items-center gap-4">
- <span className="text-md text-foreground pb-0.5">{name}</span>
- </div>
- </div>
- </div>
-
- <Badge color={required ? 'amber' : 'scale'}>{required ? 'Required' : 'Optional'}</Badge>
- </div>
- {format && (
- <div className="grid gap-2 mt-6">
- <div className="mb-4 flex items-center gap-2">
- <label className="font-mono text-xs uppercase text-foreground-lighter min-w-[55px]">
- Type
- </label>
- <div>
- <span className="flex grow-0 bg-slate-300 px-2 py-0.5 rounded-md text-foreground-light">
- <span className="flex items-center gap-2 text-sm">
- <IconCode size="tiny" />
- <span>{getColumnType(type, format)}</span>
- </span>
- </span>
- </div>
- </div>
- <div className="mb-4 flex items-center gap-2">
- <label className="font-mono text-xs uppercase text-foreground-lighter min-w-[55px]">
- Format
- </label>
- <div>
- <span className="flex grow-0 bg-slate-300 px-2 py-0.5 rounded-md text-foreground-light">
- <span className="flex items-center gap-2 text-sm">
- <IconDatabase size="tiny" />
- <span>{format}</span>
- </span>
- </span>
- </div>
- </div>
- </div>
- )}
- {description !== false && (
- <div className="grid gap-2 mt-2">
- <label className="font-mono text-xs uppercase text-foreground-lighter">Description</label>
- <Description
- content={description?.toString()}
- metadata={metadata}
- onChange={onDesciptionUpdated}
- />
- </div>
- )}
- </>
- )
-}
-export default Param
diff --git a/studio/components/interfaces/Docs/ResourceContent.tsx b/studio/components/interfaces/Docs/ResourceContent.tsx
deleted file mode 100644
index 090e0c6f73a..00000000000
--- a/studio/components/interfaces/Docs/ResourceContent.tsx
+++ /dev/null
@@ -1,314 +0,0 @@
-import { useParams } from 'common'
-import { IconTable } from 'ui'
-
-import CodeSnippet from 'components/interfaces/Docs/CodeSnippet'
-import Description from 'components/interfaces/Docs/Description'
-import Param from 'components/interfaces/Docs/Param'
-import Snippets from 'components/interfaces/Docs/Snippets'
-import { useCustomDomainsQuery } from 'data/custom-domains/custom-domains-query'
-
-const ResourceContent = ({
- autoApiService,
- resourceId,
- resources,
- definitions,
- paths,
- selectedLang,
- showApiKey,
- refreshDocs,
-}: any) => {
- const { ref } = useParams()
- const { data: customDomainData } = useCustomDomainsQuery({ projectRef: ref })
- const endpoint =
- customDomainData?.customDomain?.status === 'active'
- ? `https://${customDomainData.customDomain.hostname}`
- : autoApiService.endpoint
-
- const keyToShow = !!showApiKey ? showApiKey : 'SUPABASE_KEY'
- const resourcePaths = paths[`/${resourceId}`]
- const resourceDefinition = definitions[resourceId]
- const resourceMeta = resources[resourceId]
- const description = resourceDefinition?.description || null
- const methods = Object.keys(resourcePaths).map((x) => x.toUpperCase())
- const properties = Object.entries(resourceDefinition.properties || []).map(([id, val]: any) => ({
- ...val,
- id,
- required: resourceDefinition?.required?.includes(id),
- }))
-
- if (!paths || !definitions) return null
-
- return (
- <>
- <h2 className="doc-section__table-name text-foreground mt-0 flex items-center px-6 gap-2">
- <span className="bg-slate-300 dark:bg-slate-400 p-2 rounded-lg">
- <IconTable size="small" />
- </span>
- <span className="text-2xl font-bold">{resourceId}</span>
- </h2>
-
- <div className="doc-section">
- <article className="code-column text-foreground">
- <label className="font-mono text-xs uppercase text-foreground-lighter inline-block mb-2">
- Description
- </label>
- <Description
- content={description}
- metadata={{ table: resourceId }}
- onChange={refreshDocs}
- />
- </article>
- <article className="code"></article>
- </div>
- {properties.length > 0 && (
- <div>
- {properties.map((x) => (
- <div className="doc-section py-4" key={x.id}>
- <div className="code-column text-foreground">
- <Param
- key={x.id}
- name={x.id}
- type={x.type}
- format={x.format}
- required={x.required}
- description={x.description}
- metadata={{
- table: resourceId,
- column: x.id,
- }}
- onDesciptionUpdated={refreshDocs}
- />
- </div>
- <div className="code">
- <CodeSnippet
- selectedLang={selectedLang}
- snippet={Snippets.readColumns({
- title: `Select ${x.id}`,
- resourceId,
- endpoint: endpoint,
- apiKey: keyToShow,
- columnName: x.id,
- })}
- />
- </div>
- </div>
- ))}
- </div>
- )}
- {methods.includes('GET') && (
- <>
- <h3 className="text-foreground mt-4 px-6">Read rows</h3>
- <div className="doc-section">
- <article className="code-column text-foreground">
- <p>
- To read rows in <code>{resourceId}</code>, use the <code>select</code> method.
- </p>
- <p>
- <a
- href="https://supabase.com/docs/reference/javascript/select"
- target="_blank"
- rel="noreferrer"
- >
- Learn more
- </a>
- </p>
- </article>
- <article className="code">
- <CodeSnippet
- selectedLang={selectedLang}
- snippet={Snippets.readAll(resourceId, endpoint, keyToShow)}
- />
- <CodeSnippet
- selectedLang={selectedLang}
- snippet={Snippets.readColumns({
- resourceId,
- endpoint: endpoint,
- apiKey: keyToShow,
- })}
- />
- <CodeSnippet
- selectedLang={selectedLang}
- snippet={Snippets.readForeignTables(resourceId, endpoint, keyToShow)}
- />
- <CodeSnippet
- selectedLang={selectedLang}
- snippet={Snippets.readRange(resourceId, endpoint, keyToShow)}
- />
- </article>
- </div>
- <div className="doc-section">
- <article className="code-column text-foreground">
- <h4 className="mt-0 text-white">Filtering</h4>
- <p>Supabase provides a wide range of filters.</p>
- <p>
- <a
- href="https://supabase.com/docs/reference/javascript/using-filters"
- target="_blank"
- rel="noreferrer"
- >
- Learn more
- </a>
- </p>
- </article>
- <article className="code">
- <CodeSnippet
- selectedLang={selectedLang}
- snippet={Snippets.readFilters(resourceId, endpoint, keyToShow)}
- />
- </article>
- </div>
- </>
- )}
- {methods.includes('POST') && (
- <>
- <h3 className="text-foreground mt-4 px-6">Insert rows</h3>
- <div className="doc-section">
- <article className="code-column text-foreground">
- <p>
- <code>insert</code> lets you insert into your tables. You can also insert in bulk
- and do UPSERT.
- </p>
- <p>
- <code>insert</code> will also return the replaced values for UPSERT.
- </p>
- <p>
- <a
- href="https://supabase.com/docs/reference/javascript/insert"
- target="_blank"
- rel="noreferrer"
- >
- Learn more
- </a>
- </p>
- </article>
- <article className="code">
- <CodeSnippet
- selectedLang={selectedLang}
- snippet={Snippets.insertSingle(resourceId, endpoint, keyToShow)}
- />
- <CodeSnippet
- selectedLang={selectedLang}
- snippet={Snippets.insertMany(resourceId, endpoint, keyToShow)}
- />
- <CodeSnippet
- selectedLang={selectedLang}
- snippet={Snippets.upsert(resourceId, endpoint, keyToShow)}
- />
- </article>
- </div>
- </>
- )}
- {methods.includes('PATCH') && (
- <>
- <h3 className="text-foreground mt-4 px-6">Update rows</h3>
- <div className="doc-section">
- <article className="code-column text-foreground">
- <p>
- <code>update</code> lets you update rows. <code>update</code> will match all rows by
- default. You can update specific rows using horizontal filters, e.g. <code>eq</code>
- , <code>lt</code>, and <code>is</code>.
- </p>
- <p>
- <code>update</code> will also return the replaced values for UPDATE.
- </p>
- <p>
- <a
- href="https://supabase.com/docs/reference/javascript/update"
- target="_blank"
- rel="noreferrer"
- >
- Learn more
- </a>
- </p>
- </article>
- <article className="code">
- <CodeSnippet
- selectedLang={selectedLang}
- snippet={Snippets.update(resourceId, endpoint, keyToShow)}
- />
- </article>
- </div>
- </>
- )}
- {methods.includes('DELETE') && (
- <>
- <h3 className="text-foreground mt-4 px-6">Delete rows</h3>
- <div className="doc-section">
- <article className="code-column text-foreground">
- <p>
- <code>delete</code> lets you delete rows. <code>delete</code> will match all rows by
- default, so remember to specify your filters!
- </p>
- <p>
- <a
- href="https://supabase.com/docs/reference/javascript/delete"
- target="_blank"
- rel="noreferrer"
- >
- Learn more
- </a>
- </p>
- </article>
- <article className="code">
- <CodeSnippet
- selectedLang={selectedLang}
- snippet={Snippets.delete(resourceId, endpoint, keyToShow)}
- />
- </article>
- </div>
- </>
- )}
- {(methods.includes('DELETE') || methods.includes('POST') || methods.includes('PATCH')) && (
- <>
- <h3 className="text-foreground mt-4 px-6">Subscribe to changes</h3>
- <div className="doc-section">
- <article className="code-column text-foreground">
- <p>
- Supabase provides realtime functionality and broadcasts database changes to
- authorized users depending on Row Level Security (RLS) policies.
- </p>
- <p>
- <a
- href="https://supabase.com/docs/reference/javascript/subscribe"
- target="_blank"
- rel="noreferrer"
- >
- Learn more
- </a>
- </p>
- </article>
- <article className="code">
- <CodeSnippet
- selectedLang={selectedLang}
- snippet={Snippets.subscribeAll(resourceMeta.camelCase, resourceId)}
- />
- <CodeSnippet
- selectedLang={selectedLang}
- snippet={Snippets.subscribeInserts(resourceMeta.camelCase, resourceId)}
- />
- <CodeSnippet
- selectedLang={selectedLang}
- snippet={Snippets.subscribeUpdates(resourceMeta.camelCase, resourceId)}
- />
- <CodeSnippet
- selectedLang={selectedLang}
- snippet={Snippets.subscribeDeletes(resourceMeta.camelCase, resourceId)}
- />
- <CodeSnippet
- selectedLang={selectedLang}
- snippet={Snippets.subscribeEq(
- resourceMeta.camelCase,
- resourceId,
- 'column_name',
- 'someValue'
- )}
- />
- </article>
- </div>
- </>
- )}
- </>
- )
-}
-
-export default ResourceContent
diff --git a/studio/components/interfaces/Docs/RpcContent.tsx b/studio/components/interfaces/Docs/RpcContent.tsx
deleted file mode 100644
index 73c541a015d..00000000000
--- a/studio/components/interfaces/Docs/RpcContent.tsx
+++ /dev/null
@@ -1,88 +0,0 @@
-import CodeSnippet from 'components/interfaces/Docs/CodeSnippet'
-import Description from 'components/interfaces/Docs/Description'
-import Param from 'components/interfaces/Docs/Param'
-import Snippets from 'components/interfaces/Docs/Snippets'
-
-/**
- * TODO: need to support rpc with the same name and different params type
- */
-const RpcContent = ({
- autoApiService,
- rpcId,
- rpcs,
- paths,
- selectedLang,
- refreshDocs,
- showApiKey,
-}: any) => {
- const meta = rpcs[rpcId]
- const pathKey = `/rpc/${rpcId}`
- const path = paths && pathKey in paths ? paths[pathKey] : undefined
- const keyToShow = !!showApiKey ? showApiKey : 'SUPABASE_KEY'
-
- if (!path) return null
-
- const {
- post: { parameters, summary },
- } = path
- const rpcParamsObject =
- parameters && parameters[0] && parameters[0].schema && parameters[0].schema.properties
- ? parameters[0].schema.properties
- : {}
- const rpcParams = Object.entries(rpcParamsObject)
- .map(([k, v]: any) => ({ name: k, ...v }))
- .filter((x) => !!x.name)
- const paramList = rpcParams.map((x) => x.type).join(', ')
-
- return (
- <>
- <h2 className="text-foreground mt-0">
- <span className="px-6 text-2xl">{meta.id}</span>
- </h2>
-
- <div className="doc-section">
- <article className="code-column text-foreground">
- <label className="font-mono text-xs uppercase text-foreground-lighter">Description</label>
- <Description content={summary} metadata={{ rpc: rpcId }} onChange={refreshDocs} />
- </article>
- <article className="code">
- <CodeSnippet
- selectedLang={selectedLang}
- snippet={Snippets.rpcSingle({
- rpcName: rpcId,
- // @ts-ignore
- rpcCamelCase: meta.camelCase,
- rpcParams: rpcParams,
- apiKey: keyToShow,
- endpoint: autoApiService.endpoint,
- })}
- />
- </article>
- </div>
- {rpcParams.length > 0 && (
- <div>
- <h3 className="text-foreground mt-0 px-6 capitalize">Function Arguments</h3>
- {rpcParams.map((x, i) => {
- return (
- <div key={i} className="doc-section">
- <article className="code-column text-foreground">
- <Param
- key={x.name}
- name={x.name}
- type={x.type}
- format={x.format}
- required={true}
- description={false}
- />
- </article>
- <article className="code"></article>
- </div>
- )
- })}
- </div>
- )}
- </>
- )
-}
-
-export default RpcContent
diff --git a/studio/components/interfaces/Docs/Snippets.ts b/studio/components/interfaces/Docs/Snippets.ts
deleted file mode 100644
index f6f60556c19..00000000000
--- a/studio/components/interfaces/Docs/Snippets.ts
+++ /dev/null
@@ -1,763 +0,0 @@
-const snippets = {
- endpoint: (endpoint: string) => ({
- title: 'API URL',
- bash: {
- language: 'bash',
- code: `${endpoint}`,
- },
- js: {
- language: 'bash',
- code: `${endpoint}`,
- },
- }),
- install: () => ({
- title: 'Install',
- bash: null,
- js: {
- language: 'bash',
- code: `npm install --save @supabase/supabase-js`,
- },
- }),
- init: (endpoint: string) => ({
- title: 'Initializing',
- bash: {
- language: 'bash',
- code: `# No client library required for Bash.`,
- },
- js: {
- language: 'js',
- code: `
-import { createClient } from '@supabase/supabase-js'
-
-const supabaseUrl = '${endpoint}'
-const supabaseKey = process.env.SUPABASE_KEY
-const supabase = createClient(supabaseUrl, supabaseKey)`,
- },
- python: {
- language: 'python',
- code: `
-import os
-from supabase import create_client, Client
-
-url: str = '${endpoint}'
-key: str = os.environ.get("SUPABASE_KEY")
-supabase: Client = create_client(url, key)
-`,
- },
- dart: {
- language: 'dart',
- code: `
-const supabaseUrl = '${endpoint}';
-const supabaseKey = String.fromEnvironment('SUPABASE_KEY');
-
-Future<void> main() async {
- await Supabase.initialize(url: supabaseUrl, anonKey: supabaseKey);
- runApp(MyApp());
-}`,
- },
- }),
- authKey: (title: string, varName: string, apikey: string) => ({
- title: `${title}`,
- bash: {
- language: 'bash',
- code: `${apikey}`,
- },
- js: {
- language: 'js',
- code: `const ${varName} = '${apikey}'`,
- },
- }),
- authKeyExample: (
- defaultApiKey: string,
- endpoint: string,
- { keyName, showBearer = true }: { keyName?: string; showBearer?: boolean }
- ) => ({
- title: 'Example usage',
- bash: {
- language: 'bash',
- code: `
-curl '${endpoint}/rest/v1/' \\
--H "apikey: ${defaultApiKey}" ${
- showBearer
- ? `\\
--H "Authorization: Bearer ${defaultApiKey}"`
- : ''
- }
-`,
- },
- js: {
- language: 'js',
- code: `
-const SUPABASE_URL = "${endpoint}"
-
-const supabase = createClient(SUPABASE_URL, process.env.${keyName || 'SUPABASE_KEY'});
-`,
- },
- }),
- rpcSingle: ({
- rpcName,
- rpcParams,
- endpoint,
- apiKey,
- showBearer = true,
- }: {
- rpcName: string
- rpcParams: any[]
- endpoint: string
- apiKey: string
- showBearer: boolean
- }) => {
- let rpcList = rpcParams.map((x) => `"${x.name}": "value"`).join(', ')
- let noParams = !rpcParams.length
- let bashParams = noParams ? '' : `\n-d '{ ${rpcList} }' \\`
- let jsParams = noParams
- ? ''
- : `, {${
- rpcParams.length
- ? rpcParams
- .map((x) => `\n ${x.name}`)
- .join(`, `)
- .concat('\n ')
- : ''
- }}`
- return {
- title: 'Invoke function ',
- bash: {
- language: 'bash',
- code: `
-curl -X POST '${endpoint}/rest/v1/rpc/${rpcName}' \\${bashParams}
--H "Content-Type: application/json" \\
--H "apikey: ${apiKey}" ${
- showBearer
- ? `\\
--H "Authorization: Bearer ${apiKey}"`
- : ''
- }
-`,
- },
- js: {
- language: 'js',
- code: `
-let { data, error } = await supabase
- .rpc('${rpcName}'${jsParams})
-
-if (error) console.error(error)
-else console.log(data)
-`,
- },
- }
- },
- subscribeAll: (listenerName: string, resourceId: string) => ({
- title: 'Subscribe to all events',
- bash: {
- language: 'bash',
- code: `# Realtime streams are only supported by our client libraries`,
- },
- js: {
- language: 'js',
- code: `
-const ${listenerName} = supabase.channel('custom-all-channel')
- .on(
- 'postgres_changes',
- { event: '*', schema: 'public', table: '${resourceId}' },
- (payload) => {
- console.log('Change received!', payload)
- }
- )
- .subscribe()`,
- },
- }),
- subscribeInserts: (listenerName: string, resourceId: string) => ({
- title: 'Subscribe to inserts',
- bash: {
- language: 'bash',
- code: `# Realtime streams are only supported by our client libraries`,
- },
- js: {
- language: 'js',
- code: `
-const ${listenerName} = supabase.channel('custom-insert-channel')
- .on(
- 'postgres_changes',
- { event: 'INSERT', schema: 'public', table: '${resourceId}' },
- (payload) => {
- console.log('Change received!', payload)
- }
- )
- .subscribe()`,
- },
- }),
- subscribeUpdates: (listenerName: string, resourceId: string) => ({
- title: 'Subscribe to updates',
- bash: {
- language: 'bash',
- code: `# Realtime streams are only supported by our client libraries`,
- },
- js: {
- language: 'js',
- code: `
-const ${listenerName} = supabase.channel('custom-update-channel')
- .on(
- 'postgres_changes',
- { event: 'UPDATE', schema: 'public', table: '${resourceId}' },
- (payload) => {
- console.log('Change received!', payload)
- }
- )
- .subscribe()`,
- },
- }),
- subscribeDeletes: (listenerName: string, resourceId: string) => ({
- title: 'Subscribe to deletes',
- bash: {
- language: 'bash',
- code: `# Realtime streams are only supported by our client libraries`,
- },
- js: {
- language: 'js',
- code: `
-const ${listenerName} = supabase.channel('custom-delete-channel')
- .on(
- 'postgres_changes',
- { event: 'DELETE', schema: 'public', table: '${resourceId}' },
- (payload) => {
- console.log('Change received!', payload)
- }
- )
- .subscribe()`,
- },
- }),
- subscribeEq: (listenerName: string, resourceId: string, columnName: string, value: string) => ({
- title: 'Subscribe to specific rows',
- bash: {
- language: 'bash',
- code: `# Realtime streams are only supported by our client libraries`,
- },
- js: {
- language: 'js',
- code: `
-const ${listenerName} = supabase.channel('custom-filter-channel')
- .on(
- 'postgres_changes',
- { event: '*', schema: 'public', table: '${resourceId}', filter: '${columnName}=eq.${value}' },
- (payload) => {
- console.log('Change received!', payload)
- }
- )
- .subscribe()`,
- },
- }),
- readAll: (resourceId: string, endpoint: string, apiKey: string) => ({
- title: 'Read all rows',
- bash: {
- language: 'bash',
- code: `
-curl '${endpoint}/rest/v1/${resourceId}?select=*' \\
--H "apikey: ${apiKey}" \\
--H "Authorization: Bearer ${apiKey}"
-`,
- },
- js: {
- language: 'js',
- code: `
-let { data: ${resourceId}, error } = await supabase
- .from('${resourceId}')
- .select('*')
-`,
- },
- }),
- readColumns: ({
- title = 'Read specific columns',
- resourceId,
- endpoint,
- apiKey,
- columnName = 'some_column,other_column',
- }: {
- title?: string
- resourceId: string
- endpoint: string
- apiKey: string
- columnName?: string
- }) => ({
- title,
- bash: {
- language: 'bash',
- code: `
-curl '${endpoint}/rest/v1/${resourceId}?select=${columnName}' \\
--H "apikey: ${apiKey}" \\
--H "Authorization: Bearer ${apiKey}"
-`,
- },
- js: {
- language: 'js',
- code: `
-let { data: ${resourceId}, error } = await supabase
- .from('${resourceId}')
- .select('${columnName}')
-`,
- },
- }),
- readForeignTables: (resourceId: string, endpoint: string, apiKey: string) => ({
- title: 'Read foreign tables',
- bash: {
- language: 'bash',
- code: `
-curl '${endpoint}/rest/v1/${resourceId}?select=some_column,other_table(foreign_key)' \\
--H "apikey: ${apiKey}" \\
--H "Authorization: Bearer ${apiKey}"
-`,
- },
- js: {
- language: 'js',
- code: `
-let { data: ${resourceId}, error } = await supabase
- .from('${resourceId}')
- .select(\`
- some_column,
- other_table (
- foreign_key
- )
- \`)
-`,
- },
- }),
- readRange: (resourceId: string, endpoint: string, apiKey: string) => ({
- title: 'With pagination',
- bash: {
- language: 'bash',
- code: `
-curl '${endpoint}/rest/v1/${resourceId}?select=*' \\
--H "apikey: ${apiKey}" \\
--H "Authorization: Bearer ${apiKey}" \\
--H "Range: 0-9"
-`,
- },
- js: {
- language: 'js',
- code: `
-let { data: ${resourceId}, error } = await supabase
- .from('${resourceId}')
- .select('*')
- .range(0, 9)
-`,
- },
- }),
- readFilters: (resourceId: string, endpoint: string, apiKey: string) => ({
- title: 'With filtering',
- bash: {
- language: 'bash',
- code: `
-curl '${endpoint}/rest/v1/${resourceId}?id=eq.1&select=*' \\
--H "apikey: ${apiKey}" \\
--H "Authorization: Bearer ${apiKey}" \\
--H "Range: 0-9"
-`,
- },
- js: {
- language: 'js',
- code: `
-let { data: ${resourceId}, error } = await supabase
- .from('${resourceId}')
- .select("*")
-
- // Filters
- .eq('column', 'Equal to')
- .gt('column', 'Greater than')
- .lt('column', 'Less than')
- .gte('column', 'Greater than or equal to')
- .lte('column', 'Less than or equal to')
- .like('column', '%CaseSensitive%')
- .ilike('column', '%CaseInsensitive%')
- .is('column', null)
- .in('column', ['Array', 'Values'])
- .neq('column', 'Not equal to')
-
- // Arrays
- .cs('array_column', ['array', 'contains'])
- .cd('array_column', ['contained', 'by'])
-
-`,
- },
- }),
- insertSingle: (resourceId: string, endpoint: string, apiKey: string) => ({
- title: 'Insert a row',
- bash: {
- language: 'bash',
- code: `
-curl -X POST '${endpoint}/rest/v1/${resourceId}' \\
--H "apikey: ${apiKey}" \\
--H "Authorization: Bearer ${apiKey}" \\
--H "Content-Type: application/json" \\
--H "Prefer: return=minimal" \\
--d '{ "some_column": "someValue", "other_column": "otherValue" }'
-`,
- },
- js: {
- language: 'js',
- code: `
-const { data, error } = await supabase
- .from('${resourceId}')
- .insert([
- { some_column: 'someValue', other_column: 'otherValue' },
- ])
- .select()
-`,
- },
- }),
- insertMany: (resourceId: string, endpoint: string, apiKey: string) => ({
- title: 'Insert many rows',
- bash: {
- language: 'bash',
- code: `
-curl -X POST '${endpoint}/rest/v1/${resourceId}' \\
--H "apikey: ${apiKey}" \\
--H "Authorization: Bearer ${apiKey}" \\
--H "Content-Type: application/json" \\
--d '[{ "some_column": "someValue" }, { "other_column": "otherValue" }]'
-`,
- },
- js: {
- language: 'js',
- code: `
-const { data, error } = await supabase
- .from('${resourceId}')
- .insert([
- { some_column: 'someValue' },
- { some_column: 'otherValue' },
- ])
- .select()
-`,
- },
- }),
- upsert: (resourceId: string, endpoint: string, apiKey: string) => ({
- title: 'Upsert matching rows',
- bash: {
- language: 'bash',
- code: `
-curl -X POST '${endpoint}/rest/v1/${resourceId}' \\
--H "apikey: ${apiKey}" \\
--H "Authorization: Bearer ${apiKey}" \\
--H "Content-Type: application/json" \\
--H "Prefer: resolution=merge-duplicates" \\
--d '{ "some_column": "someValue", "other_column": "otherValue" }'
-`,
- },
- js: {
- language: 'js',
- code: `
-const { data, error } = await supabase
- .from('${resourceId}')
- .upsert({ some_column: 'someValue' })
- .select()
-`,
- },
- }),
- update: (resourceId: string, endpoint: string, apiKey: string) => ({
- title: 'Update matching rows',
- bash: {
- language: 'bash',
- code: `
-curl -X PATCH '${endpoint}/rest/v1/${resourceId}?some_column=eq.someValue' \\
--H "apikey: ${apiKey}" \\
--H "Authorization: Bearer ${apiKey}" \\
--H "Content-Type: application/json" \\
--H "Prefer: return=minimal" \\
--d '{ "other_column": "otherValue" }'
-`,
- },
- js: {
- language: 'js',
- code: `
-const { data, error } = await supabase
- .from('${resourceId}')
- .update({ other_column: 'otherValue' })
- .eq('some_column', 'someValue')
- .select()
-`,
- },
- }),
- delete: (resourceId: string, endpoint: string, apiKey: string) => ({
- title: 'Delete matching rows',
- bash: {
- language: 'bash',
- code: `
-curl -X DELETE '${endpoint}/rest/v1/${resourceId}?some_column=eq.someValue' \\
--H "apikey: ${apiKey}" \\
--H "Authorization: Bearer ${apiKey}"
-`,
- },
- js: {
- language: 'js',
- code: `
-const { error } = await supabase
- .from('${resourceId}')
- .delete()
- .eq('some_column', 'someValue')
-`,
- },
- }),
- authSignup: (endpoint: string, apiKey: string, randomPassword: string) => ({
- title: 'User signup',
- bash: {
- language: 'bash',
- code: `
-curl -X POST '${endpoint}/auth/v1/signup' \\
--H "apikey: ${apiKey}" \\
--H "Content-Type: application/json" \\
--d '{
- "email": "[email protected]",
- "password": "${randomPassword}"
-}'
-`,
- },
- js: {
- language: 'js',
- code: `
-let { data, error } = await supabase.auth.signUp({
- email: '[email protected]',
- password: '${randomPassword}'
-})
-`,
- },
- }),
- authLogin: (endpoint: string, apiKey: string, randomPassword: string) => ({
- title: 'User login',
- bash: {
- language: 'bash',
- code: `
-curl -X POST '${endpoint}/auth/v1/token?grant_type=password' \\
--H "apikey: ${apiKey}" \\
--H "Content-Type: application/json" \\
--d '{
- "email": "[email protected]",
- "password": "${randomPassword}"
-}'
-`,
- },
- js: {
- language: 'js',
- code: `
-let { data, error } = await supabase.auth.signInWithPassword({
- email: '[email protected]',
- password: '${randomPassword}'
-})
-`,
- },
- }),
- authMagicLink: (endpoint: string, apiKey: string) => ({
- title: 'User login',
- bash: {
- language: 'bash',
- code: `
-curl -X POST '${endpoint}/auth/v1/magiclink' \\
--H "apikey: ${apiKey}" \\
--H "Content-Type: application/json" \\
--d '{
- "email": "[email protected]"
-}'
-`,
- },
- js: {
- language: 'js',
- code: `
-let { data, error } = await supabase.auth.signInWithOtp({
-})
-`,
- },
- }),
- authPhoneSignUp: (endpoint: string, apiKey: string) => ({
- title: 'Phone Signup',
- bash: {
- language: 'bash',
- code: `
-curl -X POST '${endpoint}/auth/v1/signup' \\
--H "apikey: ${apiKey}" \\
--H "Content-Type: application/json" \\
--d '{
- "phone": "+13334445555",
- "password": "some-password"
-}'
-`,
- },
- js: {
- language: 'js',
- code: `
-let { data, error } = await supabase.auth.signUp({
- phone: '+13334445555',
- password: 'some-password'
-})
-`,
- },
- }),
- authMobileOTPLogin: (endpoint: string, apiKey: string) => ({
- title: 'Phone Login',
- bash: {
- language: 'bash',
- code: `
-curl -X POST '${endpoint}/auth/v1/otp' \\
--H "apikey: ${apiKey}" \\
--H "Content-Type: application/json" \\
--d '{
- "phone": "+13334445555"
-}'
-`,
- },
- js: {
- language: 'js',
- code: `
-let { data, error } = await supabase.auth.signInWithOtp({
- phone: '+13334445555'
-})
-`,
- },
- }),
- authMobileOTPVerify: (endpoint: string, apiKey: string) => ({
- title: 'Verify Pin',
- bash: {
- language: 'bash',
- code: `
-curl -X POST '${endpoint}/auth/v1/verify' \\
--H "apikey: ${apiKey}" \\
--H "Content-Type: application/json" \\
--d '{
- "type": "sms",
- "phone": "+13334445555",
- "token": "123456"
-}'
-`,
- },
- js: {
- language: 'js',
- code: `
-let { data, error } = await supabase.auth.verifyOtp({
- phone: '+13334445555',
- token: '123456',
- type: 'sms'
-})
-`,
- },
- }),
- authInvite: (endpoint: string, apiKey: string) => ({
- title: 'Invite User',
- bash: {
- language: 'bash',
- code: `
-curl -X POST '${endpoint}/auth/v1/invite' \\
--H "apikey: ${apiKey}" \\
--H "Authorization: Bearer ${apiKey}" \\
--H "Content-Type: application/json" \\
--d '{
- "email": "[email protected]"
-}'
-`,
- },
- js: {
- language: 'js',
- code: `
-let { data, error } = await supabase.auth.api.inviteUserByEmail('[email protected]')
-`,
- },
- }),
- authThirdPartyLogin: () => ({
- title: 'Third Party Login',
- bash: {
- language: 'bash',
- code: ``,
- },
- js: {
- language: 'js',
- code: `
-let { data, error } = await supabase.auth.signInWithOAuth({
- provider: 'github'
-})
-`,
- },
- }),
- authUser: (endpoint: string, apiKey: string) => ({
- title: 'Get User',
- bash: {
- language: 'bash',
- code: `
-curl -X GET '${endpoint}/auth/v1/user' \\
--H "apikey: ${apiKey}" \\
--H "Authorization: Bearer USER_TOKEN"
-`,
- },
- js: {
- language: 'js',
- code: `
-const { data: { user } } = await supabase.auth.getUser()
-`,
- },
- }),
- authRecover: (endpoint: string, apiKey: string) => ({
- title: 'Password Recovery',
- bash: {
- language: 'bash',
- code: `
- curl -X POST '${endpoint}/auth/v1/recover' \\
--H "apikey: ${apiKey}" \\
--H "Content-Type: application/json" \\
--d '{
- "email": "[email protected]"
-}'
-`,
- },
- js: {
- language: 'js',
- code: `
-let { data, error } = await supabase.auth.resetPasswordForEmail(email)
-`,
- },
- }),
- authUpdate: (endpoint: string, apiKey: string) => ({
- title: 'Update User',
- bash: {
- language: 'bash',
- code: `
- curl -X PUT '${endpoint}/auth/v1/user' \\
--H "apikey: ${apiKey}" \\
--H "Authorization: Bearer <USERS-ACCESS-TOKEN>" \\
--H "Content-Type: application/json" \\
--d '{
- "email": "[email protected]",
- "password": "new-password",
- "data": {
- "key": "value"
- }
-}'
-`,
- },
- js: {
- language: 'js',
- code: `
-const { data, error } = await supabase.auth.updateUser({
- email: "[email protected]",
- password: "new-password",
- data: { hello: 'world' }
-})
-`,
- },
- }),
- authLogout: (endpoint: string, apiKey: string) => ({
- title: 'User logout',
- bash: {
- language: 'bash',
- code: `
-curl -X POST '${endpoint}/auth/v1/logout' \\
--H "apikey: ${apiKey}" \\
--H "Content-Type: application/json" \\
--H "Authorization: Bearer USER_TOKEN"
-`,
- },
- js: {
- language: 'js',
- code: `
-let { error } = await supabase.auth.signOut()
-`,
- },
- }),
-}
-
-export default snippets
diff --git a/studio/components/interfaces/Docs/index.ts b/studio/components/interfaces/Docs/index.ts
deleted file mode 100644
index 8eaff962f84..00000000000
--- a/studio/components/interfaces/Docs/index.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import GeneralContent from './GeneralContent'
-import ResourceContent from './ResourceContent'
-import RpcContent from './RpcContent'
-
-export { GeneralContent, ResourceContent, RpcContent }
diff --git a/studio/components/interfaces/Home/NewProjectPanel/APIKeys.tsx b/studio/components/interfaces/Home/NewProjectPanel/APIKeys.tsx
index 0f56b1b948d..657108ab6f4 100644
--- a/studio/components/interfaces/Home/NewProjectPanel/APIKeys.tsx
+++ b/studio/components/interfaces/Home/NewProjectPanel/APIKeys.tsx
@@ -5,13 +5,29 @@ import { useState } from 'react'
import { IconAlertCircle, IconLoader, Input } from 'ui'
import { useParams } from 'common/hooks'
-import Snippets from 'components/interfaces/Docs/Snippets'
import SimpleCodeBlock from 'components/to-be-cleaned/SimpleCodeBlock'
import Panel from 'components/ui/Panel'
import { useJwtSecretUpdatingStatusQuery } from 'data/config/jwt-secret-updating-status-query'
import { useProjectApiQuery } from 'data/config/project-api-query'
import { useCheckPermissions } from 'hooks'
+const generateInitSnippet = (endpoint: string) => ({
+ js: `
+import { createClient } from '@supabase/supabase-js'
+
+const supabaseUrl = '${endpoint}'
+const supabaseKey = process.env.SUPABASE_KEY
+const supabase = createClient(supabaseUrl, supabaseKey)`,
+ dart: `
+const supabaseUrl = '${endpoint}';
+const supabaseKey = String.fromEnvironment('SUPABASE_KEY');
+
+Future<void> main() async {
+ await Supabase.initialize(url: supabaseUrl, anonKey: supabaseKey);
+ runApp(MyApp());
+}`,
+})
+
const APIKeys = () => {
const { ref: projectRef } = useParams()
@@ -50,9 +66,8 @@ const APIKeys = () => {
const apiUrl = `${apiService?.protocol ?? 'https'}://${apiService?.endpoint ?? '-'}`
const anonKey = apiKeys.find((key) => key.tags === 'anon')
- const clientInitSnippet: any = Snippets.init(apiUrl)
- const selectedLanguageSnippet =
- clientInitSnippet[selectedLanguage.key]?.code ?? 'No snippet available'
+ const clientInitSnippet: any = generateInitSnippet(apiUrl)
+ const selectedLanguageSnippet = clientInitSnippet[selectedLanguage.key] ?? 'No snippet available'
return (
<Panel
diff --git a/studio/components/interfaces/ProjectAPIDocs/Content/Entity.tsx b/studio/components/interfaces/ProjectAPIDocs/Content/Entity.tsx
index 3531a65046d..c2881822275 100644
--- a/studio/components/interfaces/ProjectAPIDocs/Content/Entity.tsx
+++ b/studio/components/interfaces/ProjectAPIDocs/Content/Entity.tsx
@@ -1,4 +1,5 @@
import { useParams } from 'common'
+import { useEffect } from 'react'
import Table from 'components/to-be-cleaned/Table'
import { useProjectJsonSchemaQuery } from 'data/docs/project-json-schema-query'
@@ -33,7 +34,7 @@ const Entity = ({ language, apikey = '', endpoint = '' }: ContentProps) => {
const snap = useAppStateSnapshot()
const resource = snap.activeDocsSection[1]
- const { data: jsonSchema } = useProjectJsonSchemaQuery({ projectRef: ref })
+ const { data: jsonSchema, refetch } = useProjectJsonSchemaQuery({ projectRef: ref })
const definition = jsonSchema?.definitions?.[resource]
const columns =
definition !== undefined
@@ -44,6 +45,10 @@ const Entity = ({ language, apikey = '', endpoint = '' }: ContentProps) => {
}))
: []
+ useEffect(() => {
+ if (resource !== undefined) refetch()
+ }, [resource])
+
if (resource === undefined) return null
return (
diff --git a/studio/components/interfaces/ProjectAPIDocs/Content/RPC.tsx b/studio/components/interfaces/ProjectAPIDocs/Content/RPC.tsx
index e1432cec2b6..a3cfb857d85 100644
--- a/studio/components/interfaces/ProjectAPIDocs/Content/RPC.tsx
+++ b/studio/components/interfaces/ProjectAPIDocs/Content/RPC.tsx
@@ -1,4 +1,5 @@
import { useParams } from 'common'
+import { useEffect } from 'react'
import { Badge } from 'ui'
import Table from 'components/to-be-cleaned/Table'
@@ -13,8 +14,10 @@ const RPC = ({ language }: ContentProps) => {
const { ref } = useParams()
const snap = useAppStateSnapshot()
- const { data: jsonSchema } = useProjectJsonSchemaQuery({ projectRef: ref })
- const { data } = useOpenAPISpecQuery({ projectRef: ref })
+ const { data: jsonSchema, refetch: refetchJsonSchema } = useProjectJsonSchemaQuery({
+ projectRef: ref,
+ })
+ const { data, refetch: refetchOpenAPISpec } = useOpenAPISpecQuery({ projectRef: ref })
const functions = data?.functions ?? []
const rpcName = snap.activeDocsSection[1]
@@ -24,6 +27,13 @@ const RPC = ({ language }: ContentProps) => {
const summary = rpcJsonSchema?.post.summary
const parameters = rpc?.get.parameters ?? []
+ useEffect(() => {
+ if (rpcName !== undefined) {
+ refetchJsonSchema()
+ refetchOpenAPISpec()
+ }
+ }, [rpcName])
+
if (rpc === undefined) return null
return (
diff --git a/studio/components/interfaces/SQLEditor/SQLTemplates/SQLCard.tsx b/studio/components/interfaces/SQLEditor/SQLTemplates/SQLCard.tsx
index a6c3ca9162f..a82ee41760a 100644
--- a/studio/components/interfaces/SQLEditor/SQLTemplates/SQLCard.tsx
+++ b/studio/components/interfaces/SQLEditor/SQLTemplates/SQLCard.tsx
@@ -20,7 +20,7 @@ const SQLCard = ({ title, description, sql, onClick }: SQLCardProps) => {
title={title}
loading={loading}
onClick={() => handleOnClick()}
- footer={<span className="text-foreground-light text-sm">{description}</span>}
+ description={description}
/>
)
}
diff --git a/studio/components/interfaces/TableGridEditor/APIDocumentationPanel.tsx b/studio/components/interfaces/TableGridEditor/APIDocumentationPanel.tsx
deleted file mode 100644
index 940e58d83a5..00000000000
--- a/studio/components/interfaces/TableGridEditor/APIDocumentationPanel.tsx
+++ /dev/null
@@ -1,147 +0,0 @@
-import { useState } from 'react'
-
-import { useParams } from 'common/hooks'
-import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
-import { useProjectApiQuery } from 'data/config/project-api-query'
-import { useProjectJsonSchemaQuery } from 'data/docs/project-json-schema-query'
-import { useTableQuery } from 'data/tables/table-query'
-import { snakeToCamel } from 'lib/helpers'
-import { IconBookOpen, SidePanel } from 'ui'
-import { ResourceContent } from '../Docs'
-import GeneratingTypes from '../Docs/GeneratingTypes'
-import LangSelector from '../Docs/LangSelector'
-import ActionBar from './SidePanelEditor/ActionBar'
-
-export interface APIDocumentationPanelProps {
- visible: boolean
- onClose: () => void
-}
-
-const APIDocumentationPanel = ({ visible, onClose }: APIDocumentationPanelProps) => {
- const { project } = useProjectContext()
- const { ref, page, id: _id } = useParams()
- const id = _id ? Number(_id) : undefined
-
- const { data: table } = useTableQuery({
- projectRef: project?.ref,
- connectionString: project?.connectionString,
- id,
- })
-
- const {
- data: jsonSchema,
- error: jsonSchemaError,
- isError: isErrorJSONSchema,
- isSuccess: isSuccessJSONSchema,
- 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 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 Docs--inner-wrapper">
- {isErrorJSONSchema && (
- <div className="p-6 mx-auto text-center sm:w-full md:w-3/4">
- <div className="text-foreground-light">
- <p>Error connecting to API</p>
- <p>{`${jsonSchemaError}`}</p>
- </div>
- </div>
- )}
- {isSuccessJSONSchema && (
- <>
- {jsonSchema ? (
- <>
- <div className="sticky top-0 z-10">
- <LangSelector
- selectedLang={selectedLang}
- setSelectedLang={setSelectedLang}
- showApiKey={showApiKey}
- setShowApiKey={setShowApiKey}
- apiKey={anonKey}
- autoApiService={autoApiService}
- />
- </div>
-
- {jsonSchema?.definitions && (
- <ResourceContent
- autoApiService={autoApiService}
- selectedLang={selectedLang}
- resourceId={table?.name}
- resources={resources}
- definitions={jsonSchema.definitions}
- paths={jsonSchema.paths}
- showApiKey={showApiKey.key}
- refreshDocs={async () => await refetch()}
- />
- )}
- <div className="mt-8">
- <GeneratingTypes selectedLang={selectedLang} />
- </div>
- </>
- ) : (
- <div className="p-6 mx-auto text-center sm:w-full md:w-3/4">
- <h3 className="text-lg">Building docs ...</h3>
- </div>
- )}
- </>
- )}
- </div>
- </SidePanel>
- )
-}
-
-export default APIDocumentationPanel
diff --git a/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsx b/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsx
index 366343a7e91..a306c1de5b2 100644
--- a/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsx
+++ b/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsx
@@ -11,14 +11,13 @@ import { rlsAcknowledgedKey } from 'components/grid/constants'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import ConfirmationModal from 'components/ui/ConfirmationModal'
import { useCheckPermissions, useStore } from 'hooks'
+import APIDocsButton from 'components/ui/APIDocsButton'
export interface GridHeaderActionsProps {
table: PostgresTable
- openAPIDocsPanel: () => void
- refreshDocs: () => void
}
-const GridHeaderActions = ({ table, openAPIDocsPanel, refreshDocs }: GridHeaderActionsProps) => {
+const GridHeaderActions = ({ table }: GridHeaderActionsProps) => {
const { ref } = useParams()
const { meta, ui } = useStore()
const { project } = useProjectContext()
@@ -63,24 +62,6 @@ const GridHeaderActions = ({ table, openAPIDocsPanel, refreshDocs }: GridHeaderA
return () => rlsAcknowledgedChannel.current.close()
}, [rlsKey])
- function openAPIDocs() {
- openAPIDocsPanel()
- refreshDocs()
- }
-
- const RenderAPIPreviewToggle = () => {
- return (
- <Button
- size="tiny"
- type="default"
- icon={<IconCode size={14} strokeWidth={2} />}
- onClick={openAPIDocs}
- >
- API
- </Button>
- )
- }
-
const toggleRealtime = async () => {
if (!realtimePublication) return console.error('Unable to find realtime publication')
@@ -174,7 +155,7 @@ const GridHeaderActions = ({ table, openAPIDocsPanel, refreshDocs }: GridHeaderA
{doesHaveAutoGeneratedAPIdocs && (
<div className="mt-[1px]">
- <RenderAPIPreviewToggle />
+ <APIDocsButton section={['entities', table.name]} />
</div>
)}
</div>
diff --git a/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx b/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx
index 83f77f49a8e..c72c8c61c0c 100644
--- a/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx
+++ b/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx
@@ -23,7 +23,6 @@ import {
ForeignKeyConstraint,
useForeignKeyConstraintsQuery,
} from 'data/database/foreign-key-constraints-query'
-import { useProjectJsonSchemaQuery } from 'data/docs/project-json-schema-query'
import { ENTITY_TYPE } from 'data/entity-types/entity-type-constants'
import { sqlKeys } from 'data/sql/keys'
import { useTableRowUpdateMutation } from 'data/table-rows/table-row-update-mutation'
@@ -35,8 +34,6 @@ import { EMPTY_ARR } from 'lib/void'
import { useAppStateSnapshot } from 'state/app-state'
import { useTableEditorStateSnapshot } from 'state/table-editor'
import { SchemaView } from 'types'
-import { useIsAPIDocsSidePanelEnabled } from '../App/FeaturePreview/FeaturePreviewContext'
-import APIDocumentationPanel from './APIDocumentationPanel'
import GridHeaderActions from './GridHeaderActions'
import NotFoundState from './NotFoundState'
import SidePanelEditor from './SidePanelEditor'
@@ -63,10 +60,8 @@ const TableGridEditor = ({
const appSnap = useAppStateSnapshot()
const snap = useTableEditorStateSnapshot()
const gridRef = useRef<SupabaseGridRef>(null)
- const isNewAPIDocsEnabled = useIsAPIDocsSidePanelEnabled()
const [encryptedColumns, setEncryptedColumns] = useState([])
- const [apiPreviewPanelOpen, setApiPreviewPanelOpen] = useState(false)
const [{ view: selectedView = 'data' }, setUrlState] = useUrlState()
const setSelectedView = (view: string) => {
@@ -145,9 +140,6 @@ const TableGridEditor = ({
},
})
- const { refetch } = useProjectJsonSchemaQuery({ projectRef })
- const refreshDocs = async () => await refetch()
-
const { data } = useForeignKeyConstraintsQuery({
projectRef: project?.ref,
connectionString: project?.connectionString,
@@ -321,23 +313,11 @@ const TableGridEditor = ({
editable={!isReadOnly && canEditViaTableEditor}
schema={selectedTable.schema}
table={gridTable}
- refreshDocs={refreshDocs}
headerActions={
isTableSelected || isViewSelected || canEditViaTableEditor ? (
<>
{canEditViaTableEditor && (
- <GridHeaderActions
- table={selectedTable as PostgresTable}
- openAPIDocsPanel={() => {
- if (isNewAPIDocsEnabled) {
- appSnap.setActiveDocsSection(['entities', selectedTable.name])
- appSnap.setShowProjectApiDocs(true)
- } else {
- setApiPreviewPanelOpen(true)
- }
- }}
- refreshDocs={refreshDocs}
- />
+ <GridHeaderActions table={selectedTable as PostgresTable} />
)}
{(isTableSelected || isViewSelected) && (
<>
@@ -395,11 +375,6 @@ const TableGridEditor = ({
onTableCreated={onTableCreated}
/>
)}
-
- <APIDocumentationPanel
- visible={apiPreviewPanelOpen}
- onClose={() => setApiPreviewPanelOpen(false)}
- />
</>
)
}
diff --git a/studio/components/layouts/DatabaseLayout/DatabaseLayout.tsx b/studio/components/layouts/DatabaseLayout/DatabaseLayout.tsx
index 02a3b862cb7..d5d33ad212e 100644
--- a/studio/components/layouts/DatabaseLayout/DatabaseLayout.tsx
+++ b/studio/components/layouts/DatabaseLayout/DatabaseLayout.tsx
@@ -6,7 +6,6 @@ import ProductMenu from 'components/ui/ProductMenu'
import { useSelectedProject, useStore, withAuth } from 'hooks'
import ProjectLayout from '../'
import { generateDatabaseMenu } from './DatabaseMenu.utils'
-import { useIsAPIDocsSidePanelEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'
export interface DatabaseLayoutProps {
title?: string
@@ -22,7 +21,6 @@ const DatabaseLayout = ({ children }: PropsWithChildren<DatabaseLayoutProps>) =>
const vaultExtension = meta.extensions.byId('supabase_vault')
const isVaultEnabled = vaultExtension !== undefined && vaultExtension.installed_version !== null
const pgNetExtensionExists = meta.extensions.byId('pg_net') !== undefined
- const isNewAPIDocsEnabled = useIsAPIDocsSidePanelEnabled()
useEffect(() => {
if (ui.selectedProjectRef) {
@@ -43,10 +41,7 @@ const DatabaseLayout = ({ children }: PropsWithChildren<DatabaseLayoutProps>) =>
<ProjectLayout
product="Database"
productMenu={
- <ProductMenu
- page={page}
- menu={generateDatabaseMenu(project, { pgNetExtensionExists, isNewAPIDocsEnabled })}
- />
+ <ProductMenu page={page} menu={generateDatabaseMenu(project, { pgNetExtensionExists })} />
}
>
<main style={{ maxHeight: '100vh' }} className="flex-1 overflow-y-auto">
diff --git a/studio/components/layouts/DatabaseLayout/DatabaseMenu.utils.ts b/studio/components/layouts/DatabaseLayout/DatabaseMenu.utils.ts
index 31e4c57e46f..1e848f9f042 100644
--- a/studio/components/layouts/DatabaseLayout/DatabaseMenu.utils.ts
+++ b/studio/components/layouts/DatabaseLayout/DatabaseMenu.utils.ts
@@ -4,13 +4,10 @@ import { IS_PLATFORM } from 'lib/constants'
export const generateDatabaseMenu = (
project?: Project,
- flags?: {
- pgNetExtensionExists: boolean
- isNewAPIDocsEnabled: boolean
- }
+ flags?: { pgNetExtensionExists: boolean }
): ProductMenuGroup[] => {
const ref = project?.ref ?? 'default'
- const { pgNetExtensionExists, isNewAPIDocsEnabled } = flags || {}
+ const { pgNetExtensionExists } = flags || {}
return [
{
@@ -92,16 +89,12 @@ export const generateDatabaseMenu = (
url: `/project/${ref}/database/types`,
items: [],
},
- ...(isNewAPIDocsEnabled
- ? [
- {
- name: 'GraphiQL',
- key: 'graphiql',
- url: `/project/${ref}/database/graphiql`,
- items: [],
- },
- ]
- : []),
+ {
+ name: 'GraphiQL',
+ key: 'graphiql',
+ url: `/project/${ref}/database/graphiql`,
+ items: [],
+ },
],
},
]
diff --git a/studio/components/layouts/FunctionsLayout.tsx b/studio/components/layouts/FunctionsLayout.tsx
index 605b6f2ecd8..7ade497184b 100644
--- a/studio/components/layouts/FunctionsLayout.tsx
+++ b/studio/components/layouts/FunctionsLayout.tsx
@@ -5,7 +5,7 @@ import Link from 'next/link'
import { PropsWithChildren } from 'react'
import { Button, IconCode, IconExternalLink } from 'ui'
-import { useIsAPIDocsSidePanelEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'
+import APIDocsButton from 'components/ui/APIDocsButton'
import NoPermission from 'components/ui/NoPermission'
import { useEdgeFunctionQuery } from 'data/edge-functions/edge-function-query'
import { useEdgeFunctionsQuery } from 'data/edge-functions/edge-functions-query'
@@ -21,7 +21,6 @@ interface FunctionsLayoutProps {
const FunctionsLayout = ({ title, children }: PropsWithChildren<FunctionsLayoutProps>) => {
const snap = useAppStateSnapshot()
const { functionSlug, ref } = useParams()
- const isNewAPIDocsEnabled = useIsAPIDocsSidePanelEnabled()
const { data: functions, isLoading } = useEdgeFunctionsQuery({ projectRef: ref })
const { data: selectedFunction } = useEdgeFunctionQuery({ projectRef: ref, slug: functionSlug })
@@ -114,24 +113,13 @@ const FunctionsLayout = ({ title, children }: PropsWithChildren<FunctionsLayoutP
<Button asChild type="default">
<Link href={`/project/${ref}/settings/functions`}>Manage secrets</Link>
</Button>
- {isNewAPIDocsEnabled && (
- <Button
- size="tiny"
- className="mx-2 translate-y-[1px]"
- type="default"
- icon={<IconCode size={14} strokeWidth={2} />}
- onClick={() => {
- snap.setActiveDocsSection(
- functionSlug !== undefined
- ? ['edge-functions', functionSlug]
- : ['edge-functions']
- )
- snap.setShowProjectApiDocs(true)
- }}
- >
- API
- </Button>
- )}
+ <APIDocsButton
+ section={
+ functionSlug !== undefined
+ ? ['edge-functions', functionSlug]
+ : ['edge-functions']
+ }
+ />
<Button
asChild
type="default"
diff --git a/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.tsx b/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.tsx
index 9012ce5bb95..91f0484751f 100644
--- a/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.tsx
+++ b/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.tsx
@@ -26,7 +26,6 @@ import {
useCommandMenu,
} from 'ui'
-import { useIsAPIDocsSidePanelEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'
import { useFlag, useIsFeatureEnabled } from 'hooks'
import { IS_PLATFORM } from 'lib/constants'
import { detectOS } from 'lib/helpers'
@@ -51,7 +50,6 @@ const NavigationBar = () => {
const navLayoutV2 = useFlag('navigationLayoutV2')
const supabaseAIEnabled = useFlag('sqlEditorSupabaseAI')
const showFeaturePreviews = useFlag('featurePreviews')
- const isNewAPIDocsEnabled = useIsAPIDocsSidePanelEnabled()
const {
projectAuthAll: authEnabled,
@@ -68,7 +66,7 @@ const NavigationBar = () => {
storage: storageEnabled,
realtime: realtimeEnabled,
})
- const otherRoutes = generateOtherRoutes(projectRef, project, isNewAPIDocsEnabled)
+ const otherRoutes = generateOtherRoutes(projectRef, project)
return (
<div
@@ -114,45 +112,50 @@ const NavigationBar = () => {
/>
))}
<div className="h-px w-full bg-border"></div>
- {otherRoutes.map((route) => (
- <NavigationIconButton
- key={route.key}
- route={route}
- isActive={activeRoute === route.key}
- />
- ))}
+ {otherRoutes.map((route) => {
+ if (route.key === 'api') {
+ return (
+ <Tooltip.Root delayDuration={0} key={route.key}>
+ <Tooltip.Trigger asChild>
+ <Button
+ type="text"
+ size="tiny"
+ onClick={() => snap.setShowProjectApiDocs(true)}
+ className="border-none"
+ >
+ <div className="py-[7px]">
+ <IconFileText size={18} strokeWidth={2} className="text-foreground-lighter" />
+ </div>
+ </Button>
+ </Tooltip.Trigger>
+ <Tooltip.Portal>
+ <Tooltip.Content side="right">
+ <Tooltip.Arrow className="radix-tooltip-arrow" />
+ <div
+ className={[
+ 'bg-alternative shadow-lg shadow-background-surface-100 py-1.5 px-3 rounded leading-none', // background
+ 'border border-default', //border
+ ].join(' ')}
+ >
+ <span className="text-foreground text-xs">Project API Docs</span>
+ </div>
+ </Tooltip.Content>
+ </Tooltip.Portal>
+ </Tooltip.Root>
+ )
+ } else {
+ return (
+ <NavigationIconButton
+ key={route.key}
+ route={route}
+ isActive={activeRoute === route.key}
+ />
+ )
+ }
+ })}
</ul>
{!navLayoutV2 && (
<ul className="flex flex-col space-y-4 items-center">
- {isNewAPIDocsEnabled && (
- <Tooltip.Root delayDuration={0}>
- <Tooltip.Trigger asChild>
- <Button
- type="text"
- size="tiny"
- onClick={() => snap.setShowProjectApiDocs(true)}
- className="border-none"
- >
- <div className="py-1">
- <IconFileText size={18} strokeWidth={2} className="text-foreground-lighter" />
- </div>
- </Button>
- </Tooltip.Trigger>
- <Tooltip.Portal>
- <Tooltip.Content side="right">
- <Tooltip.Arrow className="radix-tooltip-arrow" />
- <div
- className={[
- 'rounded py-1 px-2 leading-none shadow text-xs',
- 'border border-background flex items-center space-x-1',
- ].join(' ')}
- >
- Project API Docs
- </div>
- </Tooltip.Content>
- </Tooltip.Portal>
- </Tooltip.Root>
- )}
{IS_PLATFORM && (
<Tooltip.Root delayDuration={0}>
<Tooltip.Trigger asChild>
diff --git a/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.utils.tsx b/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.utils.tsx
index 4ecbb2dbdd6..3d64960358a 100644
--- a/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.utils.tsx
+++ b/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.utils.tsx
@@ -196,11 +196,7 @@ export const generateProductRoutes = (
]
}
-export const generateOtherRoutes = (
- ref?: string,
- project?: ProjectBase,
- isNewAPIDocsEnabled?: boolean
-): Route[] => {
+export const generateOtherRoutes = (ref?: string, project?: ProjectBase): Route[] => {
const isProjectBuilding = project?.status === PROJECT_STATUS.COMING_UP
const buildingUrl = `/project/${ref}/building`
@@ -221,16 +217,12 @@ export const generateOtherRoutes = (
icon: <IconList size={18} strokeWidth={2.5} />,
link: ref && (isProjectBuilding ? buildingUrl : `/project/${ref}/logs/explorer`),
},
- ...(!isNewAPIDocsEnabled
- ? [
- {
- key: 'api',
- label: 'API Docs',
- icon: <IconFileText size={18} strokeWidth={2} />,
- link: ref && (isProjectBuilding ? buildingUrl : `/project/${ref}/api`),
- },
- ]
- : []),
+ {
+ key: 'api',
+ label: 'API Docs',
+ icon: <IconFileText size={18} strokeWidth={2} />,
+ link: undefined,
+ },
...(IS_PLATFORM
? [
{
diff --git a/studio/components/layouts/StorageLayout/BucketRow.tsx b/studio/components/layouts/StorageLayout/BucketRow.tsx
index 19c5bb209e9..94b8ccc3f99 100644
--- a/studio/components/layouts/StorageLayout/BucketRow.tsx
+++ b/studio/components/layouts/StorageLayout/BucketRow.tsx
@@ -51,7 +51,9 @@ const BucketRow = ({
>
<div className="flex items-center justify-between space-x-2 truncate w-full">
<p
- className="text-sm text-foreground-light group-hover:text-foreground transition truncate"
+ className={`text-sm group-hover:text-foreground transition truncate ${
+ isSelected ? 'text-foreground' : 'text-foreground-light'
+ }`}
title={bucket.name}
>
{bucket.name}
diff --git a/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerHeader.tsx b/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerHeader.tsx
index c35cc4ea11b..faf394a62d0 100644
--- a/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerHeader.tsx
+++ b/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerHeader.tsx
@@ -36,8 +36,8 @@ import { useCheckPermissions } from 'hooks'
import { useStorageStore } from 'localStores/storageExplorer/StorageExplorerStore'
import { useStorageExplorerStateSnapshot } from 'state/storage-explorer'
import { STORAGE_SORT_BY, STORAGE_SORT_BY_ORDER, STORAGE_VIEWS } from '../Storage.constants'
-import { useIsAPIDocsSidePanelEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'
import { useAppStateSnapshot } from 'state/app-state'
+import APIDocsButton from 'components/ui/APIDocsButton'
const VIEW_OPTIONS = [
{ key: STORAGE_VIEWS.COLUMNS, name: 'As columns' },
@@ -142,7 +142,6 @@ const FileExplorerHeader = ({
const debounceDuration = 300
const appSnap = useAppStateSnapshot()
const snap = useStorageExplorerStateSnapshot()
- const isNewAPIDocsEnabled = useIsAPIDocsSidePanelEnabled()
const [pathString, setPathString] = useState('')
const [searchString, setSearchString] = useState('')
@@ -357,158 +356,63 @@ const FileExplorerHeader = ({
Reload
</Button>
- {isNewAPIDocsEnabled ? (
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- type="text"
- icon={
- view === 'LIST' ? (
- <IconList size={16} strokeWidth={2} />
- ) : (
- <IconColumns size={16} strokeWidth={2} />
- )
- }
- >
- View
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="w-40 min-w-0">
- {VIEW_OPTIONS.map((option) => (
- <DropdownMenuItem key={option.key} onClick={() => setView(option.key)}>
- <div className="flex items-center justify-between w-full">
- <p>{option.name}</p>
- {view === option.key && <IconCheck className="text-brand" strokeWidth={2} />}
- </div>
- </DropdownMenuItem>
- ))}
- <DropdownMenuSeparator />
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>Sort by</DropdownMenuSubTrigger>
- <DropdownMenuSubContent className="w-44">
- {SORT_BY_OPTIONS.map((option) => (
- <DropdownMenuItem key={option.key} onClick={() => setSortBy(option.key)}>
- <div className="flex items-center justify-between w-full">
- <p>{option.name}</p>
- {sortBy === option.key && (
- <IconCheck className="text-brand" strokeWidth={2} />
- )}
- </div>
- </DropdownMenuItem>
- ))}
- </DropdownMenuSubContent>
- </DropdownMenuSub>
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>Sort order</DropdownMenuSubTrigger>
- <DropdownMenuSubContent>
- {SORT_ORDER_OPTIONS.map((option) => (
- <DropdownMenuItem key={option.key} onClick={() => setSortByOrder(option.key)}>
- <div className="flex items-center justify-between w-full">
- <p>{option.name}</p>
- {sortByOrder === option.key && (
- <IconCheck className="text-brand" strokeWidth={2} />
- )}
- </div>
- </DropdownMenuItem>
- ))}
- </DropdownMenuSubContent>
- </DropdownMenuSub>
- </DropdownMenuContent>
- </DropdownMenu>
- ) : (
- <>
- <DropdownMenu>
- <DropdownMenuTrigger>
- <Button
- asChild
- icon={
- view === 'LIST' ? (
- <IconList size={16} strokeWidth={2} />
- ) : (
- <IconColumns size={16} strokeWidth={2} />
- )
- }
- type="text"
- disabled={breadcrumbs.length === 0}
- onChange={setView}
- >
- <span>View as</span>
- </Button>
- </DropdownMenuTrigger>
-
- <DropdownMenuContent>
- <DropdownMenuRadioGroup key="viewOptions" value={view} onValueChange={setView}>
- <DropdownMenuRadioItem value={STORAGE_VIEWS.COLUMNS}>
- Columns
- </DropdownMenuRadioItem>
- <DropdownMenuRadioItem value={STORAGE_VIEWS.LIST}>List</DropdownMenuRadioItem>
- </DropdownMenuRadioGroup>
- </DropdownMenuContent>
- </DropdownMenu>
- <DropdownMenu>
- <DropdownMenuTrigger>
- <Button
- asChild
- icon={<IconChevronsDown size={16} strokeWidth={2} />}
- type="text"
- disabled={breadcrumbs.length === 0}
- >
- <span>Sort by</span>
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent>
- <DropdownMenuRadioGroup
- key="sortOptions"
- value={sortBy}
- onValueChange={setSortBy}
- >
- <DropdownMenuRadioItem value={STORAGE_SORT_BY.NAME}>Name</DropdownMenuRadioItem>
- <DropdownMenuRadioItem value={STORAGE_SORT_BY.CREATED_AT}>
- Time created
- </DropdownMenuRadioItem>
- <DropdownMenuRadioItem value={STORAGE_SORT_BY.UPDATED_AT}>
- Time modified
- </DropdownMenuRadioItem>
- <DropdownMenuRadioItem value={STORAGE_SORT_BY.LAST_ACCESSED_AT}>
- Time last accessed
- </DropdownMenuRadioItem>
- </DropdownMenuRadioGroup>
- </DropdownMenuContent>
- </DropdownMenu>
- <DropdownMenu>
- <DropdownMenuTrigger>
- <Button
- asChild
- icon={
- sortByOrder === STORAGE_SORT_BY_ORDER.DESC ? (
- <IconChevronsDown size={16} strokeWidth={2} />
- ) : (
- <IconChevronsUp size={16} strokeWidth={2} />
- )
- }
- type="text"
- disabled={breadcrumbs.length === 0}
- >
- <span>Sort Order</span>
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent>
- <DropdownMenuRadioGroup
- key="sortOrderOptions"
- value={sortByOrder}
- onValueChange={setSortByOrder}
- >
- <DropdownMenuRadioItem value={STORAGE_SORT_BY_ORDER.ASC}>
- Ascending
- </DropdownMenuRadioItem>
- <DropdownMenuRadioItem value={STORAGE_SORT_BY_ORDER.DESC}>
- Descending
- </DropdownMenuRadioItem>
- </DropdownMenuRadioGroup>
- </DropdownMenuContent>
- </DropdownMenu>
- </>
- )}
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ type="text"
+ icon={
+ view === 'LIST' ? (
+ <IconList size={16} strokeWidth={2} />
+ ) : (
+ <IconColumns size={16} strokeWidth={2} />
+ )
+ }
+ >
+ View
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-40 min-w-0">
+ {VIEW_OPTIONS.map((option) => (
+ <DropdownMenuItem key={option.key} onClick={() => setView(option.key)}>
+ <div className="flex items-center justify-between w-full">
+ <p>{option.name}</p>
+ {view === option.key && <IconCheck className="text-brand" strokeWidth={2} />}
+ </div>
+ </DropdownMenuItem>
+ ))}
+ <DropdownMenuSeparator />
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>Sort by</DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="w-44">
+ {SORT_BY_OPTIONS.map((option) => (
+ <DropdownMenuItem key={option.key} onClick={() => setSortBy(option.key)}>
+ <div className="flex items-center justify-between w-full">
+ <p>{option.name}</p>
+ {sortBy === option.key && (
+ <IconCheck className="text-brand" strokeWidth={2} />
+ )}
+ </div>
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>Sort order</DropdownMenuSubTrigger>
+ <DropdownMenuSubContent>
+ {SORT_ORDER_OPTIONS.map((option) => (
+ <DropdownMenuItem key={option.key} onClick={() => setSortByOrder(option.key)}>
+ <div className="flex items-center justify-between w-full">
+ <p>{option.name}</p>
+ {sortByOrder === option.key && (
+ <IconCheck className="text-brand" strokeWidth={2} />
+ )}
+ </div>
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ </DropdownMenuContent>
+ </DropdownMenu>
</div>
<div className="h-6 border-r border-control" />
@@ -610,23 +514,11 @@ const FileExplorerHeader = ({
)}
</div>
- {isNewAPIDocsEnabled && (
- <>
- <div className="h-6 border-r border-control" />
- <Button
- size="tiny"
- className="mx-2"
- type="default"
- icon={<IconCode size={14} strokeWidth={2} />}
- onClick={() => {
- appSnap.setActiveDocsSection(['storage', selectedBucket.name])
- appSnap.setShowProjectApiDocs(true)
- }}
- >
- API
- </Button>
- </>
- )}
+ <div className="h-6 border-r border-control" />
+
+ <div className="mx-2">
+ <APIDocsButton section={['storage', selectedBucket.name]} />
+ </div>
</div>
</div>
)
diff --git a/studio/components/ui/APIDocsButton.tsx b/studio/components/ui/APIDocsButton.tsx
new file mode 100644
index 00000000000..dd9958d4da8
--- /dev/null
+++ b/studio/components/ui/APIDocsButton.tsx
@@ -0,0 +1,26 @@
+import { useAppStateSnapshot } from 'state/app-state'
+import { Button, IconCode } from 'ui'
+
+interface APIDocsButtonProps {
+ section?: string[]
+}
+
+const APIDocsButton = ({ section }: APIDocsButtonProps) => {
+ const snap = useAppStateSnapshot()
+
+ return (
+ <Button
+ size="tiny"
+ type="default"
+ onClick={() => {
+ if (section) snap.setActiveDocsSection(section)
+ snap.setShowProjectApiDocs(true)
+ }}
+ icon={<IconCode size={14} strokeWidth={2} />}
+ >
+ API Docs
+ </Button>
+ )
+}
+
+export default APIDocsButton
diff --git a/studio/lib/common/fetch/delete.ts b/studio/lib/common/fetch/delete.ts
index 4bedf25cfac..6a68c4b001b 100644
--- a/studio/lib/common/fetch/delete.ts
+++ b/studio/lib/common/fetch/delete.ts
@@ -2,6 +2,9 @@ import { handleError, handleResponse, handleResponseError, constructHeaders } fr
import { uuidv4 } from '../../helpers'
import { SupaResponse } from 'types/base'
+/**
+ * @deprecated please use del method from data/fetchers instead
+ */
export async function delete_<T = any>(
url: string,
data?: { [prop: string]: any },
diff --git a/studio/lib/common/fetch/get.ts b/studio/lib/common/fetch/get.ts
index 58b3f8946d3..5c3c895a58f 100644
--- a/studio/lib/common/fetch/get.ts
+++ b/studio/lib/common/fetch/get.ts
@@ -2,6 +2,9 @@ import { handleError, handleResponse, handleResponseError, constructHeaders } fr
import { uuidv4 } from '../../helpers'
import { SupaResponse } from 'types/base'
+/**
+ * @deprecated please use get method from data/fetchers instead
+ */
export async function get<T = any>(
url: string,
options?: { [prop: string]: any }
diff --git a/studio/lib/common/fetch/head.ts b/studio/lib/common/fetch/head.ts
index 2bcba4895f3..dcdb88e864c 100644
--- a/studio/lib/common/fetch/head.ts
+++ b/studio/lib/common/fetch/head.ts
@@ -2,6 +2,9 @@ import { handleError, handleHeadResponse, handleResponseError, constructHeaders
import { uuidv4 } from '../../helpers'
import { SupaResponse } from 'types/base'
+/**
+ * @deprecated please use head method from data/fetchers instead
+ */
export async function head<T = any>(
url: string,
headersToRetrieve: string[],
diff --git a/studio/lib/common/fetch/patch.ts b/studio/lib/common/fetch/patch.ts
index 7fcf4aad2c9..f99f3ca8ef0 100644
--- a/studio/lib/common/fetch/patch.ts
+++ b/studio/lib/common/fetch/patch.ts
@@ -2,6 +2,9 @@ import { constructHeaders, handleError, handleResponse, handleResponseError } fr
import { uuidv4 } from '../../helpers'
import { SupaResponse } from 'types/base'
+/**
+ * @deprecated please use patch method from data/fetchers instead
+ */
export async function patch<T = any>(
url: string,
data: { [prop: string]: any },
diff --git a/studio/lib/common/fetch/post.ts b/studio/lib/common/fetch/post.ts
index ce29bada3c6..2f398b470c4 100644
--- a/studio/lib/common/fetch/post.ts
+++ b/studio/lib/common/fetch/post.ts
@@ -2,6 +2,9 @@ import { handleError, handleResponse, handleResponseError, constructHeaders } fr
import { uuidv4 } from 'lib/helpers'
import { SupaResponse } from 'types/base'
+/**
+ * @deprecated please use post method from data/fetchers instead
+ */
export async function post<T = any>(
url: string,
data: { [prop: string]: any },
diff --git a/studio/lib/common/fetch/put.ts b/studio/lib/common/fetch/put.ts
index 8b52e958320..1eec77c933f 100644
--- a/studio/lib/common/fetch/put.ts
+++ b/studio/lib/common/fetch/put.ts
@@ -2,6 +2,9 @@ import { constructHeaders, handleError, handleResponse, handleResponseError } fr
import { uuidv4 } from '../../helpers'
import { SupaResponse } from 'types/base'
+/**
+ * @deprecated please use post method from data/fetchers instead
+ */
export async function put<T = any>(
url: string,
data: { [prop: string]: any },
diff --git a/studio/pages/project/[ref]/api/graphiql.tsx b/studio/pages/project/[ref]/api/graphiql.tsx
deleted file mode 100644
index d4a67a8883d..00000000000
--- a/studio/pages/project/[ref]/api/graphiql.tsx
+++ /dev/null
@@ -1,88 +0,0 @@
-import { createGraphiQLFetcher, Fetcher } from '@graphiql/toolkit'
-import { observer } from 'mobx-react-lite'
-import { useEffect, useMemo } from 'react'
-
-import '@graphiql/react/dist/style.css'
-import { useParams } from 'common/hooks'
-import ExtensionCard from 'components/interfaces/Database/Extensions/ExtensionCard'
-import GraphiQL from 'components/interfaces/GraphQL/GraphiQL'
-import { DocsLayout } from 'components/layouts'
-import Connecting from 'components/ui/Loading/Loading'
-import { useSessionAccessTokenQuery } from 'data/auth/session-access-token-query'
-import { useProjectApiQuery } from 'data/config/project-api-query'
-import { useStore } from 'hooks'
-import { API_URL, IS_PLATFORM } from 'lib/constants'
-import { useTheme } from 'next-themes'
-import { NextPageWithLayout } from 'types'
-
-const GraphiQLPage: NextPageWithLayout = () => {
- const { ref: projectRef } = useParams()
- const { ui, meta } = useStore()
- const { resolvedTheme } = useTheme()
- const currentTheme = resolvedTheme === 'dark' ? 'dark' : 'light'
-
- const isExtensionsLoading = meta.extensions.isLoading
- const pgGraphqlExtension = meta.extensions.byId('pg_graphql')
-
- const { data: accessToken } = useSessionAccessTokenQuery({ enabled: IS_PLATFORM })
- const { data: settings, isFetched } = useProjectApiQuery({ projectRef })
-
- const apiService = settings?.autoApiService
- const anonKey = apiService?.service_api_keys.find((x) => x.name === 'anon key')
- ? apiService.defaultApiKey
- : undefined
-
- useEffect(() => {
- if (ui.selectedProjectRef) {
- // Schemas may be needed when enabling the GraphQL extension
- meta.extensions.load()
- }
- }, [ui.selectedProjectRef])
-
- const graphqlUrl = `${API_URL}/projects/${projectRef}/api/graphql`
-
- const fetcher = useMemo(() => {
- const fetcherFn = createGraphiQLFetcher({ url: graphqlUrl, fetch })
- const customFetcher: Fetcher = (graphqlParams, opts) => {
- return fetcherFn(graphqlParams, {
- ...opts,
- headers: {
- ...opts?.headers,
- Authorization: `Bearer ${accessToken}`,
- 'x-graphql-authorization':
- opts?.headers?.['Authorization'] ?? opts?.headers?.['authorization'],
- },
- })
- }
-
- return customFetcher
- }, [graphqlUrl, accessToken])
-
- if ((IS_PLATFORM && !accessToken) || !isFetched || (isExtensionsLoading && !pgGraphqlExtension)) {
- return <Connecting />
- }
-
- if (pgGraphqlExtension?.installed_version === null) {
- return (
- <div className="flex flex-col items-center justify-center flex-1 px-4">
- <div className="w-full max-w-md">
- <div className="mb-6">
- <h1 className="mt-8 mb-2 text-2xl">Enable the GraphQL Extension</h1>
- <h2 className="text-sm text-foreground-light">
- Toggle the switch below to enable the GraphQL extension. You can then use the GraphQL
- API with your Supabase Database.
- </h2>
- </div>
-
- <ExtensionCard extension={pgGraphqlExtension} />
- </div>
- </div>
- )
- }
-
- return <GraphiQL fetcher={fetcher} theme={currentTheme} accessToken={anonKey} />
-}
-
-GraphiQLPage.getLayout = (page) => <DocsLayout title="GraphiQL">{page}</DocsLayout>
-
-export default observer(GraphiQLPage)
diff --git a/studio/pages/project/[ref]/api/index.tsx b/studio/pages/project/[ref]/api/index.tsx
deleted file mode 100644
index c159b220e02..00000000000
--- a/studio/pages/project/[ref]/api/index.tsx
+++ /dev/null
@@ -1,164 +0,0 @@
-import { useParams } from 'common'
-import { observer, useLocalObservable } from 'mobx-react-lite'
-import { useRouter } from 'next/router'
-import { createContext, useContext, useEffect, useState } from 'react'
-
-import { GeneralContent, ResourceContent, RpcContent } from 'components/interfaces/Docs'
-import LangSelector from 'components/interfaces/Docs/LangSelector'
-import { DocsLayout } from 'components/layouts'
-import { useProjectApiQuery } from 'data/config/project-api-query'
-import { useProjectJsonSchemaQuery } from 'data/docs/project-json-schema-query'
-import { snakeToCamel } from 'lib/helpers'
-import { NextPageWithLayout } from 'types'
-
-const PageContext = createContext(null)
-
-const PageConfig: NextPageWithLayout = () => {
- const PageState: any = useLocalObservable(() => ({
- projectRef: '',
- jsonSchema: {},
- resources: {},
- rpcs: {},
- setJsonSchema(value: any) {
- const { paths } = value || {}
- const functionPath = 'rpc/'
- let resources: any = {}
- let rpcs: 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 if (trimmed.includes(functionPath)) rpcs[id] = enriched
- else resources[id] = enriched
- })
-
- PageState.jsonSchema = value
- PageState.resources = resources
- PageState.rpcs = rpcs
- },
- }))
-
- const router = useRouter()
- const { query } = router
- PageState.projectRef = query.ref
-
- return (
- <PageContext.Provider value={PageState}>
- <DocView />
- </PageContext.Provider>
- )
-}
-
-PageConfig.getLayout = (page) => <DocsLayout title="API">{page}</DocsLayout>
-
-export default observer(PageConfig)
-
-const DEFAULT_KEY = { name: 'hide', key: 'SUPABASE_KEY' }
-
-const DocView = observer(() => {
- const PageState: any = useContext(PageContext)
- const { ref: projectRef, page, resource, rpc } = useParams()
- const [selectedLang, setSelectedLang] = useState<any>('js')
- const [showApiKey, setShowApiKey] = useState<any>(DEFAULT_KEY)
-
- const { data, error } = useProjectApiQuery({
- projectRef,
- })
-
- const apiService = data?.autoApiService
- const anonKey = apiService?.service_api_keys.find((x) => x.name === 'anon key')
- ? apiService.defaultApiKey
- : undefined
-
- const {
- data: jsonSchema,
- error: jsonSchemaError,
- refetch,
- } = useProjectJsonSchemaQuery({ projectRef })
-
- useEffect(() => {
- PageState.setJsonSchema(jsonSchema)
- }, [jsonSchema])
-
- const refreshDocs = async () => {
- await refetch()
- }
-
- if (error || jsonSchemaError)
- return (
- <div className="p-6 mx-auto text-center sm:w-full md:w-3/4">
- <p className="text-foreground-light">
- <p>Error connecting to API</p>
- <p>{`${error || jsonSchemaError}`}</p>
- </p>
- </div>
- )
- if (!data || !jsonSchema || !PageState.jsonSchema)
- return (
- <div className="p-6 mx-auto text-center sm:w-full md:w-3/4">
- <h3 className="text-xl">Building docs ...</h3>
- </div>
- )
-
- // Data Loaded
- const autoApiService = {
- ...data.autoApiService,
- endpoint: `${data.autoApiService.protocol ?? 'https'}://${data.autoApiService.endpoint ?? '-'}`,
- }
-
- const { paths, definitions } = PageState.jsonSchema
-
- const PAGE_KEY: any = resource || rpc || page || 'index'
-
- return (
- <div className="w-full h-full overflow-y-auto Docs Docs--api-page" key={PAGE_KEY}>
- <div className="Docs--inner-wrapper">
- <div className="sticky top-0 z-40 flex flex-row-reverse w-full ">
- <LangSelector
- selectedLang={selectedLang}
- setSelectedLang={setSelectedLang}
- showApiKey={showApiKey}
- setShowApiKey={setShowApiKey}
- apiKey={anonKey}
- autoApiService={autoApiService}
- />
- </div>
- <div className="">
- {resource ? (
- <ResourceContent
- autoApiService={autoApiService}
- selectedLang={selectedLang}
- resourceId={resource}
- resources={PageState.resources}
- definitions={definitions}
- paths={paths}
- showApiKey={showApiKey.key}
- refreshDocs={refreshDocs}
- />
- ) : rpc ? (
- <RpcContent
- autoApiService={autoApiService}
- selectedLang={selectedLang}
- rpcId={rpc}
- paths={paths}
- rpcs={PageState.rpcs}
- showApiKey={showApiKey.key}
- refreshDocs={refreshDocs}
- />
- ) : (
- <GeneralContent
- autoApiService={autoApiService}
- selectedLang={selectedLang}
- showApiKey={showApiKey.key}
- page={page}
- />
- )}
- </div>
- </div>
- </div>
- )
-})