The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Feat/api side panel (#17880)
Joshen Lim94f5fc5a6167
diff --git a/studio/components/interfaces/App/FeaturePreview/APISidePanelPreview.tsx b/studio/components/interfaces/App/FeaturePreview/APISidePanelPreview.tsxnew file mode 100644index 00000000000..5e96abfb824--- /dev/null+++ b/studio/components/interfaces/App/FeaturePreview/APISidePanelPreview.tsx@@ -0,0 +1,42 @@+import { useParams } from 'common'+import { Markdown } from 'components/interfaces/Markdown'+import { BASE_PATH } from 'lib/constants'+import Image from 'next/image'++const APISidePanelPreview = () => {+ const { ref } = useParams()++ return (+ <div className="space-y-2">+ <p className="text-foreground-light text-sm mb-4">+ Your project's API documentation will be available on any page across the dashboard. <br />+ Get contextualized code snippets based on what you're viewing in the dashboard. Less+ thinking, more building.+ </p>+ <Image+ src={`${BASE_PATH}/img/previews/api-docs-preview.png`}+ width={1860}+ height={970}+ alt="api-docs-side-panel-preview"+ className="rounded border"+ />+ <div className="space-y-2 !mt-4">+ <p className="text-sm">Enabling this preview will:</p>+ <ul className="list-disc pl-6 text-sm text-foreground-light space-y-1">+ <li>+ Replace the original API documentation page with a global API documentation side panel+ that can be accessed anywhere while in a project.+ </li>+ <li>+ <Markdown+ className="text-foreground-light"+ content={`Move the GraphiQL interface the Database section of the dashboard [here](/project/${ref}/database/graphiql).`}+ />+ </li>+ </ul>+ </div>+ </div>+ )+}++export default APISidePanelPreviewdiff --git a/studio/components/interfaces/App/FeaturePreviewContext.tsx b/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsxsimilarity index 100%rename from studio/components/interfaces/App/FeaturePreviewContext.tsxrename to studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsxdiff --git a/studio/components/interfaces/App/FeaturePreviewModal.tsx b/studio/components/interfaces/App/FeaturePreview/FeaturePreviewModal.tsxsimilarity index 71%rename from studio/components/interfaces/App/FeaturePreviewModal.tsxrename to studio/components/interfaces/App/FeaturePreview/FeaturePreviewModal.tsxindex f46a3172da1..c8860ea82c9 100644--- a/studio/components/interfaces/App/FeaturePreviewModal.tsx+++ b/studio/components/interfaces/App/FeaturePreview/FeaturePreviewModal.tsx@@ -1,13 +1,14 @@import { useTelemetryProps } from 'common'import { useRouter } from 'next/router'import { useState } from 'react'-import { Button, IconEye, IconEyeOff, Modal, ScrollArea, cn } from 'ui'+import { Button, IconExternalLink, IconEye, IconEyeOff, Modal, ScrollArea, cn } from 'ui'import { LOCAL_STORAGE_KEYS } from 'lib/constants'import Telemetry from 'lib/telemetry'import { useAppStateSnapshot } from 'state/app-state'-import { Markdown } from '../Markdown'+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.@@ -15,12 +16,13 @@ const FEATURE_PREVIEWS = [// {// key: LOCAL_STORAGE_KEYS.UI_PREVIEW_NAVIGATION_LAYOUT,// name: 'Global navigation update',- // description: `Experience a redesigned and improved site navigation on the dashboard, with an intention to making finding your way around more intuitive and easier.`,+ // content: null// },{key: LOCAL_STORAGE_KEYS.UI_PREVIEW_API_SIDE_PANEL,name: 'Project API documentation',- description: `Get building with your client application faster with your Project's API documentation now available on any page across the dashboard.`,+ content: <APISidePanelPreview />,+ discussionsUrl: 'https://github.com/orgs/supabase/discussions',},]@@ -52,13 +54,14 @@ const FeaturePreviewModal = () => {<ModalhideFootersize="xlarge"+ className="max-w-4xl"header="Dashboard feature previews"visible={snap.showFeaturePreviewModal}onCancel={() => snap.setShowFeaturePreviewModal(false)}><div className="flex"><div>- <ScrollArea className="h-[400px] w-[240px] border-r">+ <ScrollArea className="h-[550px] w-[240px] border-r">{FEATURE_PREVIEWS.map((feature) => {const isEnabled = flags[feature.key] ?? false@@ -82,14 +85,25 @@ const FeaturePreviewModal = () => {})}</ScrollArea></div>- <div className="flex-grow p-4 space-y-3">+ <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>- <Button type="default" onClick={() => toggleFeature()}>- {isSelectedFeatureEnabled ? 'Disable' : 'Enable'} feature- </Button>+ <div className="flex items-center space-x-2">+ {selectedFeature?.discussionsUrl !== undefined && (+ <Link passHref href={selectedFeature.discussionsUrl}>+ <Button asChild type="default" icon={<IconExternalLink strokeWidth={1.5} />}>+ <a target="_blank" rel="noreferrer">+ Give feedback+ </a>+ </Button>+ </Link>+ )}+ <Button type="default" onClick={() => toggleFeature()}>+ {isSelectedFeatureEnabled ? 'Disable' : 'Enable'} feature+ </Button>+ </div></div>- <Markdown className="text-sm" content={selectedFeature?.description ?? ''} />+ {selectedFeature?.content}</div></div></Modal>diff --git a/studio/components/interfaces/App/FeaturePreview/index.ts b/studio/components/interfaces/App/FeaturePreview/index.tsnew file mode 100644index 00000000000..bf36ec23b7a--- /dev/null+++ b/studio/components/interfaces/App/FeaturePreview/index.ts@@ -0,0 +1,4 @@+import { FeaturePreviewContextProvider } from './FeaturePreviewContext'+import FeaturePreviewModal from './FeaturePreviewModal'++export { FeaturePreviewContextProvider, FeaturePreviewModal }diff --git a/studio/components/interfaces/Auth/Users/Users.tsx b/studio/components/interfaces/Auth/Users/Users.tsxindex 2d19c364152..18476e9a947 100644--- a/studio/components/interfaces/Auth/Users/Users.tsx+++ b/studio/components/interfaces/Auth/Users/Users.tsx@@ -1,15 +1,19 @@import { useParams } from 'common'import { useState } from 'react'-import { Button, IconRefreshCw, IconSearch, IconX, Input, Listbox } from 'ui'+import { Button, IconCode, IconRefreshCw, IconSearch, IconX, Input, Listbox } from 'ui'import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'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('')@@ -80,6 +84,19 @@ 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>+ )}<Buttonsize="tiny"icon={<IconRefreshCw />}@@ -89,7 +106,6 @@ const Users = () => {>Reload</Button>-<AddUserDropdown projectKpsVersion={project?.kpsVersion} /></div></div>diff --git a/studio/components/interfaces/GraphQL/GraphiQL.tsx b/studio/components/interfaces/GraphQL/GraphiQL.tsxindex 9b8df44c33f..6baa40ddbc6 100644--- a/studio/components/interfaces/GraphQL/GraphiQL.tsx+++ b/studio/components/interfaces/GraphQL/GraphiQL.tsx@@ -227,7 +227,7 @@ export const GraphiQLInterface = ({ theme }: GraphiQLInterfaceProps) => {className={clsx('graphiql-query-editor', styles.graphiqlQueryEditor)}aria-label="Query Editor">- <div className="graphiql-query-editor-wrapper">+ <div className="graphiql-query-editor-wrapper text-sm"><QueryEditor /></div><div className="graphiql-toolbar" role="toolbar" aria-label="Editor Commands">@@ -306,7 +306,7 @@ export const GraphiQLInterface = ({ theme }: GraphiQLInterfaceProps) => {</div><div ref={editorToolsResize.secondRef}><section- className="graphiql-editor-tool"+ className="graphiql-editor-tool text-sm"aria-label={activeSecondaryEditor === 'variables' ? 'Variables' : 'Headers'}><VariableEditor@@ -327,7 +327,7 @@ export const GraphiQLInterface = ({ theme }: GraphiQLInterfaceProps) => {<div ref={editorResize.secondRef}><divclassName={clsx(- 'graphiql-response',+ 'graphiql-response text-sm',hasSingleTab? styles.graphiqlResponseSingleTab: styles.graphiqlResponseMultiTabdiff --git a/studio/components/interfaces/ProjectAPIDocs/Content/Bucket.tsx b/studio/components/interfaces/ProjectAPIDocs/Content/Bucket.tsxnew file mode 100644index 00000000000..2477b2b78f9--- /dev/null+++ b/studio/components/interfaces/ProjectAPIDocs/Content/Bucket.tsx@@ -0,0 +1,98 @@+import { useParams } from 'common'+import { Badge } from 'ui'++import { useBucketsQuery } from 'data/storage/buckets-query'+import { formatBytes } from 'lib/helpers'+import { useAppStateSnapshot } from 'state/app-state'+import { DOCS_RESOURCE_CONTENT } from '../ProjectAPIDocs.constants'+import ResourceContent from '../ResourceContent'+import { ContentProps } from './Content.types'++const Bucket = ({ language }: ContentProps) => {+ const { ref } = useParams()+ const snap = useAppStateSnapshot()+ const { data } = useBucketsQuery({ projectRef: ref })++ const resource = snap.activeDocsSection[1]+ const buckets = data ?? []+ const bucket = buckets.find((b) => b.name === resource)+ const allowedMimeTypes = bucket?.allowed_mime_types+ const maxFileSizeLimit = bucket?.file_size_limit++ if (bucket === undefined) return null++ return (+ <div className="divide-y">+ <div className="space-y-1 px-4 py-6">+ <div className="flex items-center space-x-2">+ <h2 className="text-xl">{bucket.name}</h2>+ <Badge color={bucket.public ? 'amber' : 'scale'}>+ {bucket.public ? 'Public' : 'Private'}+ </Badge>+ </div>+ <p className="text-sm text-foreground-light">+ Allowed MIME types:{' '}+ {allowedMimeTypes === null+ ? 'All types are allowed'+ : (allowedMimeTypes ?? []).length === 0+ ? 'No types are allowed'+ : (allowedMimeTypes ?? []).length > 1+ ? (allowedMimeTypes ?? []).join(', ')+ : 'Unknown'}+ </p>+ <p className="text-sm text-foreground-light">+ Max file size limit:{' '}+ {maxFileSizeLimit === null ? 'No limit' : `${formatBytes(maxFileSizeLimit)}`}+ </p>+ </div>++ <ResourceContent+ selectedLanguage={language}+ snippet={DOCS_RESOURCE_CONTENT.uploadFile}+ codeSnippets={DOCS_RESOURCE_CONTENT.uploadFile.code({+ name: resource,+ })}+ />+ <ResourceContent+ selectedLanguage={language}+ snippet={DOCS_RESOURCE_CONTENT.deleteFiles}+ codeSnippets={DOCS_RESOURCE_CONTENT.deleteFiles.code({+ name: resource,+ })}+ />+ <ResourceContent+ selectedLanguage={language}+ snippet={DOCS_RESOURCE_CONTENT.listFiles}+ codeSnippets={DOCS_RESOURCE_CONTENT.listFiles.code({+ name: resource,+ })}+ />+ <ResourceContent+ selectedLanguage={language}+ snippet={DOCS_RESOURCE_CONTENT.downloadFile}+ codeSnippets={DOCS_RESOURCE_CONTENT.downloadFile.code({+ name: resource,+ })}+ />+ {bucket.public ? (+ <ResourceContent+ selectedLanguage={language}+ snippet={DOCS_RESOURCE_CONTENT.retrievePublicURL}+ codeSnippets={DOCS_RESOURCE_CONTENT.retrievePublicURL.code({+ name: resource,+ })}+ />+ ) : (+ <ResourceContent+ selectedLanguage={language}+ snippet={DOCS_RESOURCE_CONTENT.createSignedURL}+ codeSnippets={DOCS_RESOURCE_CONTENT.createSignedURL.code({+ name: resource,+ })}+ />+ )}+ </div>+ )+}++export default Bucketdiff --git a/studio/components/interfaces/ProjectAPIDocs/Content/Content.types.ts b/studio/components/interfaces/ProjectAPIDocs/Content/Content.types.tsnew file mode 100644index 00000000000..7a624c4a606--- /dev/null+++ b/studio/components/interfaces/ProjectAPIDocs/Content/Content.types.ts@@ -0,0 +1,6 @@+export interface ContentProps {+ showKeys?: boolean+ language: 'js' | 'bash'+ endpoint?: string+ apikey?: string+}diff --git a/studio/components/interfaces/ProjectAPIDocs/Content/Content.utils.ts b/studio/components/interfaces/ProjectAPIDocs/Content/Content.utils.tsnew file mode 100644index 00000000000..7a3f2dfb694--- /dev/null+++ b/studio/components/interfaces/ProjectAPIDocs/Content/Content.utils.ts@@ -0,0 +1,6 @@+export const navigateToSection = (key: string) => {+ if (typeof window !== 'undefined') {+ const el = document.getElementById(key)+ if (el) el.scrollIntoView({ behavior: 'smooth' })+ }+}diff --git a/studio/components/interfaces/ProjectAPIDocs/Content/EdgeFunction.tsx b/studio/components/interfaces/ProjectAPIDocs/Content/EdgeFunction.tsxnew file mode 100644index 00000000000..7e1022ea6d7--- /dev/null+++ b/studio/components/interfaces/ProjectAPIDocs/Content/EdgeFunction.tsx@@ -0,0 +1,41 @@+import { useParams } from 'common'++import { useEdgeFunctionsQuery } from 'data/edge-functions/edge-functions-query'+import { useAppStateSnapshot } from 'state/app-state'+import { DOCS_RESOURCE_CONTENT } from '../ProjectAPIDocs.constants'+import ResourceContent from '../ResourceContent'+import { ContentProps } from './Content.types'++const Bucket = ({ language, apikey = 'API_KEY', endpoint }: ContentProps) => {+ const { ref } = useParams()+ const snap = useAppStateSnapshot()+ const { data } = useEdgeFunctionsQuery({ projectRef: ref })++ const resource = snap.activeDocsSection[1]+ const edgeFunctions = data ?? []+ const edgeFunction = edgeFunctions.find((fn) => fn.name === resource)++ if (edgeFunction === undefined) return null++ return (+ <div className="divide-y">+ <div className="space-y-1 px-4 py-6">+ <div className="flex items-center space-x-2">+ <h2 className="text-xl">{edgeFunction.name}</h2>+ </div>+ </div>++ <ResourceContent+ selectedLanguage={language}+ snippet={DOCS_RESOURCE_CONTENT.invokeEdgeFunction}+ codeSnippets={DOCS_RESOURCE_CONTENT.invokeEdgeFunction.code({+ name: resource,+ endpoint: `${endpoint}`,+ apikey: apikey,+ })}+ />+ </div>+ )+}++export default Bucketdiff --git a/studio/components/interfaces/ProjectAPIDocs/Content/EdgeFunctions.tsx b/studio/components/interfaces/ProjectAPIDocs/Content/EdgeFunctions.tsxnew file mode 100644index 00000000000..c3ed52dfdb1--- /dev/null+++ b/studio/components/interfaces/ProjectAPIDocs/Content/EdgeFunctions.tsx@@ -0,0 +1,16 @@+import ContentSnippet from '../ContentSnippet'+import { DOCS_CONTENT } from '../ProjectAPIDocs.constants'+import { ContentProps } from './Content.types'++const EdgeFunctions = ({ language }: ContentProps) => {+ return (+ <>+ <ContentSnippet selectedLanguage={language} snippet={DOCS_CONTENT.edgeFunctions} />+ <ContentSnippet selectedLanguage={language} snippet={DOCS_CONTENT.edgeFunctionsPreReq} />+ <ContentSnippet selectedLanguage={language} snippet={DOCS_CONTENT.createEdgeFunction} />+ <ContentSnippet selectedLanguage={language} snippet={DOCS_CONTENT.deployEdgeFunction} />+ </>+ )+}++export default EdgeFunctionsdiff --git a/studio/components/interfaces/ProjectAPIDocs/Content/Entities.tsx b/studio/components/interfaces/ProjectAPIDocs/Content/Entities.tsxnew file mode 100644index 00000000000..885ed3beba9--- /dev/null+++ b/studio/components/interfaces/ProjectAPIDocs/Content/Entities.tsx@@ -0,0 +1,76 @@+import { useParams } from 'common'+import Link from 'next/link'+import { useState } from 'react'+import { Button, IconDownload, IconExternalLink } from 'ui'++import { generateTypes } from 'data/projects/project-type-generation-query'+import { useStore } from 'hooks'+import ContentSnippet from '../ContentSnippet'+import { DOCS_CONTENT } from '../ProjectAPIDocs.constants'+import { ContentProps } from './Content.types'++const Entities = ({ language }: ContentProps) => {+ const { ui } = useStore()+ const { ref } = useParams()++ 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 (+ <>+ <ContentSnippet selectedLanguage={language} snippet={DOCS_CONTENT.entitiesIntroduction} />+ <div>+ <ContentSnippet selectedLanguage={language} snippet={DOCS_CONTENT.generatingTypes} />+ <div className="flex items-center space-x-2 px-4 mt-3">+ <Link href="https://supabase.com/docs/guides/database/api/generating-types">+ <Button asChild type="default" icon={<IconExternalLink />}>+ <a target="_blank" rel="noreferrer">+ Documentation+ </a>+ </Button>+ </Link>+ <Button+ type="default"+ disabled={isGeneratingTypes}+ loading={isGeneratingTypes}+ icon={<IconDownload strokeWidth={1.5} />}+ onClick={onClickGenerateTypes}+ >+ Generate and download types+ </Button>+ </div>+ <p className="text-xs text-foreground-light px-4 mt-2">+ Remember to re-generate and download this file as you make changes to your tables.+ </p>+ </div>+ <ContentSnippet selectedLanguage={language} snippet={DOCS_CONTENT.graphql} />+ </>+ )+}++export default Entitiesdiff --git a/studio/components/interfaces/ProjectAPIDocs/Content/Entity.tsx b/studio/components/interfaces/ProjectAPIDocs/Content/Entity.tsxnew file mode 100644index 00000000000..ffbae3be487--- /dev/null+++ b/studio/components/interfaces/ProjectAPIDocs/Content/Entity.tsx@@ -0,0 +1,135 @@+import { useParams } from 'common'++import Table from 'components/to-be-cleaned/Table'+import { useProjectJsonSchemaQuery } from 'data/docs/project-json-schema-query'+import { useAppStateSnapshot } from 'state/app-state'+import { DOCS_RESOURCE_CONTENT } from '../ProjectAPIDocs.constants'+import ResourceContent from '../ResourceContent'+import { ContentProps } from './Content.types'++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 type+ }+}++const Entity = ({ language, apikey = '', endpoint = '' }: ContentProps) => {+ const { ref } = useParams()+ const snap = useAppStateSnapshot()+ const resource = snap.activeDocsSection[1]++ const { data: jsonSchema } = useProjectJsonSchemaQuery({ projectRef: ref })+ const definition = jsonSchema?.definitions?.[resource]+ const columns =+ definition !== undefined+ ? Object.entries(definition.properties).map(([id, val]: any) => ({+ ...val,+ id,+ required: definition.required.includes(id),+ }))+ : []++ if (resource === undefined) return null++ return (+ <div className="divide-y">+ <div className="space-y-1 px-4 py-6">+ <h2 className="text-xl">{resource}</h2>+ <p className="text-sm text-foreground-light">+ {definition?.description ?? 'No description available'}+ </p>+ </div>+ <div className="space-y-2 px-4 py-4">+ <p className="text-sm text-foreground-light">Columns</p>+ <Table+ head={[+ <Table.th key="name">Name</Table.th>,+ <Table.th key="format">Format</Table.th>,+ <Table.th key="type">Type</Table.th>,+ <Table.th key="description">Description</Table.th>,+ ]}+ body={columns.map((column) => {+ const formattedColumnType = getColumnType(column.type, column.format)+ return (+ <Table.tr key={column.id}>+ <Table.td title={column.id}>{column.id}</Table.td>+ <Table.td title={column.format}>+ <p className="truncate">{column.format}</p>+ </Table.td>+ <Table.td title={formattedColumnType}>{formattedColumnType}</Table.td>+ <Table.td title={column.description}>{column.description ?? ''}</Table.td>+ </Table.tr>+ )+ })}+ />+ </div>++ <ResourceContent+ selectedLanguage={language}+ snippet={DOCS_RESOURCE_CONTENT.readRows}+ codeSnippets={DOCS_RESOURCE_CONTENT.readRows.code({+ resourceId: resource,+ endpoint,+ apikey,+ })}+ />+ <ResourceContent+ selectedLanguage={language}+ snippet={DOCS_RESOURCE_CONTENT.filtering}+ codeSnippets={DOCS_RESOURCE_CONTENT.filtering.code({+ resourceId: resource,+ endpoint,+ apikey,+ })}+ />+ <ResourceContent+ selectedLanguage={language}+ snippet={DOCS_RESOURCE_CONTENT.insertRows}+ codeSnippets={DOCS_RESOURCE_CONTENT.insertRows.code({+ resourceId: resource,+ endpoint,+ apikey,+ })}+ />+ <ResourceContent+ selectedLanguage={language}+ snippet={DOCS_RESOURCE_CONTENT.updateRows}+ codeSnippets={DOCS_RESOURCE_CONTENT.updateRows.code({+ resourceId: resource,+ endpoint,+ apikey,+ })}+ />+ <ResourceContent+ selectedLanguage={language}+ snippet={DOCS_RESOURCE_CONTENT.deleteRows}+ codeSnippets={DOCS_RESOURCE_CONTENT.deleteRows.code({+ resourceId: resource,+ endpoint,+ apikey,+ })}+ />+ <ResourceContent+ selectedLanguage={language}+ snippet={DOCS_RESOURCE_CONTENT.subscribeChanges}+ codeSnippets={DOCS_RESOURCE_CONTENT.subscribeChanges.code({ resourceId: resource })}+ />+ </div>+ )+}++export default Entitydiff --git a/studio/components/interfaces/ProjectAPIDocs/Content/Introduction.tsx b/studio/components/interfaces/ProjectAPIDocs/Content/Introduction.tsxnew file mode 100644index 00000000000..c308dd63ba1--- /dev/null+++ b/studio/components/interfaces/ProjectAPIDocs/Content/Introduction.tsx@@ -0,0 +1,115 @@+import { useParams } from 'common'+import { Button, IconCopy, Input } from 'ui'++import { useProjectApiQuery } from 'data/config/project-api-query'+import ContentSnippet from '../ContentSnippet'+import { DOCS_CONTENT } from '../ProjectAPIDocs.constants'+import { ContentProps } from './Content.types'+import { copyToClipboard } from 'lib/helpers'+import { useEffect, useState } from 'react'++const Introduction = ({ showKeys, language, apikey, endpoint }: ContentProps) => {+ const { ref } = useParams()+ const { data } = useProjectApiQuery({ projectRef: ref })++ const [copied, setCopied] = useState<'anon' | 'service'>()++ useEffect(() => {+ if (copied !== undefined) setTimeout(() => setCopied(undefined), 2000)+ }, [copied])++ const serviceKey = showKeys+ ? data?.autoApiService.serviceApiKey ?? 'SUPABASE_CLIENT_SERVICE_KEY'+ : 'SUPABASE_CLIENT_SERVICE_KEY'++ return (+ <>+ <ContentSnippet+ selectedLanguage={language}+ apikey={apikey}+ endpoint={endpoint}+ snippet={DOCS_CONTENT.init}+ >+ <div className="px-4 space-y-6">+ <div className="flex space-x-4 mt-8">+ <p className="text-sm w-40">Project URL</p>+ <Input disabled readOnly copy size="small" value={endpoint} className="w-full" />+ </div>+ <div className="flex space-x-4">+ <p className="text-sm w-40">Client API key</p>+ <Input+ disabled+ readOnly+ size="small"+ value={showKeys ? apikey : 'Reveal API keys via dropdown in the header'}+ className="w-full"+ descriptionText="This key is safe to use in a browser if you have enabled Row Level Security (RLS) for your tables and configured policies."+ actions={[+ <Button+ key="copy"+ type="default"+ icon={<IconCopy />}+ onClick={() => {+ setCopied('anon')+ copyToClipboard(+ data?.autoApiService.defaultApiKey ?? 'SUPABASE_CLIENT_ANON_KEY'+ )+ }}+ >+ {copied === 'anon' ? 'Copied' : 'Copy'}+ </Button>,+ ]}+ />+ </div>+ <div className="flex space-x-4">+ <p className="text-sm w-40 mb-16">Service key</p>+ <Input+ disabled+ readOnly+ size="small"+ value={showKeys ? serviceKey : 'Reveal API keys via dropdown in the header'}+ className="w-full"+ descriptionText={+ <p>+ This key has the ability to bypass Row Level Security.{' '}+ <span className="text-amber-900">Never share it publicly.</span>+ </p>+ }+ actions={[+ <Button+ key="copy"+ type="default"+ icon={<IconCopy />}+ onClick={() => {+ setCopied('service')+ copyToClipboard(+ data?.autoApiService.serviceApiKey ?? 'SUPABASE_CLIENT_SERVICE_KEY'+ )+ }}+ >+ {copied === 'service' ? 'Copied' : 'Copy'}+ </Button>,+ ]}+ />+ </div>+ </div>+ </ContentSnippet>++ <ContentSnippet+ selectedLanguage={language}+ apikey={apikey}+ endpoint={endpoint}+ snippet={DOCS_CONTENT.clientApiKeys}+ />++ <ContentSnippet+ selectedLanguage={language}+ apikey={serviceKey}+ endpoint={endpoint}+ snippet={DOCS_CONTENT.serviceApiKeys}+ />+ </>+ )+}++export default Introductiondiff --git a/studio/components/interfaces/ProjectAPIDocs/Content/RPC.tsx b/studio/components/interfaces/ProjectAPIDocs/Content/RPC.tsxnew file mode 100644index 00000000000..e1432cec2b6--- /dev/null+++ b/studio/components/interfaces/ProjectAPIDocs/Content/RPC.tsx@@ -0,0 +1,77 @@+import { useParams } from 'common'+import { Badge } from 'ui'++import Table from 'components/to-be-cleaned/Table'+import { useProjectJsonSchemaQuery } from 'data/docs/project-json-schema-query'+import { useOpenAPISpecQuery } from 'data/open-api/api-spec-query'+import { useAppStateSnapshot } from 'state/app-state'+import { DOCS_RESOURCE_CONTENT } from '../ProjectAPIDocs.constants'+import ResourceContent from '../ResourceContent'+import { ContentProps } from './Content.types'++const RPC = ({ language }: ContentProps) => {+ const { ref } = useParams()+ const snap = useAppStateSnapshot()++ const { data: jsonSchema } = useProjectJsonSchemaQuery({ projectRef: ref })+ const { data } = useOpenAPISpecQuery({ projectRef: ref })+ const functions = data?.functions ?? []++ const rpcName = snap.activeDocsSection[1]+ const rpc = functions.find((fn) => fn.name === rpcName)+ const rpcJsonSchema = jsonSchema?.paths[rpc?.path]++ const summary = rpcJsonSchema?.post.summary+ const parameters = rpc?.get.parameters ?? []++ if (rpc === undefined) return null++ return (+ <div className="divide-y">+ <div className="space-y-1 px-4 py-6">+ <h2 className="text-xl">{rpc.name}</h2>+ <p className="text-sm text-foreground-light">{summary ?? 'No description available'}</p>+ </div>+ <div className="space-y-2 px-4 py-4">+ <p className="text-sm text-foreground-light">Function arguments</p>+ <Table+ head={[+ <Table.th key="name">Name</Table.th>,+ <Table.th key="format">Format</Table.th>,+ <Table.th key="type">Type</Table.th>,+ <Table.th key="required"></Table.th>,+ ]}+ body={parameters.map((parameter: any) => (+ <Table.tr key={parameter.name}>+ <Table.td title={parameter.name}>+ <p className="font-mono text-xs text-foreground truncate">{parameter.name}</p>+ </Table.td>+ <Table.td title={parameter.format}>{parameter.format}</Table.td>+ <Table.td title={parameter.type}>{parameter.type}</Table.td>+ <Table.td>+ {parameter.required ? (+ <Badge color="amber">Required</Badge>+ ) : (+ <p className="text-foreground-light">Optional</p>+ )}+ </Table.td>+ </Table.tr>+ ))}+ />+ </div>+ <ResourceContent+ selectedLanguage={language}+ snippet={DOCS_RESOURCE_CONTENT.rpcSingle}+ codeSnippets={DOCS_RESOURCE_CONTENT.rpcSingle.code({+ rpcName,+ rpcParams: parameters,+ endpoint: 'endpoint',+ apiKey: 'apiKey',+ showBearer: true,+ })}+ />+ </div>+ )+}++export default RPCdiff --git a/studio/components/interfaces/ProjectAPIDocs/Content/Realtime.tsx b/studio/components/interfaces/ProjectAPIDocs/Content/Realtime.tsxnew file mode 100644index 00000000000..abf69033170--- /dev/null+++ b/studio/components/interfaces/ProjectAPIDocs/Content/Realtime.tsx@@ -0,0 +1,17 @@+import ContentSnippet from '../ContentSnippet'+import { DOCS_CONTENT } from '../ProjectAPIDocs.constants'+import { ContentProps } from './Content.types'++const Realtime = ({ language }: ContentProps) => {+ return (+ <>+ <ContentSnippet selectedLanguage={language} snippet={DOCS_CONTENT.realtime} />+ <ContentSnippet selectedLanguage={language} snippet={DOCS_CONTENT.subscribeChannel} />+ <ContentSnippet selectedLanguage={language} snippet={DOCS_CONTENT.unsubscribeChannel} />+ <ContentSnippet selectedLanguage={language} snippet={DOCS_CONTENT.unsubscribeChannels} />+ <ContentSnippet selectedLanguage={language} snippet={DOCS_CONTENT.retrieveAllChannels} />+ </>+ )+}++export default Realtimediff --git a/studio/components/interfaces/ProjectAPIDocs/Content/Storage.tsx b/studio/components/interfaces/ProjectAPIDocs/Content/Storage.tsxnew file mode 100644index 00000000000..c9a76f5c415--- /dev/null+++ b/studio/components/interfaces/ProjectAPIDocs/Content/Storage.tsx@@ -0,0 +1,13 @@+import ContentSnippet from '../ContentSnippet'+import { DOCS_CONTENT } from '../ProjectAPIDocs.constants'+import { ContentProps } from './Content.types'++const Storage = ({ language }: ContentProps) => {+ return (+ <>+ <ContentSnippet selectedLanguage={language} snippet={DOCS_CONTENT.storage} />+ </>+ )+}++export default Storagediff --git a/studio/components/interfaces/ProjectAPIDocs/Content/StoredProcedures.tsx b/studio/components/interfaces/ProjectAPIDocs/Content/StoredProcedures.tsxnew file mode 100644index 00000000000..977e88a777d--- /dev/null+++ b/studio/components/interfaces/ProjectAPIDocs/Content/StoredProcedures.tsx@@ -0,0 +1,16 @@+import ContentSnippet from '../ContentSnippet'+import { DOCS_CONTENT } from '../ProjectAPIDocs.constants'+import { ContentProps } from './Content.types'++const StoredProcedures = ({ language }: ContentProps) => {+ return (+ <>+ <ContentSnippet+ selectedLanguage={language}+ snippet={DOCS_CONTENT.storedProceduresIntroduction}+ />+ </>+ )+}++export default StoredProceduresdiff --git a/studio/components/interfaces/ProjectAPIDocs/Content/UserManagement.tsx b/studio/components/interfaces/ProjectAPIDocs/Content/UserManagement.tsxnew file mode 100644index 00000000000..4f75a2c2663--- /dev/null+++ b/studio/components/interfaces/ProjectAPIDocs/Content/UserManagement.tsx@@ -0,0 +1,85 @@+import ContentSnippet from '../ContentSnippet'+import { DOCS_CONTENT } from '../ProjectAPIDocs.constants'+import { ContentProps } from './Content.types'++const UserManagement = ({ language, apikey, endpoint }: ContentProps) => {+ return (+ <>+ <ContentSnippet selectedLanguage={language} snippet={DOCS_CONTENT.userManagement} />+ <ContentSnippet+ selectedLanguage={language}+ apikey={apikey}+ endpoint={endpoint}+ snippet={DOCS_CONTENT.signUp}+ />+ <ContentSnippet+ selectedLanguage={language}+ apikey={apikey}+ endpoint={endpoint}+ snippet={DOCS_CONTENT.emailLogin}+ />+ <ContentSnippet+ selectedLanguage={language}+ apikey={apikey}+ endpoint={endpoint}+ snippet={DOCS_CONTENT.magicLinkLogin}+ />+ <ContentSnippet+ selectedLanguage={language}+ apikey={apikey}+ endpoint={endpoint}+ snippet={DOCS_CONTENT.phoneLogin}+ />+ <ContentSnippet+ selectedLanguage={language}+ apikey={apikey}+ endpoint={endpoint}+ snippet={DOCS_CONTENT.smsLogin}+ />+ <ContentSnippet+ selectedLanguage={language}+ apikey={apikey}+ endpoint={endpoint}+ snippet={DOCS_CONTENT.smsVerify}+ />+ <ContentSnippet+ selectedLanguage={language}+ apikey={apikey}+ endpoint={endpoint}+ snippet={DOCS_CONTENT.oauthLogin}+ />+ <ContentSnippet+ selectedLanguage={language}+ apikey={apikey}+ endpoint={endpoint}+ snippet={DOCS_CONTENT.user}+ />+ <ContentSnippet+ selectedLanguage={language}+ apikey={apikey}+ endpoint={endpoint}+ snippet={DOCS_CONTENT.forgotPassWordEmail}+ />+ <ContentSnippet+ selectedLanguage={language}+ apikey={apikey}+ endpoint={endpoint}+ snippet={DOCS_CONTENT.updateUser}+ />+ <ContentSnippet+ selectedLanguage={language}+ apikey={apikey}+ endpoint={endpoint}+ snippet={DOCS_CONTENT.logout}+ />+ <ContentSnippet+ selectedLanguage={language}+ apikey={apikey}+ endpoint={endpoint}+ snippet={DOCS_CONTENT.emailInvite}+ />+ </>+ )+}++export default UserManagementdiff --git a/studio/components/interfaces/ProjectAPIDocs/Content/index.ts b/studio/components/interfaces/ProjectAPIDocs/Content/index.tsnew file mode 100644index 00000000000..7b2e4fe7d59--- /dev/null+++ b/studio/components/interfaces/ProjectAPIDocs/Content/index.ts@@ -0,0 +1,26 @@+import EdgeFunctions from './EdgeFunctions'+import Entities from './Entities'+import Introduction from './Introduction'+import Realtime from './Realtime'+import Storage from './Storage'+import StoredProcedures from './StoredProcedures'+import UserManagement from './UserManagement'++import Bucket from './Bucket'+import EdgeFunction from './EdgeFunction'+import Entity from './Entity'+import RPC from './RPC'++export {+ Bucket,+ EdgeFunction,+ EdgeFunctions,+ Entities,+ Entity,+ Introduction,+ RPC,+ Realtime,+ Storage,+ StoredProcedures,+ UserManagement,+}diff --git a/studio/components/interfaces/ProjectAPIDocs/ContentSnippet.tsx b/studio/components/interfaces/ProjectAPIDocs/ContentSnippet.tsxnew file mode 100644index 00000000000..a21840d3975--- /dev/null+++ b/studio/components/interfaces/ProjectAPIDocs/ContentSnippet.tsx@@ -0,0 +1,60 @@+import { useParams } from 'common'++import SimpleCodeBlock from 'components/to-be-cleaned/SimpleCodeBlock'+import { Markdown } from '../Markdown'+import { PropsWithChildren } from 'react'++interface ContentSnippetProps {+ apikey?: string+ endpoint?: string+ selectedLanguage: 'js' | 'bash'+ snippet: {+ key: string+ category: string+ title: string+ description?: string+ js?: (apikey?: string, endpoint?: string) => string+ bash?: (apikey?: string, endpoint?: string) => string+ }+}++const ContentSnippet = ({+ apikey,+ endpoint,+ selectedLanguage,+ snippet,+ children,+}: PropsWithChildren<ContentSnippetProps>) => {+ const { ref: projectRef } = useParams()+ const codeSnippet = snippet[selectedLanguage]?.(apikey, endpoint).replaceAll(+ '[ref]',+ projectRef ?? ''+ )++ return (+ <div id={snippet.key} className="space-y-4 py-6 pb-2 last:pb-6">+ <div className="px-4 space-y-4">+ <h2 className="doc-heading">{snippet.title}</h2>+ {snippet.description !== undefined && (+ <div className="doc-section">+ <article className="text text-sm text-light">+ <Markdown+ className="max-w-none"+ content={snippet.description.replaceAll('[ref]', projectRef ?? '_')}+ />+ </article>+ </div>+ )}+ </div>+ {children}+ {codeSnippet !== undefined && (+ <div className="px-4 codeblock-container">+ <div className="bg rounded p-2">+ <SimpleCodeBlock className={selectedLanguage}>{codeSnippet}</SimpleCodeBlock>+ </div>+ </div>+ )}+ </div>+ )+}+export default ContentSnippetdiff --git a/studio/components/interfaces/ProjectAPIDocs/FirstLevelNav.tsx b/studio/components/interfaces/ProjectAPIDocs/FirstLevelNav.tsxnew file mode 100644index 00000000000..3b86f39dbf9--- /dev/null+++ b/studio/components/interfaces/ProjectAPIDocs/FirstLevelNav.tsx@@ -0,0 +1,147 @@+import { useParams } from 'common'+import Link from 'next/link'+import { Fragment } from 'react'+import { Button, IconBook, IconBookOpen } from 'ui'++import { useEdgeFunctionsQuery } from 'data/edge-functions/edge-functions-query'+import { useOpenAPISpecQuery } from 'data/open-api/api-spec-query'+import { useBucketsQuery } from 'data/storage/buckets-query'+import { useAppStateSnapshot } from 'state/app-state'+import { navigateToSection } from './Content/Content.utils'+import { DOCS_CONTENT, DOCS_MENU } from './ProjectAPIDocs.constants'++const Separator = () => <div className="border-t !mt-3 pb-1 mx-3" />++const FirstLevelNav = () => {+ const { ref } = useParams()+ const snap = useAppStateSnapshot()++ const { data } = useOpenAPISpecQuery({ projectRef: ref })+ const tables = data?.tables ?? []+ const functions = data?.functions ?? []++ const { data: buckets } = useBucketsQuery({ projectRef: ref })+ const { data: edgeFunctions } = useEdgeFunctionsQuery({ projectRef: ref })++ return (+ <>+ <div className="px-2 py-4 border-b">+ {DOCS_MENU.map((item) => {+ const isActive = snap.activeDocsSection[0] === item.key+ const sections = Object.values(DOCS_CONTENT).filter(+ (snippet) => snippet.category === item.key+ )++ // [Joshen] Need to find the right UI component for accessbility+ return (+ <Fragment key={item.key}>+ <div+ className={`cursor-pointer text-sm py-2 px-3 rounded-md transition ${+ isActive ? 'bg-surface-300' : ''+ }`}+ onClick={() => snap.setActiveDocsSection([item.key])}+ >+ {item.name}+ </div>+ {isActive && sections.length > 0 && (+ <div className="space-y-2 py-2">+ {sections.map((section) => (+ <p+ key={section.key}+ title={section.title}+ className="text-sm text-light px-4 hover:text-foreground transition cursor-pointer"+ onClick={() => {+ snap.setActiveDocsSection([item.key])+ navigateToSection(section.key)+ }}+ >+ {section.title}+ </p>+ ))}+ {item.key === 'entities' && (+ <>+ {tables.length > 0 && <Separator />}+ {tables.map((table) => (+ <p+ key={table.name}+ title={table.name}+ className="text-sm text-light px-4 hover:text-foreground transition cursor-pointer"+ onClick={() => snap.setActiveDocsSection([item.key, table.name])}+ >+ {table.name}+ </p>+ ))}+ </>+ )}+ {item.key === 'stored-procedures' && (+ <>+ {functions.length > 0 && <Separator />}+ {functions.map((fn) => (+ <p+ key={fn.name}+ title={fn.name}+ className="text-sm text-light px-4 hover:text-foreground transition cursor-pointer"+ onClick={() => snap.setActiveDocsSection([item.key, fn.name])}+ >+ {fn.name}+ </p>+ ))}+ </>+ )}+ {item.key === 'storage' && (+ <>+ {(buckets ?? []).length > 0 && <Separator />}+ {(buckets ?? []).map((bucket) => (+ <p+ key={bucket.name}+ title={bucket.name}+ className="text-sm text-light px-4 hover:text-foreground transition cursor-pointer"+ onClick={() => snap.setActiveDocsSection([item.key, bucket.name])}+ >+ {bucket.name}+ </p>+ ))}+ </>+ )}+ {item.key === 'edge-functions' && (+ <>+ {(edgeFunctions ?? []).length > 0 && <Separator />}+ {(edgeFunctions ?? []).map((fn) => (+ <p+ key={fn.name}+ title={fn.name}+ className="text-sm text-light px-4 hover:text-foreground transition cursor-pointer"+ onClick={() => snap.setActiveDocsSection([item.key, fn.name])}+ >+ {fn.name}+ </p>+ ))}+ </>+ )}+ </div>+ )}+ </Fragment>+ )+ })}+ </div>+ <div className="px-2 py-4">+ <Link passHref href="https://supabase.com/docs">+ <Button block asChild type="text" size="small" icon={<IconBook />}>+ <a target="_blank" rel="noreferrer" className="!justify-start">+ Documentation+ </a>+ </Button>+ </Link>+ <Link passHref href="https://supabase.com/docs/guides/api">+ <Button block asChild type="text" size="small" icon={<IconBookOpen />}>+ <a target="_blank" rel="noreferrer" className="!justify-start">+ API Reference+ </a>+ </Button>+ </Link>+ </div>+ </>+ )+}++export default FirstLevelNavdiff --git a/studio/components/interfaces/ProjectAPIDocs/ProjectAPIDocs.constants.ts b/studio/components/interfaces/ProjectAPIDocs/ProjectAPIDocs.constants.tsnew file mode 100644index 00000000000..6147433e2ae--- /dev/null+++ b/studio/components/interfaces/ProjectAPIDocs/ProjectAPIDocs.constants.ts@@ -0,0 +1,1191 @@+export const DOCS_MENU = [+ { name: 'Connect', key: 'introduction' },+ { name: 'User Management', key: 'user-management' },+ { name: 'Tables & Views', key: 'entities' },+ { name: 'Stored Procedures', key: 'stored-procedures' },+ { name: 'Storage', key: 'storage' },+ { name: 'Edge Functions', key: 'edge-functions' },+ { name: 'Realtime', key: 'realtime' },+]++export const DOCS_CONTENT = {+ init: {+ key: 'introduction',+ category: 'introduction',+ title: `Connect to your project`,+ description: `Projects have a RESTful endpoint that you can use with your project's API key to query and manage your database. Put these keys in your .env file.`,+ js: (apikey?: string, endpoint?: string) => `+import { createClient } from '@supabase/supabase-js'++const supabaseUrl = '${endpoint}'+const supabaseKey = process.env.SUPABASE_KEY+const supabase = createClient(supabaseUrl, supabaseKey)`,+ bash: () => `# No client library required for Bash.`,+ },+ clientApiKeys: {+ key: 'client-api-keys',+ category: 'introduction',+ title: `Client API Keys`,+ description: `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.++In this documentation, we will refer to the key using the name \`SUPABASE_KEY\`. You can find the \`anon\` key in the [API settings](/project/[ref]/settings/api) page.`,+ js: (apikey?: string, endpoint?: string) => `+const SUPABASE_KEY = '${apikey}'+const SUPABASE_URL = '${endpoint}'+const supabase = createClient(SUPABASE_URL, process.env.SUPABASE_KEY);`,+ bash: (apikey?: string, endpoint?: string) => `${apikey}`,+ },+ serviceApiKeys: {+ key: 'service-keys',+ category: 'introduction',+ title: `Service Keys`,+ description: `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.++In this documentation, we refer to the key using the name \`SERVICE_KEY\`. You can find the \`service_role\` key above or in the [API settings](/project/[ref]/settings/api) page.`,+ js: (apikey?: string, endpoint?: string) => `+const SUPABASE_KEY = '${apikey}'+const SUPABASE_URL = 'https://${endpoint}'+const supabase = createClient(SUPABASE_URL, process.env.SUPABASE_KEY);`,+ bash: (apikey?: string, endpoint?: string) => `${apikey}`,+ },+ // User Management+ userManagement: {+ key: 'user-management',+ category: 'user-management',+ title: `Introduction`,+ description: `Supabase makes it easy to manage your users.++ Supabase assigns each user a unique ID. You can reference this ID anywhere in your database. For example, you might create a \`profiles\` table references the user using a \`user_id\` field.++ Supabase already has built in the routes to sign up, login, and log out for managing users in your apps and websites.`,+ js: undefined,+ bash: undefined,+ },+ signUp: {+ key: 'sign-up',+ category: 'user-management',+ title: `Sign up`,+ description: `Allow your users to sign up and create a new account++ After they have signed up, all interactions using the Supabase client will be performed as "that user".`,+ js: (apikey?: string, endpoint?: string) => `+let { data, error } = await supabase.auth.signUp({+ email: '[email protected]',+ password: 'some-secure-password'+})`,+ bash: (apikey?: string, endpoint?: string) => `+curl -X POST '${endpoint}/auth/v1/signup' \\+-H "apikey: ${apikey}" \\+-H "Content-Type: application/json" \\+-d '{+ "email": "[email protected]",+ "password": "some-secure-password"+}'`,+ },+ emailLogin: {+ key: 'email-login',+ category: 'user-management',+ title: `Log in with Email/Password`,+ description: `+If an account is created, users can login to your app.++After they have logged in, all interactions using the Supabase JS client will be performed as "that user".`,+ js: (apikey?: string, endpoint?: string) => `+let { data, error } = await supabase.auth.signInWithPassword({+ email: '[email protected]',+ password: 'some-secure-password'+})+ `,+ bash: (apikey?: string, endpoint?: string) => `+curl -X POST '${endpoint}/auth/v1/token?grant_type=password' \\+-H "apikey: ${apikey}" \\+-H "Content-Type: application/json" \\+-d '{+ "email": "[email protected]",+ "password": "some-secure-password"+}'+ `,+ },+ magicLinkLogin: {+ key: 'magic-link-login',+ category: 'user-management',+ title: `Log in with Magic Link via Email`,+ description: `+Send a user a passwordless link which they can use to redeem an access_token.++After they have clicked the link, all interactions using the Supabase JS client will be performed as "that user".`,+ js: (apikey?: string, endpoint?: string) => `+let { data, error } = await supabase.auth.signInWithOtp({+ email: '[email protected]'+})+ `,+ bash: (apikey?: string, endpoint?: string) => `+curl -X POST '${endpoint}/auth/v1/magiclink' \\+-H "apikey: ${apikey}" \\+-H "Content-Type: application/json" \\+-d '{+ "email": "[email protected]"+}'+ `,+ },+ phoneLogin: {+ key: 'phone-log-in',+ category: 'user-management',+ title: `Sign up with Phone/Password`,+ description: `+A phone number can be used instead of an email as a primary account confirmation mechanism.++The user will receive a mobile OTP via sms with which they can verify that they control the phone number.++You must enter your own twilio credentials on the auth settings page to enable sms confirmations.`,+ js: (apikey?: string, endpoint?: string) => `+let { data, error } = await supabase.auth.signUp({+ phone: '+13334445555',+ password: 'some-password'+})+ `,+ bash: (apikey?: string, endpoint?: string) => `+curl -X POST '${endpoint}/auth/v1/signup' \\+-H "apikey: ${apikey}" \\+-H "Content-Type: application/json" \\+-d '{+ "phone": "+13334445555",+ "password": "some-password"+}'+ `,+ },+ smsLogin: {+ key: 'sms-otp-log-in',+ category: 'user-management',+ title: `Login via SMS OTP`,+ description: `+SMS OTPs work like magic links, except you have to provide an interface for the user to verify the 6 digit number they receive.++You must enter your own twilio credentials on the auth settings page to enable SMS-based Logins.`,+ js: (apikey?: string, endpoint?: string) => `+let { data, error } = await supabase.auth.signInWithOtp({+ phone: '+13334445555'+})+ `,+ bash: (apikey?: string, endpoint?: string) => `+curl -X POST '${endpoint}/auth/v1/otp' \\+-H "apikey: ${apikey}" \\+-H "Content-Type: application/json" \\+-d '{+ "phone": "+13334445555"+}'+ `,+ },+ smsVerify: {+ key: 'sms-verify',+ category: 'user-management',+ title: `Verify an SMS OTP`,+ description: `+Once the user has received the OTP, have them enter it in a form and send it for verification++You must enter your own twilio credentials on the auth settings page to enable SMS-based OTP verification.`,+ js: (apikey?: string, endpoint?: string) => `+let { data, error } = await supabase.auth.verifyOtp({+ phone: '+13334445555',+ token: '123456',+ type: 'sms'+})+ `,+ bash: (apikey?: string, endpoint?: string) => `+curl -X POST '${endpoint}/auth/v1/verify' \\+-H "apikey: ${apikey}" \\+-H "Content-Type: application/json" \\+-d '{+ "type": "sms",+ "phone": "+13334445555",+ "token": "123456"+}'+ `,+ },+ oauthLogin: {+ key: 'oauth-login',+ category: 'user-management',+ title: `Log in with Third Party OAuth`,+ description: `+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 [here](https://supabase.com).++View all the available [Third Party OAuth providers](https://supabase.com).++After they have logged in, all interactions using the Supabase JS client will be performed as "that user".++Generate your Client ID and secret from: [Google](https://console.developers.google.com/apis/credentials), [Github](https://github.com/settings/applications/new), [Gitlab](https://gitlab.com/oauth/applications), [Facebook](https://developers.facebook.com/apps), and [Bitbucket](https://support.atlassian.com/bitbucket-cloud/docs/use-oauth-on-bitbucket-cloud).`,+ js: (apikey?: string, endpoint?: string) => `+let { data, error } = await supabase.auth.signInWithOAuth({+ provider: 'github'+})+ `,+ bash: (apikey?: string, endpoint?: string) => `No available command`,+ },+ user: {+ key: 'get-user',+ category: 'user-management',+ title: `Get user`,+ description: `Get the JSON object for the logged in user.`,+ js: (apikey?: string, endpoint?: string) => `+const { data: { user } } = await supabase.auth.getUser()+ `,+ bash: (apikey?: string, endpoint?: string) => `+curl -X GET '${endpoint}/auth/v1/user' \\+-H "apikey: ${apikey}" \\+-H "Authorization: Bearer USER_TOKEN"+ `,+ },+ forgotPassWordEmail: {+ key: 'forgot-password-email',+ category: 'user-management',+ title: `Forgot password / email`,+ description: `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.`,+ js: (apikey?: string, endpoint?: string) => `+let { data, error } = await supabase.auth.resetPasswordForEmail(email)+ `,+ bash: (apikey?: string, endpoint?: string) => `+curl -X POST '${endpoint}/auth/v1/recover' \\+-H "apikey: ${apikey}" \\+-H "Content-Type: application/json" \\+-d '{+"email": "[email protected]"+}'+`,+ },+ updateUser: {+ key: 'update-user',+ category: 'user-management',+ title: `Update User`,+ description: `Update the user with a new email or password. Each key (email, password, and data) is optional.`,+ js: (apikey?: string, endpoint?: string) => `+const { data, error } = await supabase.auth.updateUser({+ email: "[email protected]",+ password: "new-password",+ data: { hello: 'world' }+})+ `,+ bash: (apikey?: string, endpoint?: string) => `+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"+}+}'+`,+ },+ logout: {+ key: 'log-out',+ category: 'user-management',+ title: `Log out`,+ description: `After calling log out, all interactions using the Supabase JS client will be "anonymous".`,+ js: (apikey?: string, endpoint?: string) => `+let { error } = await supabase.auth.signOut()+ `,+ bash: (apikey?: string, endpoint?: string) => `+curl -X POST '${endpoint}/auth/v1/logout' \\+-H "apikey: ${apikey}" \\+-H "Content-Type: application/json" \\+-H "Authorization: Bearer USER_TOKEN"+ `,+ },+ emailInvite: {+ key: 'email-invite',+ category: 'user-management',+ title: `Invite user over email`,+ description: `+Send a user a passwordless link which they can use to sign up and log in.++After they have clicked the link, all interactions using the Supabase JS client will be performed as "that user".++This endpoint requires you use the \`service_role_key\` when initializing the client, and should only be invoked from the server, never from the client.`,+ js: (apikey?: string, endpoint?: string) => `+let { data, error } = await supabase.auth.api.inviteUserByEmail('[email protected]')+ `,+ bash: (apikey?: string, endpoint?: string) => `+curl -X POST '${endpoint}/auth/v1/invite' \\+-H "apikey: ${apikey}" \\+-H "Authorization: Bearer ${apikey}" \\+-H "Content-Type: application/json" \\+-d '{+ "email": "[email protected]"+}'+ `,+ },+ // Storage+ storage: {+ key: 'storage',+ category: 'storage',+ title: `Introduction`,+ description: `Supabase Storage makes it simple to upload and serve files of any size, providing a robust framework for file access controls.++You can use Supabase Storage to store images, videos, documents, and any other file type. Serve your assets with a global CDN to reduce latency from over 285 cities globally. Supabase Storage includes a built-in image optimizer, so you can resize and compress your media files on the fly.`,+ js: undefined,+ bash: undefined,+ },+ // Edge functions+ edgeFunctions: {+ key: 'edge-function',+ category: 'edge-functions',+ title: 'Introduction',+ description: `+Edge Functions are server-side TypeScript functions, distributed globally at the edge—close to your users. They can be used for listening to webhooks or integrating your Supabase project with third-parties like Stripe. Edge Functions are developed using Deno, which offers a few benefits to you as a developer:+`,+ js: undefined,+ bash: undefined,+ },+ edgeFunctionsPreReq: {+ key: 'edge-function-pre-req',+ category: 'edge-functions',+ title: 'Pre-requisites',+ description: `+Follow the steps to prepare your Supabase project on your local machine.++- Install the Supabase [CLI](https://supabase.com/docs/guides/cli).+- [Login to the CLI](https://supabase.com/docs/reference/cli/usage#supabase-login) using the command: \`supabase login\`..+- [Initialize Supabase](https://supabase.com/docs/guides/getting-started/local-development#getting-started) inside your project using the command: \`supabase init\`..+- [Link to your Remote Project](https://supabase.com/docs/reference/cli/usage#supabase-link) using the command \`supabase link --project-ref [ref]\`..+- Setup your environment: Follow the steps [here](https://supabase.com/docs/guides/functions/quickstart#setting-up-your-environment).+`,+ js: undefined,+ bash: undefined,+ },+ createEdgeFunction: {+ key: 'create-edge-function',+ category: 'edge-functions',+ title: 'Create an Edge Function',+ description: `+Create a Supabase Edge Function locally via the Supabase CLI.+`,+ js: () => `// Create an edge function via the Supabase CLI`,+ bash: () => `+supabase functions new hello-world+`,+ },+ deployEdgeFunction: {+ key: 'deploy-edge-function',+ category: 'edge-functions',+ title: 'Deploy an Edge Function',+ description: `+Deploy a Supabase Edge Function to your Supabase project via the Supabase CLI.+`,+ js: () => `// Deploy an edge function via the Supabase CLI`,+ bash: () => `supabase functions deploy hello-world --project-ref [ref]+`,+ },+ // Entities+ entitiesIntroduction: {+ key: 'entities-introduction',+ category: 'entities',+ title: 'Introduction',+ description: `+All views and tables in the \`public\` schema, and those accessible by the active database role for a request are available for querying via the API.++If you don't want to expose tables in your API, simply add them to a different schema (not the \`public\` schema).+`,+ js: undefined,+ bash: undefined,+ },+ generatingTypes: {+ key: 'generating-types',+ category: 'entities',+ title: 'Generating Types',+ description: `+Supabase APIs are generated from your database, which means that we can use database introspection to generate type-safe API definitions.++You can generate types from your database either through the [Supabase CLI](https://supabase.com/docs/guides/database/api/generating-types), or by downloading the types file via the button on the right and importing it in your application within \`src/index.ts\`.+`,+ js: undefined,+ bash: undefined,+ },+ graphql: {+ key: 'graphql',+ category: 'entities',+ title: 'GraphQL vs Supabase',+ description: `+If you have a GraphQL background, you might be wonering if you can fetch your data in a single round-trip. The answer is yes! The syntax is very similar. This example shows how you might achieve the same thing with Apollo GraphQL and Supabase.++Still want GraphQL?+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 [in the settings](/project/[ref]/settings/database).+`,+ js: (apikey?: string, endpoint?: string) => `+// With Apollo GraphQL+const { loading, error, data } = useQuery(gql\`+ query GetDogs {+ dogs {+ id+ breed+ owner {+ id+ name+ }+ }+ }+ \`)++// With Supabase+const { data, error } = await supabase+ .from('dogs')+ .select(\`+ id, breed,+ owner (id, name)+ \`)+`,+ bash: (apikey?: string, endpoint?: string) => `+// With Apollo GraphQL+const { loading, error, data } = useQuery(gql\`+ query GetDogs {+ dogs {+ id+ breed+ owner {+ id+ name+ }+ }+ }+ \`)++// With Supabase+const { data, error } = await supabase+ .from('dogs')+ .select(\`+ id, breed,+ owner (id, name)+ \`)+ `,+ },+ // Stored Procedures+ storedProceduresIntroduction: {+ key: 'stored-procedures-introduction',+ category: 'stored-procedures',+ title: 'Introduction',+ description: `+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)!++The API endpoint supports POST (and in some cases GET) to execute the function.+`,+ js: undefined,+ bash: undefined,+ },+ // Realtime+ realtime: {+ key: 'realtime-introduction',+ category: 'realtime',+ title: 'Introduction',+ description: `+Supabase provides a globally distributed cluster of Realtime servers that enable the following functionality:++- [Broadcast](https://supabase.com/docs/guides/realtime/broadcast): Send ephemeral messages from client to clients with low latency.+- [Presence](https://supabase.com/docs/guides/realtime/presence): Track and synchronize shared state between clients.+- [Postgres Changes](https://supabase.com/docs/guides/realtime/postgres-changes): Listen to Postgres database changes and send them to authorized clients.+`,+ js: undefined,+ bash: undefined,+ },+ subscribeChannel: {+ key: 'subscribe-to-channel',+ category: 'realtime',+ title: 'Subscribe to channel',+ description: `+Creates an event handler that listens to changes.++- By default, Broadcast and Presence are enabled for all projects.+- By default, listening to database changes is disabled for new projects due to database performance and security concerns. You can turn it on by managing Realtime's [replication](https://supabase.com/docs/guides/api#realtime-api-overview).+- You can receive the "previous" data for updates and deletes by setting the table's \`REPLICA IDENTITY\` to \`FULL\` (e.g., \`ALTER TABLE your_table REPLICA IDENTITY FULL;\`).+- Row level security is not applied to delete statements. When RLS is enabled and replica identity is set to full, only the primary key is sent to clients.+`,+ js: () => `+supabase+ .channel('any')+ .on('broadcast', { event: 'cursor-pos' }, payload => {+ console.log('Cursor position received!', payload)+ })+ .subscribe((status) => {+ if (status === 'SUBSCRIBED') {+ channel.send({+ type: 'broadcast',+ event: 'cursor-pos',+ payload: { x: Math.random(), y: Math.random() },+ })+ }+ })+ `,+ bash: () => `# Realtime streams are only supported by our client libraries`,+ },+ unsubscribeChannel: {+ key: 'unsubscribe-channel',+ category: 'realtime',+ title: 'Unsubscribe from a channel',+ description: `+Unsubscribes and removes Realtime channel from Realtime client.++Removing a channel is a great way to maintain the performance of your project's Realtime service as well as your database if you're listening to Postgres changes. Supabase will automatically handle cleanup 30 seconds after a client is disconnected, but unused channels may cause degradation as more clients are simultaneously subscribed.+`,+ js: () => `supabase.removeChannel(myChannel)`,+ bash: () => `# Realtime streams are only supported by our client libraries`,+ },+ unsubscribeChannels: {+ key: 'unsubscribe-channels',+ category: 'realtime',+ title: 'Unsubscribe from all channels',+ description: `+Unsubscribes and removes all Realtime channels from Realtime client.++Removing a channel is a great way to maintain the performance of your project's Realtime service as well as your database if you're listening to Postgres changes. Supabase will automatically handle cleanup 30 seconds after a client is disconnected, but unused channels may cause degradation as more clients are simultaneously subscribed.+`,+ js: () => `supabase.removeChannels()`,+ bash: () => `# Realtime streams are only supported by our client libraries`,+ },+ retrieveAllChannels: {+ key: 'unsubscribe-channel',+ category: 'realtime',+ title: 'Unsubscribe from a channel',+ description: `+Returns all Realtime channels.+`,+ js: () => `const channels = supabase.getChannels()`,+ bash: () => `# Realtime streams are only supported by our client libraries`,+ },+}++export const DOCS_RESOURCE_CONTENT: {+ [key: string]: {+ key: string+ title: string+ category: string+ description?: string+ docsUrl: string+ code: (props: any) => { key: string; title?: string; bash: string; js: string }[]+ }+} = {+ rpcSingle: {+ key: 'invoke-function',+ title: 'Invoke function',+ category: 'stored-procedures',+ description: undefined,+ docsUrl: 'https://supabase.com/docs/reference/javascript/rpc',+ code: ({+ 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 [+ {+ key: 'rpc-single',+ title: undefined,+ bash: `+ curl -X POST '${endpoint}/rest/v1/rpc/${rpcName}' \\${bashParams}+ -H "Content-Type: application/json" \\+ -H "apikey: ${apiKey}" ${+ showBearer+ ? `\\+ -H "Authorization: Bearer ${apiKey}"`+ : ''+ }+ `,+ js: `+let { data, error } = await supabase+ .rpc('${rpcName}'${jsParams})++if (error) console.error(error)+else console.log(data)+ `,+ },+ ]+ },+ },+ readRows: {+ key: 'read-rows',+ title: `Read rows`,+ category: 'entities',+ docsUrl: 'https://supabase.com/docs/reference/javascript/select',+ description: `To read rows in this table, use the \`select\` method.`,+ code: ({+ resourceId,+ endpoint,+ apikey,+ }: {+ resourceId: string+ endpoint: string+ apikey: string+ }) => {+ return [+ {+ key: 'read-all-rows',+ title: 'Read all rows',+ bash: `+curl '${endpoint}/rest/v1/${resourceId}?select=*' \\+-H "apikey: ${apikey}" \\+-H "Authorization: Bearer ${apikey}"+ `,+ js: `+let { data: ${resourceId}, error } = await supabase+ .from('${resourceId}')+ .select('*')+ `,+ },+ {+ key: 'read-specific-columns',+ title: 'Read specific columns',+ bash: `+curl '${endpoint}/rest/v1/${resourceId}?select=some_column,other_column' \\+-H "apikey: ${apikey}" \\+-H "Authorization: Bearer ${apikey}"+ `,+ js: `+let { data: ${resourceId}, error } = await supabase+ .from('${resourceId}')+ .select('some_column,other_column')+ `,+ },+ {+ key: 'read-foreign-tables',+ title: 'Read foreign tables',+ bash: `+curl '${endpoint}/rest/v1/${resourceId}?select=some_column,other_table(foreign_key)' \\+-H "apikey: ${apikey}" \\+-H "Authorization: Bearer ${apikey}"+ `,+ js: `+let { data: ${resourceId}, error } = await supabase+ .from('${resourceId}')+ .select(\`+ some_column,+ other_table (+ foreign_key+ )+ \`)+ `,+ },+ {+ key: 'with-pagination',+ title: 'With pagination',+ bash: `+curl '${endpoint}/rest/v1/${resourceId}?select=*' \\+-H "apikey: ${apikey}" \\+-H "Authorization: Bearer ${apikey}" \\+-H "Range: 0-9"+ `,+ js: `+let { data: ${resourceId}, error } = await supabase+ .from('${resourceId}')+ .select('*')+ .range(0, 9)+ `,+ },+ ]+ },+ },+ filtering: {+ key: 'filter-rows',+ category: 'entities',+ title: 'Filtering',+ description: `Supabase provides a wide range of filters`,+ docsUrl: 'https://supabase.com/docs/reference/javascript/using-filters',+ code: ({+ resourceId,+ endpoint,+ apikey,+ }: {+ resourceId: string+ endpoint: string+ apikey: string+ }) => {+ return [+ {+ key: 'with-filtering',+ title: 'With filtering',+ bash: `+curl '${endpoint}/rest/v1/${resourceId}?id=eq.1&select=*' \\+-H "apikey: ${apikey}" \\+-H "Authorization: Bearer ${apikey}" \\+-H "Range: 0-9"+ `,+ js: `+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'])+ `,+ },+ ]+ },+ },+ insertRows: {+ key: 'insert-rows',+ category: 'entities',+ title: 'Insert rows',+ description: `+\`insert\` lets you insert into your tables. You can also insert in bulk and do UPSERT.++\`insert\` will also return the replaced values for UPSERT.+`,+ docsUrl: 'https://supabase.com/docs/reference/javascript/insert',+ code: ({+ resourceId,+ endpoint,+ apikey,+ }: {+ resourceId: string+ endpoint: string+ apikey: string+ }) => {+ return [+ {+ key: 'insert-a-row',+ title: 'Insert a row',+ bash: `+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: `+const { data, error } = await supabase+ .from('${resourceId}')+ .insert([+ { some_column: 'someValue', other_column: 'otherValue' },+ ])+ .select()+ `,+ },+ {+ key: 'insert-many-rows',+ title: 'Insert many rows',+ bash: `+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: `+const { data, error } = await supabase+ .from('${resourceId}')+ .insert([+ { some_column: 'someValue' },+ { some_column: 'otherValue' },+ ])+ .select()+ `,+ },+ {+ key: 'upsert-matching-rows',+ title: 'Upsert matching rows',+ bash: `+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: `+const { data, error } = await supabase+ .from('${resourceId}')+ .upsert({ some_column: 'someValue' })+ .select()+ `,+ },+ ]+ },+ },+ updateRows: {+ key: 'update-rows',+ category: 'entities',+ title: 'Update rows',+ description: `+\`update\` lets you update rows. \`update\` will match all rows by default. You can update specific rows using horizontal filters, e.g. \`eq\`, \`lt\`, and \`is\`.++\`update\` will also return the replaced values for UPDATE.+`,+ docsUrl: 'https://supabase.com/docs/reference/javascript/update',+ code: ({+ resourceId,+ endpoint,+ apikey,+ }: {+ resourceId: string+ endpoint: string+ apikey: string+ }) => {+ return [+ {+ key: 'update-matching-rows',+ title: 'Update matching rows',+ bash: `+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: `+const { data, error } = await supabase+ .from('${resourceId}')+ .update({ other_column: 'otherValue' })+ .eq('some_column', 'someValue')+ .select()+ `,+ },+ ]+ },+ },+ deleteRows: {+ key: 'delete-rows',+ category: 'entities',+ title: 'Delete rows',+ description: `+\`delete\` lets you delete rows. \`delete\` will match all rows by default, so remember to specify your filters!+`,+ docsUrl: 'https://supabase.com/docs/reference/javascript/delete',+ code: ({+ resourceId,+ endpoint,+ apikey,+ }: {+ resourceId: string+ endpoint: string+ apikey: string+ }) => {+ return [+ {+ key: 'delete-matching-rows',+ title: 'Delete matching rows',+ bash: `+curl -X DELETE '${endpoint}/rest/v1/${resourceId}?some_column=eq.someValue' \\+-H "apikey: ${apikey}" \\+-H "Authorization: Bearer ${apikey}"+ `,+ js: `+const { error } = await supabase+ .from('${resourceId}')+ .delete()+ .eq('some_column', 'someValue')+ `,+ },+ ]+ },+ },+ subscribeChanges: {+ key: 'subscribe-changes',+ category: 'entities',+ title: 'Subscribe to changes',+ description: `+Supabase provides realtime functionality and broadcasts database changes to authorized users depending on Row Level Security (RLS) policies.+`,+ docsUrl: 'https://supabase.com/docs/reference/javascript/subscribe',+ code: ({ resourceId }: { resourceId: string }) => {+ return [+ {+ key: 'subscribe-all-events',+ title: 'Subscribe to all events',+ bash: `# Realtime streams are only supported by our client libraries`,+ js: `+const channels = supabase.channel('custom-all-channel')+ .on(+ 'postgres_changes',+ { event: '*', schema: 'public', table: '${resourceId}' },+ (payload) => {+ console.log('Change received!', payload)+ }+ )+ .subscribe()`,+ },+ {+ key: 'subscribe-to-inserts',+ title: 'Subscribe to inserts',+ bash: `# Realtime streams are only supported by our client libraries`,+ js: `+const channels = supabase.channel('custom-insert-channel')+ .on(+ 'postgres_changes',+ { event: 'INSERT', schema: 'public', table: '${resourceId}' },+ (payload) => {+ console.log('Change received!', payload)+ }+ )+ .subscribe()`,+ },+ {+ key: 'subscribe-to-updates',+ title: 'Subscribe to updates',+ bash: `# Realtime streams are only supported by our client libraries`,+ js: `+const channels = supabase.channel('custom-update-channel')+ .on(+ 'postgres_changes',+ { event: 'UPDATE', schema: 'public', table: '${resourceId}' },+ (payload) => {+ console.log('Change received!', payload)+ }+ )+ .subscribe()`,+ },+ {+ key: 'subscribe-to-deletes',+ title: 'Subscribe to deletes',+ bash: `# Realtime streams are only supported by our client libraries`,+ js: `+const channels = supabase.channel('custom-delete-channel')+ .on(+ 'postgres_changes',+ { event: 'DELETE', schema: 'public', table: '${resourceId}' },+ (payload) => {+ console.log('Change received!', payload)+ }+ )+ .subscribe()`,+ },+ {+ key: 'subscribe-to-specific-rows',+ title: 'Subscribe to specific rows',+ bash: `# Realtime streams are only supported by our client libraries`,+ js: `+const channels = supabase.channel('custom-filter-channel')+ .on(+ 'postgres_changes',+ { event: '*', schema: 'public', table: '${resourceId}', filter: 'some_column=eq.some_value' },+ (payload) => {+ console.log('Change received!', payload)+ }+ )+ .subscribe()`,+ },+ ]+ },+ },+ uploadFile: {+ key: 'upload-file',+ category: 'storage',+ title: 'Upload a file',+ docsUrl: 'https://supabase.com/docs/reference/javascript/storage-from-upload',+ description: `+Upload a file to an existing bucket. RLS policy permissions required:+- \`buckets\` table permissions: none+- \`objects\` table permissions: only \`insert\` when you are uploading new files and \`select\`, \`insert\`, and \`update\` when you are upserting files.+`,+ code: ({ name }: { name: string }) => [+ {+ key: 'storage-upload-file',+ title: undefined,+ bash: `# No command via bash available`,+ js: `+const avatarFile = event.target.files[0]+const { data, error } = await supabase+ .storage+ .from('${name}')+ .upload('folder/avatar1.png', avatarFile, {+ cacheControl: '3600',+ upsert: false+ })+`,+ },+ ],+ },+ deleteFiles: {+ key: 'delete-files',+ category: 'storage',+ title: 'Delete files',+ docsUrl: 'https://supabase.com/docs/reference/javascript/storage-from-remove',+ description: `+Delete files within the bucket. RLS policy permissions required:+- \`buckets\` table permissions: none+- \`objects\` table permissions: \`delete\` and \`select\`+`,+ code: ({ name }: { name: string }) => [+ {+ key: 'storage-delete-files',+ title: undefined,+ bash: `# No command via bash available`,+ js: `+const { data, error } = await supabase+ .storage+ .from('${name}')+ .remove(['folder/avatar1.png'])+ `,+ },+ ],+ },+ listFiles: {+ key: 'list-files',+ category: 'storage',+ title: 'List all files',+ docsUrl: 'https://supabase.com/docs/reference/javascript/storage-from-list',+ description: `+List all files within the bucket. RLS policy permissions required:+- \`buckets\` table permissions: none+- \`objects\` table permissions: \`select\`+`,+ code: ({ name }: { name: string }) => [+ {+ key: 'storage-list-files',+ title: undefined,+ bash: `# No command via bash available`,+ js: `+const { data, error } = await supabase+ .storage+ .from('${name}')+ .list('folder', {+ limit: 100,+ offset: 0,+ sortBy: { column: 'name', order: 'asc' },+ })+ `,+ },+ ],+ },+ downloadFile: {+ key: 'download-file',+ category: 'storage',+ title: 'Download a file',+ docsUrl: 'https://supabase.com/docs/reference/javascript/storage-from-download',+ description: `+Downloads a file from a private bucket. For public buckets, make a request to the URL returned from getPublicUrl instead. RLS policy permissions required:+- \`buckets\` table permissions: none+- \`objects\` table permissions: \`select\`+`,+ code: ({ name }: { name: string }) => [+ {+ key: 'storage-download-file',+ title: undefined,+ bash: `# No command via bash available`,+ js: `+const { data, error } = await supabase+ .storage+ .from('avatars')+ .download('folder/avatar1.png')+ `,+ },+ ],+ },+ createSignedURL: {+ key: 'create-signed-url',+ category: 'storage',+ title: 'Create a signed URL',+ docsUrl: 'https://supabase.com/docs/reference/javascript/storage-from-createsignedurl',+ description: `+Create a signed URL which can be used to share a file for a fixed amount of time. RLS policy permissions required:+- \`buckets\` table permissions: none+- \`objects\` table permissions: \`select\`+`,+ code: ({ name }: { name: string }) => [+ {+ key: 'storage-create-signed-url',+ title: undefined,+ bash: `# No command via bash available`,+ js: `+const { data, error } = await supabase+ .storage+ .from('${name}')+ .createSignedUrl('folder/avatar1.png', 60)+ `,+ },+ ],+ },+ retrievePublicURL: {+ key: 'retrieve-public-url',+ category: 'storage',+ title: 'Retrieve public URL',+ docsUrl: 'https://supabase.com/docs/reference/javascript/storage-from-getpublicurl',+ description: `+A simple convenience function to get the URL for an asset in a public bucket. If you do not want to use this function, you can construct the public URL by concatenating the bucket URL with the path to the asset.++This function does not verify if the bucket is public. If a public URL is created for a bucket which is not public, you will not be able to download the asset.++The bucket needs to be set to public, either via updateBucket() or by going to Storage on supabase.com/dashboard, clicking the overflow menu on a bucket and choosing "Make public"++RLS policy permissions required:+- \`buckets\` table permissions: none+- \`objects\` table permissions: none+`,+ code: ({ name }: { name: string }) => [+ {+ key: 'storage-retrieve-public-url',+ title: undefined,+ bash: `# No command via bash available`,+ js: `+const { data } = supabase+ .storage+ .from('${name}')+ .getPublicUrl('folder/avatar1.png')+ `,+ },+ ],+ },+ invokeEdgeFunction: {+ key: 'invoke-edge-function',+ category: 'edge-functions',+ title: 'Invoke an edge function',+ docsUrl: 'https://supabase.com/docs/reference/javascript/functions-invoke',+ description: `+Invokes a Supabase Edge Function. Requires an Authorization header, and invoke params generally match the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) spec.++When you pass in a body to your function, we automatically attach the \`Content-Type\` header for \`Blob\`, \`ArrayBuffer\`, \`File\`, \`FormData\` and \`String\`. If it doesn't match any of these types we assume the payload is \`json\`, serialize it and attach the \`Content-Type\` header as \`application/json\`. You can override this behavior by passing in a \`Content-Type\` header of your own.++Responses are automatically parsed as \`json\`, \`blob\` and \`form-data\` depending on the \`Content-Type\` header sent by your function. Responses are parsed as \`text\` by default.+`,+ code: ({ name, endpoint, apikey }: { name: string; endpoint: string; apikey: string }) => [+ {+ key: 'invoke-edge-function',+ title: undefined,+ bash: `+curl --request POST '${endpoint}/functions/v1/${name}' \\+--header 'Authorization: Bearer ${apikey}' \\+--header 'Content-Type: application/json' \\+--data '{ "name": "Functions" }'+ `,+ js: `+const { data, error } = await supabase+ .functions+ .invoke('${name}', {+ body: { foo: 'bar' }+ })`,+ },+ ],+ },+}diff --git a/studio/components/interfaces/ProjectAPIDocs/ProjectAPIDocs.tsx b/studio/components/interfaces/ProjectAPIDocs/ProjectAPIDocs.tsxnew file mode 100644index 00000000000..4a08358912c--- /dev/null+++ b/studio/components/interfaces/ProjectAPIDocs/ProjectAPIDocs.tsx@@ -0,0 +1,184 @@+import { useState } from 'react'+import {+ Button,+ CommandGroup_Shadcn_,+ CommandItem_Shadcn_,+ CommandList_Shadcn_,+ Command_Shadcn_,+ IconTerminal,+ PopoverContent_Shadcn_,+ PopoverTrigger_Shadcn_,+ Popover_Shadcn_,+ SidePanel,+} from 'ui'++import { useParams } from 'common'+import { useProjectApiQuery } from 'data/config/project-api-query'+import { useCustomDomainsQuery } from 'data/custom-domains/custom-domains-query'+import { BASE_PATH } from 'lib/constants'+import { useAppStateSnapshot } from 'state/app-state'+import {+ Bucket,+ EdgeFunction,+ EdgeFunctions,+ Entities,+ Entity,+ Introduction,+ RPC,+ Realtime,+ Storage,+ StoredProcedures,+ UserManagement,+} from './Content'+import FirstLevelNav from './FirstLevelNav'+import SecondLevelNav from './SecondLevelNav'++const ProjectAPIDocs = () => {+ const { ref } = useParams()+ const snap = useAppStateSnapshot()++ const [openLanguage, setOpenLanguage] = useState(false)+ const [showKeys, setShowKeys] = useState(false)+ const [language, setLanguage] = useState<'js' | 'bash'>('js')++ const { data } = useProjectApiQuery({ projectRef: ref })+ const { data: customDomainData } = useCustomDomainsQuery({ projectRef: ref })++ const apikey = showKeys+ ? data?.autoApiService.defaultApiKey ?? 'SUPABASE_CLIENT_ANON_KEY'+ : 'SUPABASE_CLIENT_ANON_KEY'+ const endpoint =+ customDomainData?.customDomain?.status === 'active'+ ? `https://${customDomainData.customDomain?.hostname}/auth/v1/callback`+ : `https://${data?.autoApiService.endpoint ?? ''}`++ const updateLanguage = (value: 'js' | 'bash') => {+ setLanguage(value)+ setOpenLanguage(false)+ }++ return (+ <SidePanel+ hideFooter+ size="xxlarge"+ className="max-w-5xl"+ visible={snap.showProjectApiDocs}+ onCancel={() => snap.setShowProjectApiDocs(false)}+ >+ <div className="flex items-start h-full">+ <div className="w-64 border-r h-full">+ <div className="border-b px-4 py-2 flex items-center justify-between">+ <h4>API Docs</h4>+ <div className="flex items-center space-x-1">+ <Popover_Shadcn_ open={openLanguage} onOpenChange={setOpenLanguage} modal={false}>+ <PopoverTrigger_Shadcn_ asChild>+ <Button+ type="default"+ className="px-1"+ icon={+ language === 'js' ? (+ <img+ src={`${BASE_PATH}/img/libraries/javascript-icon.svg`}+ alt={`javascript logo`}+ width="14"+ />+ ) : (+ <IconTerminal size={14} strokeWidth={2.5} />+ )+ }+ />+ </PopoverTrigger_Shadcn_>+ <PopoverContent_Shadcn_ className="p-0 w-24" side="bottom" align="end">+ <Command_Shadcn_>+ <CommandList_Shadcn_>+ <CommandGroup_Shadcn_>+ <CommandItem_Shadcn_+ className="cursor-pointer"+ onSelect={() => updateLanguage('js')}+ onClick={() => updateLanguage('js')}+ >+ <p>Javascript</p>+ </CommandItem_Shadcn_>+ <CommandItem_Shadcn_+ className="cursor-pointer"+ onSelect={() => updateLanguage('bash')}+ onClick={() => updateLanguage('bash')}+ >+ <p>Bash</p>+ </CommandItem_Shadcn_>+ </CommandGroup_Shadcn_>+ </CommandList_Shadcn_>+ </Command_Shadcn_>+ </PopoverContent_Shadcn_>+ </Popover_Shadcn_>+ <Button type="default" onClick={() => setShowKeys(!showKeys)}>+ {showKeys ? 'Hide keys' : 'Show keys'}+ </Button>+ </div>+ </div>++ {snap.activeDocsSection.length === 1 ? <FirstLevelNav /> : <SecondLevelNav />}+ </div>++ <div className="flex-1 divide-y space-y-4 max-h-screen overflow-auto px-4">+ {snap.activeDocsSection[0] === 'introduction' && (+ <Introduction+ showKeys={showKeys}+ language={language}+ apikey={apikey}+ endpoint={endpoint}+ />+ )}++ {snap.activeDocsSection[0] === 'user-management' && (+ <UserManagement language={language} apikey={apikey} endpoint={endpoint} />+ )}++ {snap.activeDocsSection[0] === 'realtime' && <Realtime language={language} />}++ {snap.activeDocsSection[0] === 'storage' && (+ <>+ {snap.activeDocsSection[1] !== undefined ? (+ <Bucket language={language} />+ ) : (+ <Storage language={language} />+ )}+ </>+ )}++ {snap.activeDocsSection[0] === 'edge-functions' && (+ <>+ {snap.activeDocsSection[1] !== undefined ? (+ <EdgeFunction language={language} apikey={apikey} endpoint={endpoint} />+ ) : (+ <EdgeFunctions language={language} />+ )}+ </>+ )}++ {snap.activeDocsSection[0] === 'entities' && (+ <>+ {snap.activeDocsSection[1] !== undefined ? (+ <Entity language={language} apikey={apikey} endpoint={endpoint} />+ ) : (+ <Entities language={language} />+ )}+ </>+ )}++ {snap.activeDocsSection[0] === 'stored-procedures' && (+ <>+ {snap.activeDocsSection[1] !== undefined ? (+ <RPC language={language} />+ ) : (+ <StoredProcedures language={language} />+ )}+ </>+ )}+ </div>+ </div>+ </SidePanel>+ )+}++export default ProjectAPIDocsdiff --git a/studio/components/interfaces/ProjectAPIDocs/ResourceContent.tsx b/studio/components/interfaces/ProjectAPIDocs/ResourceContent.tsxnew file mode 100644index 00000000000..c78fd29ebc5--- /dev/null+++ b/studio/components/interfaces/ProjectAPIDocs/ResourceContent.tsx@@ -0,0 +1,63 @@+import { useParams } from 'common'+import Link from 'next/link'+import { Button, IconExternalLink } from 'ui'++import SimpleCodeBlock from 'components/to-be-cleaned/SimpleCodeBlock'+import { Markdown } from '../Markdown'++interface ResourceContentProps {+ selectedLanguage: 'js' | 'bash'+ snippet: {+ key: string+ title: string+ description?: string+ docsUrl?: string+ }+ codeSnippets: any[]+}++const ResourceContent = ({ selectedLanguage, snippet, codeSnippets }: ResourceContentProps) => {+ const { ref: projectRef } = useParams()++ return (+ <div id={snippet.key} className="space-y-4 py-6">+ <div className="px-4 space-y-2">+ <div className="flex items-center justify-between">+ <h2 className="doc-heading">{snippet.title}</h2>+ {snippet.docsUrl !== undefined && (+ <Link passHref href={snippet.docsUrl}>+ <Button asChild type="default" icon={<IconExternalLink />}>+ <a target="_blank" rel="noreferrer">+ Documentation+ </a>+ </Button>+ </Link>+ )}+ </div>+ {snippet.description !== undefined && (+ <div className="doc-section">+ <article className="text text-sm text-light">+ <Markdown+ className="max-w-none"+ content={snippet.description.replaceAll('[ref]', projectRef ?? '_')}+ />+ </article>+ </div>+ )}+ </div>+ {codeSnippets.map((codeSnippet) => (+ <div key={codeSnippet.key} className="px-4 space-y-2">+ <p className="text-sm text-foreground-light">{codeSnippet.title}</p>+ <div className="codeblock-container">+ <div className="bg rounded p-2">+ <SimpleCodeBlock className={selectedLanguage}>+ {codeSnippet[selectedLanguage]}+ </SimpleCodeBlock>+ </div>+ </div>+ </div>+ ))}+ </div>+ )+}+export default ResourceContentdiff --git a/studio/components/interfaces/ProjectAPIDocs/SecondLevelNav.tsx b/studio/components/interfaces/ProjectAPIDocs/SecondLevelNav.tsxnew file mode 100644index 00000000000..bc6d86273a6--- /dev/null+++ b/studio/components/interfaces/ProjectAPIDocs/SecondLevelNav.tsx@@ -0,0 +1,173 @@+import { useParams } from 'common'+import Link from 'next/link'+import { useState } from 'react'+import {+ AlertDescription_Shadcn_,+ AlertTitle_Shadcn_,+ Alert_Shadcn_,+ Button,+ CommandGroup_Shadcn_,+ CommandItem_Shadcn_,+ CommandList_Shadcn_,+ Command_Shadcn_,+ IconChevronLeft,+ IconCode,+ IconExternalLink,+ PopoverContent_Shadcn_,+ PopoverTrigger_Shadcn_,+ Popover_Shadcn_,+} from 'ui'++import { useEdgeFunctionsQuery } from 'data/edge-functions/edge-functions-query'+import { useOpenAPISpecQuery } from 'data/open-api/api-spec-query'+import { useBucketsQuery } from 'data/storage/buckets-query'+import { useAppStateSnapshot } from 'state/app-state'+import { navigateToSection } from './Content/Content.utils'+import { DOCS_RESOURCE_CONTENT } from './ProjectAPIDocs.constants'++const SecondLevelNav = () => {+ const { ref } = useParams()+ const snap = useAppStateSnapshot()+ const [open, setOpen] = useState(false)++ const { data } = useOpenAPISpecQuery({ projectRef: ref })+ const tables = data?.tables ?? []+ const functions = data?.functions ?? []+ const [section, resource] = snap.activeDocsSection++ const { data: buckets } = useBucketsQuery({ projectRef: ref })+ const { data: edgeFunctions } = useEdgeFunctionsQuery({ projectRef: ref })+ const bucket = (buckets ?? []).find((b) => b.name === resource)++ const content: { [key: string]: { title: string; options: any[]; docsUrl: string } } = {+ entities: {+ title: 'Tables & Views',+ options: tables,+ docsUrl: 'https://supabase.com/docs/reference/javascript/select',+ },+ 'stored-procedures': {+ title: 'Stored Procedures',+ options: functions,+ docsUrl: 'https://supabase.com/docs/reference/javascript/rpc',+ },+ storage: {+ title: 'Storage',+ options: buckets ?? [],+ docsUrl: 'https://supabase.com/docs/reference/javascript/storage-createbucket',+ },+ 'edge-functions': {+ title: 'Edge Functions',+ options: edgeFunctions ?? [],+ docsUrl: 'https://supabase.com/docs/reference/javascript/functions-invoke',+ },+ }++ const updateSection = (value: string) => {+ snap.setActiveDocsSection([snap.activeDocsSection[0], value])+ setOpen(false)+ }++ const menuItems = Object.values(DOCS_RESOURCE_CONTENT).filter(+ (content) => content.category === snap.activeDocsSection[0]+ )++ return (+ <div className="py-4 space-y-2">+ <div className="px-2 flex items-center space-x-2">+ <Button+ type="text"+ icon={<IconChevronLeft />}+ className="px-1"+ onClick={() => snap.setActiveDocsSection([snap.activeDocsSection[0]])}+ />+ <p className="text-sm text-foreground-light capitalize">{content[section].title}</p>+ </div>+ <Popover_Shadcn_ open={open} onOpenChange={setOpen} modal={false}>+ <PopoverTrigger_Shadcn_ asChild>+ <div className="px-2">+ <Button block type="default" size="small" className="[&>span]:w-full">+ <div>+ <div className="flex items-center justify-between w-full">+ <p>{snap.activeDocsSection[1]}</p>+ <div>+ <IconCode className="rotate-90" strokeWidth={1.5} size={12} />+ </div>+ </div>+ </div>+ </Button>+ </div>+ </PopoverTrigger_Shadcn_>+ <PopoverContent_Shadcn_ className="p-0" side="bottom" align="start">+ <Command_Shadcn_>+ <CommandList_Shadcn_>+ <CommandGroup_Shadcn_>+ {content[section].options.map((option) => (+ <CommandItem_Shadcn_+ key={option.name}+ className="cursor-pointer"+ onSelect={() => updateSection(option.name)}+ onClick={() => updateSection(option.name)}+ >+ <p>{option.name}</p>+ </CommandItem_Shadcn_>+ ))}+ </CommandGroup_Shadcn_>+ </CommandList_Shadcn_>+ </Command_Shadcn_>+ </PopoverContent_Shadcn_>+ </Popover_Shadcn_>++ <div className="px-2 space-y-2 py-2">+ {menuItems.map((item) => {+ if (section === 'storage' && bucket !== undefined) {+ if (+ (!bucket.public && item.key === 'retrieve-public-url') ||+ (bucket.public && item.key === 'create-signed-url')+ )+ return null+ }+ return (+ <p+ key={item.key}+ title={item.title}+ className="text-sm text-light px-4 hover:text-foreground transition cursor-pointer"+ onClick={() => navigateToSection(item.key)}+ >+ {item.title}+ </p>+ )+ })}+ </div>++ <div className="px-4 py-4 border-t space-y-2">+ <Alert_Shadcn_ className="p-3">+ <AlertTitle_Shadcn_>+ <p className="text-xs">Unable to find what you're looking for?</p>+ </AlertTitle_Shadcn_>+ <AlertDescription_Shadcn_ className="space-y-1">+ <p className="text-xs !leading-normal">+ The API methods shown here are only the commonly used ones to get you started building+ quickly.+ </p>+ <p className="text-xs !leading-normal">+ Head over to our docs site for the full API documentation.+ </p>+ <Link passHref href={content[section].docsUrl}>+ <Button+ asChild+ className="!mt-2"+ size="tiny"+ type="default"+ icon={<IconExternalLink strokeWidth={1.5} />}+ >+ <a>Documentation</a>+ </Button>+ </Link>+ </AlertDescription_Shadcn_>+ </Alert_Shadcn_>+ </div>+ </div>+ )+}++export default SecondLevelNavdiff --git a/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsx b/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsxindex bb2d6d21376..64632c88c5b 100644--- a/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsx+++ b/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsx@@ -2,29 +2,23 @@ import * as Tooltip from '@radix-ui/react-tooltip'import type { PostgresPolicy, PostgresTable } from '@supabase/postgres-meta'import { PermissionAction } from '@supabase/shared-types/out/constants'import { useParams } from 'common'+import { MousePointer2 } from 'lucide-react'import Link from 'next/link'import { useEffect, useRef, useState } from 'react'-import { Button, IconAlertCircle, IconCode, IconLock, IconZap, IconZapOff, Modal } from 'ui'+import { Button, IconAlertCircle, IconCode, IconLock, Modal } from 'ui'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 { MousePointer2 } from 'lucide-react'export interface GridHeaderActionsProps {table: PostgresTable- apiPreviewPanelOpen: boolean- setApiPreviewPanelOpen: (apiPreviewPanelOpen: boolean) => void+ openAPIDocsPanel: () => voidrefreshDocs: () => void}-const GridHeaderActions = ({- table,- apiPreviewPanelOpen,- setApiPreviewPanelOpen,- refreshDocs,-}: GridHeaderActionsProps) => {+const GridHeaderActions = ({ table, openAPIDocsPanel, refreshDocs }: GridHeaderActionsProps) => {const { ref } = useParams()const { meta, ui } = useStore()const { project } = useProjectContext()@@ -69,8 +63,8 @@ const GridHeaderActions = ({return () => rlsAcknowledgedChannel.current.close()}, [rlsKey])- function handlePreviewToggle() {- setApiPreviewPanelOpen(!apiPreviewPanelOpen)+ function openAPIDocs() {+ openAPIDocsPanel()refreshDocs()}@@ -80,7 +74,7 @@ const GridHeaderActions = ({size="tiny"type="default"icon={<IconCode size={14} strokeWidth={2} />}- onClick={handlePreviewToggle}+ onClick={openAPIDocs}>API</Button>diff --git a/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx b/studio/components/interfaces/TableGridEditor/TableGridEditor.tsxindex 1ba1504284c..ef2a0b1c97b 100644--- a/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx+++ b/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx@@ -1,12 +1,12 @@import type { PostgresColumn, PostgresRelationship, PostgresTable } from '@supabase/postgres-meta'import { PermissionAction } from '@supabase/shared-types/out/constants'import { QueryKey, useQueryClient } from '@tanstack/react-query'+import { useParams } from 'common'import { find, isUndefined } from 'lodash'import { observer } from 'mobx-react-lite'import { useRouter } from 'next/router'import { useEffect, useRef, useState } from 'react'-import { useParams } from 'common'import {Dictionary,parseSupaTable,@@ -32,8 +32,10 @@ import useEntityType from 'hooks/misc/useEntityType'import { TableLike } from 'hooks/misc/useTable'import { EXCLUDED_SCHEMAS } from 'lib/constants/schemas'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'@@ -53,12 +55,15 @@ const TableGridEditor = ({isLoadingSelectedTable = false,selectedTable,}: TableGridEditorProps) => {- const { project } = useProjectContext()- const snap = useTableEditorStateSnapshot()- const { meta, ui, vault } = useStore()const router = useRouter()+ const { meta, ui, vault } = useStore()const { ref: projectRef, id } = useParams()++ const { project } = useProjectContext()+ const appSnap = useAppStateSnapshot()+ const snap = useTableEditorStateSnapshot()const gridRef = useRef<SupabaseGridRef>(null)+ const isNewAPIDocsEnabled = useIsAPIDocsSidePanelEnabled()const [encryptedColumns, setEncryptedColumns] = useState([])const [apiPreviewPanelOpen, setApiPreviewPanelOpen] = useState(false)@@ -327,8 +332,14 @@ const TableGridEditor = ({{canEditViaTableEditor && (<GridHeaderActionstable={selectedTable as PostgresTable}- apiPreviewPanelOpen={apiPreviewPanelOpen}- setApiPreviewPanelOpen={setApiPreviewPanelOpen}+ openAPIDocsPanel={() => {+ if (isNewAPIDocsEnabled) {+ appSnap.setActiveDocsSection(['entities', selectedTable.name])+ appSnap.setShowProjectApiDocs(true)+ } else {+ setApiPreviewPanelOpen(true)+ }+ }}refreshDocs={refreshDocs}/>)}diff --git a/studio/components/layouts/DatabaseLayout/DatabaseLayout.tsx b/studio/components/layouts/DatabaseLayout/DatabaseLayout.tsxindex d5d33ad212e..02a3b862cb7 100644--- a/studio/components/layouts/DatabaseLayout/DatabaseLayout.tsx+++ b/studio/components/layouts/DatabaseLayout/DatabaseLayout.tsx@@ -6,6 +6,7 @@ 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@@ -21,6 +22,7 @@ const DatabaseLayout = ({ children }: PropsWithChildren<DatabaseLayoutProps>) =>const vaultExtension = meta.extensions.byId('supabase_vault')const isVaultEnabled = vaultExtension !== undefined && vaultExtension.installed_version !== nullconst pgNetExtensionExists = meta.extensions.byId('pg_net') !== undefined+ const isNewAPIDocsEnabled = useIsAPIDocsSidePanelEnabled()useEffect(() => {if (ui.selectedProjectRef) {@@ -41,7 +43,10 @@ const DatabaseLayout = ({ children }: PropsWithChildren<DatabaseLayoutProps>) =><ProjectLayoutproduct="Database"productMenu={- <ProductMenu page={page} menu={generateDatabaseMenu(project, { pgNetExtensionExists })} />+ <ProductMenu+ page={page}+ menu={generateDatabaseMenu(project, { pgNetExtensionExists, isNewAPIDocsEnabled })}+ />}><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.tsindex cd797f39592..48957d4a025 100644--- a/studio/components/layouts/DatabaseLayout/DatabaseMenu.utils.ts+++ b/studio/components/layouts/DatabaseLayout/DatabaseMenu.utils.ts@@ -6,10 +6,11 @@ export const generateDatabaseMenu = (project?: Project,flags?: {pgNetExtensionExists: boolean+ isNewAPIDocsEnabled: boolean}): ProductMenuGroup[] => {const ref = project?.ref ?? 'default'- const { pgNetExtensionExists } = flags || {}+ const { pgNetExtensionExists, isNewAPIDocsEnabled } = flags || {}return [{@@ -85,6 +86,16 @@ export const generateDatabaseMenu = (url: `/project/${ref}/database/indexes`,items: [],},+ ...(isNewAPIDocsEnabled+ ? [+ {+ name: 'GraphiQL',+ key: 'graphiql',+ url: `/project/${ref}/database/graphiql`,+ items: [],+ },+ ]+ : []),],},]diff --git a/studio/components/layouts/FunctionsLayout.tsx b/studio/components/layouts/FunctionsLayout.tsxindex 946dc05191b..3cbe746ef0d 100644--- a/studio/components/layouts/FunctionsLayout.tsx+++ b/studio/components/layouts/FunctionsLayout.tsx@@ -5,10 +5,12 @@ import Link from 'next/link'import { PropsWithChildren } from 'react'import { Button, IconCode, IconExternalLink } from 'ui'+import { useIsAPIDocsSidePanelEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'import NoPermission from 'components/ui/NoPermission'import { useEdgeFunctionQuery } from 'data/edge-functions/edge-function-query'import { useEdgeFunctionsQuery } from 'data/edge-functions/edge-functions-query'import { useCheckPermissions, withAuth } from 'hooks'+import { useAppStateSnapshot } from 'state/app-state'import FunctionsNav from '../interfaces/Functions/FunctionsNav'import ProjectLayout from './'@@ -17,7 +19,9 @@ 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 })@@ -112,6 +116,24 @@ const FunctionsLayout = ({ title, children }: PropsWithChildren<FunctionsLayoutP<Button type="default">Manage secrets</Button></a></Link>+ {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>+ )}<Link href="https://supabase.com/docs/guides/functions"><a target="_link"><Buttondiff --git a/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.tsx b/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.tsxindex 85954fb01e2..dcca534cd5b 100644--- a/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.tsx+++ b/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.tsx@@ -1,14 +1,10 @@import * as Tooltip from '@radix-ui/react-tooltip'import { useParams } from 'common'-import { useFlag } from 'hooks'-import { IS_PLATFORM } from 'lib/constants'-import { detectOS } from 'lib/helpers'import { isUndefined } from 'lodash'import { FlaskConical } from 'lucide-react'import { useTheme } from 'next-themes'import Link from 'next/link'import { useRouter } from 'next/router'-import { useAppStateSnapshot } from 'state/app-state'import {Button,DropdownMenu,@@ -21,12 +17,19 @@ import {DropdownMenuSeparator,DropdownMenuTrigger,IconCommand,+ IconFileText,IconHome,IconSearch,IconSettings,IconUser,useCommandMenu,} from 'ui'++import { useIsAPIDocsSidePanelEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'+import { useFlag } from 'hooks'+import { IS_PLATFORM } from 'lib/constants'+import { detectOS } from 'lib/helpers'+import { useAppStateSnapshot } from 'state/app-state'import { useProjectContext } from '../ProjectContext'import {generateOtherRoutes,@@ -47,11 +50,12 @@ const NavigationBar = () => {const navLayoutV2 = useFlag('navigationLayoutV2')const supabaseAIEnabled = useFlag('sqlEditorSupabaseAI')const showFeaturePreviews = useFlag('featurePreviews')+ const isNewAPIDocsEnabled = useIsAPIDocsSidePanelEnabled()const activeRoute = router.pathname.split('/')[3]const toolRoutes = generateToolRoutes(projectRef, project, supabaseAIEnabled)const productRoutes = generateProductRoutes(projectRef, project)- const otherRoutes = generateOtherRoutes(projectRef, project)+ const otherRoutes = generateOtherRoutes(projectRef, project, isNewAPIDocsEnabled)return (<div@@ -109,6 +113,35 @@ const NavigationBar = () => {</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-scale-200 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>@@ -168,7 +201,7 @@ const NavigationBar = () => {onSelect={() => snap.setShowFeaturePreviewModal(true)}><FlaskConical size={14} strokeWidth={2} />- <p className="text">Feature previews</p>+ <p>Feature previews</p></DropdownMenuItem>)}<DropdownMenuSeparator />diff --git a/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.utils.tsx b/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.utils.tsxindex 09496abc903..a0871893503 100644--- a/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.utils.tsx+++ b/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.utils.tsx@@ -152,7 +152,11 @@ export const generateProductRoutes = (ref?: string, project?: ProjectBase): Rout]}-export const generateOtherRoutes = (ref?: string, project?: ProjectBase): Route[] => {+export const generateOtherRoutes = (+ ref?: string,+ project?: ProjectBase,+ isNewAPIDocsEnabled?: boolean+): Route[] => {const isProjectBuilding = project?.status === PROJECT_STATUS.COMING_UPconst buildingUrl = `/project/${ref}/building`@@ -173,12 +177,16 @@ export const generateOtherRoutes = (ref?: string, project?: ProjectBase): Route[icon: <IconList size={18} strokeWidth={2.5} />,link: ref && (isProjectBuilding ? buildingUrl : `/project/${ref}/logs/explorer`),},- {- key: 'api',- label: 'API Docs',- icon: <IconFileText size={18} strokeWidth={2} />,- link: ref && (isProjectBuilding ? buildingUrl : `/project/${ref}/api`),- },+ ...(!isNewAPIDocsEnabled+ ? [+ {+ key: 'api',+ label: 'API Docs',+ icon: <IconFileText size={18} strokeWidth={2} />,+ link: ref && (isProjectBuilding ? buildingUrl : `/project/${ref}/api`),+ },+ ]+ : []),...(IS_PLATFORM? [{diff --git a/studio/components/layouts/ProjectLayout/ProjectLayout.tsx b/studio/components/layouts/ProjectLayout/ProjectLayout.tsxindex d24c102c53d..be8f1817046 100644--- a/studio/components/layouts/ProjectLayout/ProjectLayout.tsx+++ b/studio/components/layouts/ProjectLayout/ProjectLayout.tsx@@ -19,6 +19,7 @@ import ProjectPausedState from './ProjectPausedState'import RestoringState from './RestoringState'import UpgradingState from './UpgradingState'import Connecting from 'components/ui/Loading/Loading'+import ProjectAPIDocs from 'components/interfaces/ProjectAPIDocs/ProjectAPIDocs'// [Joshen] This is temporary while we unblock users from managing their project// if their project is not responding well for any reason. Eventually needs a bit of an overhaul@@ -123,6 +124,7 @@ const ProjectLayout = ({</div><EnableBranchingModal />+ <ProjectAPIDocs /></ProjectContextProvider></AppLayout>)@@ -271,6 +273,7 @@ export const ProjectLayoutNonBlocking = ({</div><EnableBranchingModal />+ <ProjectAPIDocs /></ProjectContextProvider></AppLayout>)diff --git a/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerHeader.tsx b/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerHeader.tsxindex bc8fe9cc3e6..3729d8b559a 100644--- a/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerHeader.tsx+++ b/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerHeader.tsx@@ -7,12 +7,14 @@ import {DropdownMenu,DropdownMenuContent,DropdownMenuRadioGroup,- DropdownMenuRadioItem,+ DropdownMenuSeparator,+ DropdownMenuItem,DropdownMenuTrigger,IconChevronLeft,IconChevronRight,IconChevronsDown,IconChevronsUp,+ IconCode,IconColumns,IconEdit2,IconFolderPlus,@@ -23,12 +25,36 @@ import {IconUpload,IconX,Input,+ IconCheck,+ DropdownMenuSub,+ DropdownMenuSubTrigger,+ DropdownMenuSubContent,+ DropdownMenuRadioItem,} from 'ui'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'++const VIEW_OPTIONS = [+ { key: STORAGE_VIEWS.COLUMNS, name: 'As columns' },+ { key: STORAGE_VIEWS.LIST, name: 'As list' },+]++const SORT_BY_OPTIONS = [+ { key: STORAGE_SORT_BY.NAME, name: 'Name' },+ { key: STORAGE_SORT_BY.CREATED_AT, name: 'Time created' },+ { key: STORAGE_SORT_BY.UPDATED_AT, name: 'Time modified' },+ { key: STORAGE_SORT_BY.LAST_ACCESSED_AT, name: 'Time last accessed' },+]++const SORT_ORDER_OPTIONS = [+ { key: STORAGE_SORT_BY_ORDER.ASC, name: 'Ascending' },+ { key: STORAGE_SORT_BY_ORDER.DESC, name: 'Descending' },+]const HeaderPathEdit = ({ loading, isSearching, breadcrumbs, togglePathEdit }: any) => {return (@@ -114,7 +140,9 @@ const FileExplorerHeader = ({onFilesUpload = noop,}: FileExplorerHeader) => {const debounceDuration = 300+ const appSnap = useAppStateSnapshot()const snap = useStorageExplorerStateSnapshot()+ const isNewAPIDocsEnabled = useIsAPIDocsSidePanelEnabled()const [pathString, setPathString] = useState('')const [searchString, setSearchString] = useState('')@@ -144,6 +172,7 @@ const FileExplorerHeader = ({addNewFolderPlaceholder,clearOpenedFolders,closeFilePreview,+ selectedBucket,} = storageExplorerStoreconst breadcrumbs = columns.map((column: any) => column.name)@@ -249,9 +278,9 @@ const FileExplorerHeader = ({return (<divclassName="- flex h-[40px]+ flex h-[40px] pl-2items-center justify-between- rounded-t-md border-b border-panel-border-light bg-panel-header-light px-2 dark:border-panel-border-dark dark:bg-panel-header-dark"+ rounded-t-md border-b border-panel-border-light bg-panel-header-light dark:border-panel-border-dark dark:bg-panel-header-dark">{/* Navigation */}<div className={`flex items-center ${isEditingPath ? 'w-1/2' : ''}`}>@@ -260,7 +289,7 @@ const FileExplorerHeader = ({icon={<IconChevronLeft size={16} strokeWidth={2} />}size="tiny"type="text"- className={breadcrumbs.length > 1 ? 'opacity-100' : 'opacity-25'}+ className={`${breadcrumbs.length > 1 ? 'opacity-100' : 'opacity-25'} px-1`}disabled={backDisabled}onClick={() => {setIsEditingPath(false)@@ -268,7 +297,6 @@ const FileExplorerHeader = ({}}/>)}- {!snap.isSearching && <></>}{isEditingPath ? (<form className="ml-2 flex-grow"><Input@@ -317,10 +345,9 @@ const FileExplorerHeader = ({</div>{/* Actions */}- <div className="flex items-center space-x-4">- <div className="flex items-center space-x-1">+ <div className="flex items-center">+ <div className="flex items-center space-x-1 px-2"><Button- className="mr-2"size="tiny"icon={<IconRefreshCw />}type="text"@@ -329,93 +356,163 @@ const FileExplorerHeader = ({>Reload</Button>- <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>++ {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>+ </>+ )}</div>- <div className="h-6 border-r border-panel-border-light dark:border-panel-border-dark" />- <div className="flex items-center space-x-1">++ <div className="h-6 border-r border-scale-600" />+ <div className="flex items-center space-x-1 px-2"><div className="hidden">{/* @ts-ignore */}<input ref={uploadButtonRef} type="file" multiple onChange={onFilesUpload} />@@ -481,7 +578,7 @@ const FileExplorerHeader = ({</div><div className="h-6 border-r border-scale-600" />- <div className="flex items-center pr-1.5">+ <div className="flex items-center px-2">{snap.isSearching ? (<Inputsize="tiny"@@ -512,6 +609,24 @@ const FileExplorerHeader = ({/>)}</div>++ {isNewAPIDocsEnabled && (+ <>+ <div className="h-6 border-r border-scale-600" />+ <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></div>)diff --git a/studio/data/open-api/api-spec-query.ts b/studio/data/open-api/api-spec-query.tsnew file mode 100644index 00000000000..489746e2b21--- /dev/null+++ b/studio/data/open-api/api-spec-query.ts@@ -0,0 +1,65 @@+import { useQuery, UseQueryOptions } from '@tanstack/react-query'++import { get } from 'data/fetchers'+import { ResponseError } from 'types'+import { openApiKeys } from './keys'++export type OpenAPISpecVariables = {+ projectRef?: string+}++export type OpenAPISpecResponse = {+ data: any+ tables: any[]+ functions: any[]+}++export async function getOpenAPISpec({ projectRef }: OpenAPISpecVariables, signal?: AbortSignal) {+ if (!projectRef) throw new Error('projectRef is required')++ const { data, error } = await get(`/platform/projects/{ref}/api/rest`, {+ params: { path: { ref: projectRef } },+ signal,+ })+ if (error) throw error++ const tables = data.definitions+ ? Object.entries(data.definitions).map(([key, table]: any) => ({+ ...table,+ name: key,+ fields: Object.entries(table.properties || {}).map(([key, field]: any) => ({+ ...field,+ name: key,+ })),+ }))+ : []++ const functions = data.paths+ ? Object.entries(data.paths)+ .map(([path, value]: any) => ({+ ...value,+ path,+ name: path.replace('/rpc/', ''),+ }))+ .filter((x) => x.path.includes('/rpc'))+ .sort((a, b) => a.name.localeCompare(b.name))+ : []++ return { data: data, tables, functions }+}++export type OpenAPISpecData = Awaited<OpenAPISpecResponse>+export type OpenAPISpecError = ResponseError++export const useOpenAPISpecQuery = <TData = OpenAPISpecData>(+ { projectRef }: OpenAPISpecVariables,+ { enabled = true, ...options }: UseQueryOptions<OpenAPISpecData, OpenAPISpecError, TData> = {}+) =>+ useQuery<OpenAPISpecData, OpenAPISpecError, TData>(+ openApiKeys.apiSpec(projectRef),+ ({ signal }) => getOpenAPISpec({ projectRef }, signal),+ {+ enabled: enabled && typeof projectRef !== 'undefined',+ ...options,+ }+ )diff --git a/studio/data/open-api/keys.ts b/studio/data/open-api/keys.tsnew file mode 100644index 00000000000..0172f1a1125--- /dev/null+++ b/studio/data/open-api/keys.ts@@ -0,0 +1,3 @@+export const openApiKeys = {+ apiSpec: (projectRef: string | undefined) => ['projects', projectRef, 'open-api-spec'] as const,+}diff --git a/studio/pages/_app.tsx b/studio/pages/_app.tsxindex e196fd9546a..81053a44023 100644--- a/studio/pages/_app.tsx+++ b/studio/pages/_app.tsx@@ -55,8 +55,10 @@ import { useAppStateSnapshot } from 'state/app-state'import { RootStore } from 'stores'import HCaptchaLoadedStore from 'stores/hcaptcha-loaded-store'import { AppPropsWithLayout } from 'types'-import { FeaturePreviewContextProvider } from 'components/interfaces/App/FeaturePreviewContext'-import FeaturePreviewModal from 'components/interfaces/App/FeaturePreviewModal'+import {+ FeaturePreviewContextProvider,+ FeaturePreviewModal,+} from 'components/interfaces/App/FeaturePreview'dayjs.extend(customParseFormat)dayjs.extend(utc)diff --git a/studio/pages/project/[ref]/database/graphiql.tsx b/studio/pages/project/[ref]/database/graphiql.tsxnew file mode 100644index 00000000000..c950b0f3ecd--- /dev/null+++ b/studio/pages/project/[ref]/database/graphiql.tsx@@ -0,0 +1,87 @@+import { createGraphiQLFetcher, Fetcher } from '@graphiql/toolkit'+import { observer } from 'mobx-react-lite'+import { useEffect, useMemo } from 'react'++import { useParams } from 'common/hooks'+import ExtensionCard from 'components/interfaces/Database/Extensions/ExtensionCard'+import GraphiQL from 'components/interfaces/GraphQL/GraphiQL'+import { DatabaseLayout } 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 { theme } = useTheme()+ const currentTheme = theme === '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) => <DatabaseLayout title="GraphiQL">{page}</DatabaseLayout>++export default observer(GraphiQLPage)diff --git a/studio/public/img/previews/api-docs-preview.png b/studio/public/img/previews/api-docs-preview.pngnew file mode 100644index 00000000000..64a9ce7a06cBinary files /dev/null and b/studio/public/img/previews/api-docs-preview.png differdiff --git a/studio/state/app-state.ts b/studio/state/app-state.tsindex f0c1f75cecb..689f49ae815 100644--- a/studio/state/app-state.ts+++ b/studio/state/app-state.ts@@ -2,6 +2,15 @@ import { LOCAL_STORAGE_KEYS } from 'lib/constants'import { proxy, snapshot, useSnapshot } from 'valtio'export const appState = proxy({+ activeDocsSection: ['introduction'],+ showProjectApiDocs: false,+ setShowProjectApiDocs: (value: boolean) => {+ appState.showProjectApiDocs = value+ },+ setActiveDocsSection: (value: string[]) => {+ appState.activeDocsSection = value+ },+isOptedInTelemetry: false,setIsOptedInTelemetry: (value: boolean) => {appState.isOptedInTelemetry = value