The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Chore/revert changes to api docs (#18865)
Joshen Lim30375c55a0bd
diff --git a/packages/ui/src/lib/theme/defaultTheme.ts b/packages/ui/src/lib/theme/defaultTheme.tsindex cac00a814fa..f81d20ec1ab 100644--- a/packages/ui/src/lib/theme/defaultTheme.ts+++ b/packages/ui/src/lib/theme/defaultTheme.ts@@ -1232,6 +1232,7 @@ export default {bg-surface-200space-y-1 py-3 px-4 sm:px-5border-b border-overlay+ flex items-center justify-between`,footer: `flex justify-end gap-2diff --git a/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsx b/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsxindex a8a6d8bfea0..9963867ad69 100644--- a/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsx+++ b/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsx@@ -21,6 +21,7 @@ export const useFeaturePreviewContext = () => useContext(FeaturePreviewContext)export const FeaturePreviewContextProvider = ({ children }: PropsWithChildren<{}>) => {const [flags, setFlags] = useState({[LOCAL_STORAGE_KEYS.UI_PREVIEW_NAVIGATION_LAYOUT]: false,+ [LOCAL_STORAGE_KEYS.UI_PREVIEW_API_SIDE_PANEL]: false,})useEffect(() => {@@ -28,6 +29,8 @@ export const FeaturePreviewContextProvider = ({ children }: PropsWithChildren<{}setFlags({[LOCAL_STORAGE_KEYS.UI_PREVIEW_NAVIGATION_LAYOUT]:localStorage.getItem(LOCAL_STORAGE_KEYS.UI_PREVIEW_NAVIGATION_LAYOUT) === 'true',+ [LOCAL_STORAGE_KEYS.UI_PREVIEW_API_SIDE_PANEL]:+ localStorage.getItem(LOCAL_STORAGE_KEYS.UI_PREVIEW_API_SIDE_PANEL) === 'true',})}}, [])@@ -51,3 +54,8 @@ export const useIsNavigationPreviewEnabled = () => {const { flags } = useFeaturePreviewContext()return flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_NAVIGATION_LAYOUT]}++export const useIsAPIDocsSidePanelEnabled = () => {+ const { flags } = useFeaturePreviewContext()+ return flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_API_SIDE_PANEL]+}diff --git a/studio/components/interfaces/App/FeaturePreview/FeaturePreviewModal.tsx b/studio/components/interfaces/App/FeaturePreview/FeaturePreviewModal.tsxindex 56840088487..ab87afcb1c5 100644--- a/studio/components/interfaces/App/FeaturePreview/FeaturePreviewModal.tsx+++ b/studio/components/interfaces/App/FeaturePreview/FeaturePreviewModal.tsx@@ -1,12 +1,14 @@import { useTelemetryProps } from 'common'+import { FlaskConical } from 'lucide-react'+import Link from 'next/link'import { useRouter } from 'next/router'import { useState } from 'react'import { Button, IconExternalLink, IconEye, IconEyeOff, Modal, ScrollArea, cn } from 'ui'+import { LOCAL_STORAGE_KEYS } from 'lib/constants'import Telemetry from 'lib/telemetry'-import { FlaskConical } from 'lucide-react'-import Link from 'next/link'import { useAppStateSnapshot } from 'state/app-state'+import APISidePanelPreview from './APISidePanelPreview'import { useFeaturePreviewContext } from './FeaturePreviewContext'// [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.@@ -17,6 +19,12 @@ const FEATURE_PREVIEWS: { key: string; name: string; content: any; discussionsUr// name: 'Global navigation update',// content: null,// },+ {+ key: LOCAL_STORAGE_KEYS.UI_PREVIEW_API_SIDE_PANEL,+ name: 'Project API documentation',+ content: <APISidePanelPreview />,+ discussionsUrl: 'https://github.com/orgs/supabase/discussions/18038',+ },]const FeaturePreviewModal = () => {@@ -54,7 +62,7 @@ const FeaturePreviewModal = () => {onCancel={() => snap.setShowFeaturePreviewModal(false)}>{FEATURE_PREVIEWS.length > 0 ? (- <div className="flex">+ <div className="flex border-t"><div><ScrollArea className="h-[550px] w-[240px] border-r">{FEATURE_PREVIEWS.map((feature) => {diff --git a/studio/components/interfaces/Auth/Users/Users.tsx b/studio/components/interfaces/Auth/Users/Users.tsxindex 0bba6d0cdf7..a144d24f356 100644--- a/studio/components/interfaces/Auth/Users/Users.tsx+++ b/studio/components/interfaces/Auth/Users/Users.tsx@@ -2,6 +2,7 @@ import { useParams } from 'common'import { useState } from 'react'import { Button, IconRefreshCw, IconSearch, IconX, Input, Listbox } from 'ui'+import { useIsAPIDocsSidePanelEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'import APIDocsButton from 'components/ui/APIDocsButton'import { useUsersQuery } from 'data/auth/users-query'@@ -11,6 +12,7 @@ import UsersList from './UsersList'const Users = () => {const { project } = useProjectContext()const { ref: projectRef } = useParams()+ const isNewAPIDocsEnabled = useIsAPIDocsSidePanelEnabled()const [page, setPage] = useState(1)const [search, setSearch] = useState('')@@ -81,7 +83,7 @@ const Users = () => {</Listbox></div><div className="mt-4 flex items-center gap-2 md:mt-0">- <APIDocsButton section={['user-management']} />+ {isNewAPIDocsEnabled && <APIDocsButton section={['user-management']} />}<Buttonsize="tiny"icon={<IconRefreshCw />}diff --git a/studio/components/interfaces/Docs/Authentication.tsx b/studio/components/interfaces/Docs/Authentication.tsxnew file mode 100644index 00000000000..296584ac070--- /dev/null+++ b/studio/components/interfaces/Docs/Authentication.tsx@@ -0,0 +1,109 @@+import Link from 'next/link'++import { AutoApiService } from 'data/config/project-api-query'+import CodeSnippet from './CodeSnippet'+import Snippets from './Snippets'++interface AuthenticationProps {+ autoApiService: AutoApiService+ selectedLang: 'bash' | 'js'+ showApiKey: string+}++const Authentication = ({ autoApiService, selectedLang, showApiKey }: AuthenticationProps) => {+ // [Joshen] ShowApiKey should really be a boolean, its confusing+ const defaultApiKey =+ showApiKey !== 'SUPABASE_KEY'+ ? autoApiService?.defaultApiKey ?? 'SUPABASE_CLIENT_API_KEY'+ : 'SUPABASE_CLIENT_API_KEY'+ const serviceApiKey =+ showApiKey !== 'SUPABASE_KEY'+ ? autoApiService?.serviceApiKey ?? 'SUPABASE_SERVICE_KEY'+ : 'SUPABASE_SERVICE_KEY'++ return (+ <>+ <h2 className="doc-heading">Authentication</h2>+ <div className="doc-section">+ <article className="code-column text-foreground">+ <p>Supabase works through a mixture of JWT and Key auth.</p>+ <p>+ If no <code>Authorization</code> header is included, the API will assume that you are+ making a request with an anonymous user.+ </p>+ <p>+ If an <code>Authorization</code> header is included, the API will "switch" to the role+ of the user making the request. See the User Management section for more details.+ </p>+ <p>We recommend setting your keys as Environment Variables.</p>+ </article>+ </div>++ <h2 className="doc-heading">Client API Keys</h2>+ <div className="doc-section ">+ <article className="code-column text-foreground">+ <p>+ Client keys allow "anonymous access" to your database, until the user has logged in.+ After logging in the keys will switch to the user's own login token.+ </p>+ <p>+ In this documentation, we will refer to the key using the name <code>SUPABASE_KEY</code>+ .+ </p>+ <p>+ We have provided you a Client Key to get started. You will soon be able to add as many+ keys as you like. You can find the <code>anon</code> key in the{' '}+ <Link href={`/project/${autoApiService.project.ref}/settings/api`}>API Settings</Link>{' '}+ page.+ </p>+ </article>+ <article className="code">+ <CodeSnippet+ selectedLang={selectedLang}+ snippet={Snippets.authKey('CLIENT API KEY', 'SUPABASE_KEY', defaultApiKey)}+ />+ <CodeSnippet+ selectedLang={selectedLang}+ snippet={Snippets.authKeyExample(defaultApiKey, autoApiService.endpoint, {+ showBearer: false,+ })}+ />+ </article>+ </div>++ <h2 className="doc-heading">Service Keys</h2>+ <div className="doc-section ">+ <article className="code-column text-foreground">+ <p>+ Service keys have FULL access to your data, bypassing any security policies. Be VERY+ careful where you expose these keys. They should only be used on a server and never on a+ client or browser.+ </p>+ <p>+ In this documentation, we will refer to the key using the name <code>SERVICE_KEY</code>.+ </p>+ <p>+ We have provided you with a Service Key to get started. Soon you will be able to add as+ many keys as you like. You can find the <code>service_role</code> in the{' '}+ <Link href={`/project/${autoApiService.project.ref}/settings/api`}>API Settings</Link>{' '}+ page.+ </p>+ </article>+ <article className="code">+ <CodeSnippet+ selectedLang={selectedLang}+ snippet={Snippets.authKey('SERVICE KEY', 'SERVICE_KEY', serviceApiKey)}+ />+ <CodeSnippet+ selectedLang={selectedLang}+ snippet={Snippets.authKeyExample(serviceApiKey, autoApiService.endpoint, {+ keyName: 'SERVICE_KEY',+ })}+ />+ </article>+ </div>+ </>+ )+}++export default Authenticationdiff --git a/studio/components/interfaces/Docs/CodeSnippet.tsx b/studio/components/interfaces/Docs/CodeSnippet.tsxnew file mode 100644index 00000000000..9bb0b831f29--- /dev/null+++ b/studio/components/interfaces/Docs/CodeSnippet.tsx@@ -0,0 +1,23 @@+import SimpleCodeBlock from 'components/to-be-cleaned/SimpleCodeBlock'++interface CodeSnippetProps {+ selectedLang: 'bash' | 'js'+ snippet: {+ title?: string+ bash: { language?: string; code: string }+ js?: { language?: string; code: string }+ }+}++const CodeSnippet = ({ selectedLang, snippet }: CodeSnippetProps) => {+ if (!snippet[selectedLang]) return null+ return (+ <div className="codeblock-container">+ <h4>{snippet.title}</h4>+ <SimpleCodeBlock className={snippet[selectedLang]?.language}>+ {snippet[selectedLang]?.code}+ </SimpleCodeBlock>+ </div>+ )+}+export default CodeSnippetdiff --git a/studio/components/interfaces/Docs/Description.tsx b/studio/components/interfaces/Docs/Description.tsxnew file mode 100644index 00000000000..e308488d9b4--- /dev/null+++ b/studio/components/interfaces/Docs/Description.tsx@@ -0,0 +1,120 @@+import { PermissionAction } from '@supabase/shared-types/out/constants'+import { noop } from 'lodash'+import { useState } from 'react'+import { Button, IconLoader } from 'ui'++import AutoTextArea from 'components/to-be-cleaned/forms/AutoTextArea'+import { useCheckPermissions, useStore } from 'hooks'+import { timeout } from 'lib/helpers'++// Removes some auto-generated Postgrest text+// Ideally PostgREST wouldn't add this if there is already a comment+const temp_removePostgrestText = (content: string) => {+ const postgrestTextPk = `Note:\nThis is a Primary Key.<pk/>`+ const postgrestTextFk = `Note:\nThis is a Foreign Key to`+ const pkTextPos = content.lastIndexOf(postgrestTextPk)+ const fkTextPos = content.lastIndexOf(postgrestTextFk)++ let cleansed = content+ if (pkTextPos >= 0) cleansed = cleansed.substring(0, pkTextPos)+ if (fkTextPos >= 0) cleansed = cleansed.substring(0, fkTextPos)+ return cleansed+}++interface DescrptionProps {+ content: string+ metadata: { table?: string; column?: string; rpc?: string }+ onChange: (value: string) => void+}++const Description = ({ content, metadata, onChange = noop }: DescrptionProps) => {+ const { meta, ui } = useStore()++ const contentText = temp_removePostgrestText(content || '').trim()+ const [value, setValue] = useState(contentText)+ const [isUpdating, setIsUpdating] = useState(false)++ const { table, column, rpc } = metadata++ const hasChanged = value != contentText+ const animateCss = `transition duration-150`++ const canUpdateDescription = useCheckPermissions(PermissionAction.TENANT_SQL_QUERY, '*')++ const updateDescription = async () => {+ if (isUpdating || !canUpdateDescription) return false++ setIsUpdating(true)+ let query = ''+ let description = value.replaceAll("'", "''")+ if (table && column)+ query = `comment on column public."${table}"."${column}" is '${description}';`+ if (table && !column) query = `comment on table public."${table}" is '${description}';`+ if (rpc) query = `comment on function "${rpc}" is '${description}';`++ if (query) {+ const res = await meta.query(query)++ // [Joshen] Temp fix, immediately refreshing the docs fetches stale state+ await timeout(500)++ if (res.error) {+ ui.setNotification({+ error: res.error,+ category: 'error',+ message: `Failed to update description: ${res.error.message}`,+ })+ } else {+ ui.setNotification({+ category: 'success',+ message: `Successfully updated description`,+ })+ }+ }++ onChange(value)+ setIsUpdating(false)+ }++ if (!canUpdateDescription) {+ return (+ <span className={`block ${value ? 'text-foreground' : ''}`}>{value || 'No description'}</span>+ )+ }++ return (+ <div className="space-y-2">+ <AutoTextArea+ className="w-full"+ placeholder="Click to edit."+ value={value}+ onChange={(e: any) => setValue(e.target.value)}+ />+ <div+ className={`flex items-center gap-2 ${+ hasChanged ? 'opacity-100' : 'h-0 cursor-default opacity-0'+ } ${animateCss}`}+ >+ <Button+ type="default"+ disabled={!hasChanged}+ onClick={() => {+ setValue(contentText)+ setIsUpdating(false)+ }}+ >+ Cancel+ </Button>+ <Button disabled={!hasChanged} onClick={updateDescription}>+ {isUpdating ? (+ <IconLoader className="mx-auto animate-spin" size={14} strokeWidth={2} />+ ) : (+ <span>Save</span>+ )}+ </Button>+ </div>+ </div>+ )+}++export default Descriptiondiff --git a/studio/components/interfaces/Docs/Docs.types.ts b/studio/components/interfaces/Docs/Docs.types.tsnew file mode 100644index 00000000000..7ea36375c90--- /dev/null+++ b/studio/components/interfaces/Docs/Docs.types.ts@@ -0,0 +1,4 @@+export type showApiKey = {+ key: string+ name: string+}diff --git a/studio/components/interfaces/Docs/GeneralContent.tsx b/studio/components/interfaces/Docs/GeneralContent.tsxnew file mode 100644index 00000000000..cb336120919--- /dev/null+++ b/studio/components/interfaces/Docs/GeneralContent.tsx@@ -0,0 +1,38 @@+import Introduction from 'components/interfaces/Docs/Introduction'+import Authentication from 'components/interfaces/Docs/Authentication'+import TablesIntroduction from 'components/interfaces/Docs/Pages/Tables/Introduction'+import UserManagement from 'components/interfaces/Docs/Pages/UserManagement'+import RpcIntroduction from 'components/interfaces/Docs/Pages/Rpc/Introduction'++const GeneralContent = ({ autoApiService, selectedLang, page, showApiKey }: any) => {+ let selected = page?.toLowerCase()+ if (selected == 'intro' || selected == null)+ return <Introduction autoApiService={autoApiService} selectedLang={selectedLang} />+ if (selected == 'auth')+ return (+ <Authentication+ autoApiService={autoApiService}+ selectedLang={selectedLang}+ showApiKey={showApiKey}+ />+ )+ if (selected == 'users')+ return (+ <UserManagement+ autoApiService={autoApiService}+ selectedLang={selectedLang}+ showApiKey={showApiKey}+ />+ )+ if (selected == 'tables-intro') return <TablesIntroduction selectedLang={selectedLang} />+ if (selected == 'rpc-intro') return <RpcIntroduction />+ else+ return (+ <div>+ <h2 className="m-4">Not found</h2>+ <p className="m-4"> Looks like you went somewhere that nobody knows.</p>+ </div>+ )+}++export default GeneralContentdiff --git a/studio/components/interfaces/Docs/GeneratingTypes.tsx b/studio/components/interfaces/Docs/GeneratingTypes.tsxnew file mode 100644index 00000000000..97e8df27e3a--- /dev/null+++ b/studio/components/interfaces/Docs/GeneratingTypes.tsx@@ -0,0 +1,123 @@+import Link from 'next/link'+import { useState } from 'react'+import { Button, IconDownload, IconExternalLink } from 'ui'++import { useParams } from 'common/hooks'+import CodeSnippet from 'components/interfaces/Docs/CodeSnippet'+import { generateTypes } from 'data/projects/project-type-generation-query'+import { useStore } from 'hooks'++interface Props {+ selectedLang: 'bash' | 'js'+}++export default function GeneratingTypes({ selectedLang }: Props) {+ const { ref } = useParams()+ const { ui } = useStore()+ const [isGeneratingTypes, setIsGeneratingTypes] = useState(false)++ const onClickGenerateTypes = async () => {+ try {+ setIsGeneratingTypes(true)+ const res = await generateTypes({ ref })+ let element = document.createElement('a')+ element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(res.types))+ element.setAttribute('download', 'supabase.ts')+ element.style.display = 'none'+ document.body.appendChild(element)+ element.click()+ document.body.removeChild(element)+ ui.setNotification({+ category: 'success',+ message: `Successfully generated types! File is being downloaded`,+ })+ } catch (error: any) {+ ui.setNotification({+ error,+ category: 'error',+ message: `Failed to generate types: ${error.message}`,+ })+ } finally {+ setIsGeneratingTypes(false)+ }+ }++ return (+ <>+ <h2 className="doc-heading flex items-center justify-between">+ <span>Generating types</span>+ <Button asChild type="default" icon={<IconExternalLink />}>+ <Link+ href="https://supabase.com/docs/guides/database/api/generating-types"+ target="_blank"+ rel="noreferrer"+ >+ Documentation+ </Link>+ </Button>+ </h2>+ <div className="doc-section">+ <article className="code-column text-foreground">+ <p>+ Supabase APIs are generated from your database, which means that we can use database+ introspection to generate type-safe API definitions.+ </p>+ <p>+ You can generate types from your database either through the{' '}+ <Link href="https://supabase.com/docs/guides/database/api/generating-types">+ Supabase CLI+ </Link>+ , or by downloading the types file via the button on the right and importing it in your+ application within <code>src/index.ts</code>.+ </p>+ </article>+ <article+ className={`code ${selectedLang === 'js' ? 'flex items-center justify-center' : ''}`}+ >+ <div className="grid gap-2">+ <p className="text-center">+ {selectedLang === 'js' && (+ <Button+ type="default"+ disabled={isGeneratingTypes}+ loading={isGeneratingTypes}+ icon={<IconDownload strokeWidth={1.5} />}+ onClick={onClickGenerateTypes}+ >+ Generate and download types+ </Button>+ )}+ </p>+ <p className="text-xs text-center text-foreground-light bg-background p-4">+ Remember to re-generate and download this file as you make changes to your tables.+ </p>+ </div>+ <CodeSnippet selectedLang={selectedLang} snippet={localSnippets.cliLogin()} />+ <CodeSnippet+ selectedLang={selectedLang}+ snippet={localSnippets.generateTypes(ref ?? '')}+ />+ </article>+ </div>+ </>+ )+}++const localSnippets = {+ cliLogin: () => ({+ title: 'Login via the CLI with your Personal Access Token',+ bash: {+ code: `+npx supabase login+`,+ },+ }),+ generateTypes: (ref: string) => ({+ title: 'Generate types',+ bash: {+ code: `+npx supabase gen types typescript --project-id "${ref}" --schema public > types/supabase.ts+`,+ },+ }),+}diff --git a/studio/components/interfaces/Docs/Introduction.tsx b/studio/components/interfaces/Docs/Introduction.tsxnew file mode 100644index 00000000000..fcdd3f48e13--- /dev/null+++ b/studio/components/interfaces/Docs/Introduction.tsx@@ -0,0 +1,23 @@+import { AutoApiService } from 'data/config/project-api-query'+import Snippets from 'components/interfaces/Docs/Snippets'+import CodeSnippet from './CodeSnippet'++interface Props {+ autoApiService: AutoApiService+ selectedLang: 'bash' | 'js'+}++export default function Introduction({ autoApiService, selectedLang }: Props) {+ return (+ <>+ <div className="doc-section doc-section--client-libraries">+ <article className="code">+ <CodeSnippet+ selectedLang={selectedLang}+ snippet={Snippets.init(autoApiService.endpoint)}+ />+ </article>+ </div>+ </>+ )+}diff --git a/studio/components/interfaces/Docs/LangSelector.tsx b/studio/components/interfaces/Docs/LangSelector.tsxnew file mode 100644index 00000000000..becbd171fce--- /dev/null+++ b/studio/components/interfaces/Docs/LangSelector.tsx@@ -0,0 +1,114 @@+import { PermissionAction } from '@supabase/shared-types/out/constants'+import { useCheckPermissions } from 'hooks'+import {+ Button,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+ IconKey,+} from 'ui'++import { showApiKey } from 'components/interfaces/Docs/Docs.types'++const DEFAULT_KEY = { name: 'hide', key: 'SUPABASE_KEY' }++interface LangSelectorProps {+ selectedLang: string+ setSelectedLang: (selectedLang: string) => void+ showApiKey: showApiKey+ setShowApiKey: (showApiKey: showApiKey) => void+ apiKey: string | undefined+ autoApiService: any+}++const LangSelector = ({+ selectedLang,+ setSelectedLang,+ showApiKey,+ setShowApiKey,+ apiKey,+ autoApiService,+}: LangSelectorProps) => {+ const canReadServiceKey = useCheckPermissions(+ PermissionAction.READ,+ 'service_api_keys.service_role_key'+ )++ return (+ <div className="p-1 w-1/2 ml-auto">+ <div className="z-0 flex justify-end">+ <button+ type="button"+ onClick={() => setSelectedLang('js')}+ className={`${+ selectedLang == 'js'+ ? 'bg-surface-100 font-medium text-foreground'+ : 'bg-alternative text-foreground-lighter'+ } relative inline-flex items-center border-r border-background p-1 px-2 text-sm transition hover:text-foreground focus:outline-none`}+ >+ JavaScript+ </button>+ <button+ type="button"+ onClick={() => setSelectedLang('bash')}+ className={`${+ selectedLang == 'bash'+ ? 'bg-surface-100 font-medium text-foreground'+ : 'bg-alternative text-foreground-lighter'+ } relative inline-flex items-center border-r border-background p-1 px-2 text-sm transition hover:text-foreground focus:outline-none`}+ >+ Bash+ </button>+ {selectedLang == 'bash' && (+ <div className="flex">+ <div className="flex items-center gap-2 p-1 pl-2 text-xs text-foreground-lighter">+ <IconKey size={12} strokeWidth={1.5} />+ <span>Project API key :</span>+ </div>+ <DropdownMenu>+ <DropdownMenuTrigger>+ <Button type="default">{showApiKey.name}</Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" side="bottom">+ <>+ <DropdownMenuItem key="hide" onClick={() => setShowApiKey(DEFAULT_KEY)}>+ hide+ </DropdownMenuItem>+ {apiKey && (+ <DropdownMenuItem+ key="anon"+ onClick={() =>+ setShowApiKey({+ key: apiKey,+ name: 'anon (public)',+ })+ }+ >+ <p>anon (public)</p>+ </DropdownMenuItem>+ )}+ {canReadServiceKey && (+ <DropdownMenuItem+ key="service"+ onClick={() =>+ setShowApiKey({+ key: autoApiService.serviceApiKey,+ name: 'service_role (secret)',+ })+ }+ >+ <p>service_role (secret)</p>+ </DropdownMenuItem>+ )}+ </>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ )}+ </div>+ </div>+ )+}++export default LangSelectordiff --git a/studio/components/interfaces/Docs/NoDescription.tsx b/studio/components/interfaces/Docs/NoDescription.tsxnew file mode 100644index 00000000000..7ffb0f43a26--- /dev/null+++ b/studio/components/interfaces/Docs/NoDescription.tsx@@ -0,0 +1,11 @@+const NoDescription = () => {+ return (+ <p className="text-gray-300 text-sm">+ No description provided.+ <br />+ Hint: you can create a custom description by adding a "comment" to this item in your database.+ </p>+ )+}++export default NoDescriptiondiff --git a/studio/components/interfaces/Docs/Pages/Rpc/Introduction.tsx b/studio/components/interfaces/Docs/Pages/Rpc/Introduction.tsxnew file mode 100644index 00000000000..bc78b7ef7b6--- /dev/null+++ b/studio/components/interfaces/Docs/Pages/Rpc/Introduction.tsx@@ -0,0 +1,18 @@+const Introduction = () => {+ return (+ <>+ <h2 className="doc-heading">Introduction</h2>+ <div className="doc-section">+ <article className="code-column text-foreground">+ <p>+ All of your database stored procedures are available on your API. This means you can+ build your logic directly into the database (if you're brave enough)!+ </p>+ <p>The API endpoint supports POST (and in some cases GET) to execute the function.</p>+ </article>+ </div>+ </>+ )+}++export default Introductiondiff --git a/studio/components/interfaces/Docs/Pages/Tables/Introduction.tsx b/studio/components/interfaces/Docs/Pages/Tables/Introduction.tsxnew file mode 100644index 00000000000..499b9709810--- /dev/null+++ b/studio/components/interfaces/Docs/Pages/Tables/Introduction.tsx@@ -0,0 +1,134 @@+import { useParams } from 'common'+import Link from 'next/link'++import CodeSnippet from 'components/interfaces/Docs/CodeSnippet'+import GeneratingTypes from 'components/interfaces/Docs/GeneratingTypes'++interface IntroductionProps {+ selectedLang: 'bash' | 'js'+}++const Introduction = ({ selectedLang }: IntroductionProps) => {+ const { ref } = useParams()++ return (+ <>+ <h2 className="doc-heading">Introduction</h2>+ <div className="doc-section">+ <article className="code-column text-foreground">+ <p>+ All views and tables in the <code>public</code> schema and accessible by the active+ database role for a request are available for querying.+ </p>+ </article>+ </div>++ <h2 className="doc-heading">Non-exposed tables</h2>+ <div className="doc-section">+ <article className="code-column text-foreground">+ <p>+ If you don't want to expose tables in your API, simply add them to a different schema+ (not the <code>public</code> schema).+ </p>+ </article>+ <article className="code"></article>+ </div>++ <GeneratingTypes selectedLang={selectedLang} />++ <h2 className="doc-heading">+ GraphQL <span className="lowercase">vs</span> Supabase+ </h2>+ <div className="doc-section">+ <article className="code-column text-foreground">+ <p>+ If you have a GraphQL background, you might be wondering if you can fetch your data in a+ single round-trip. The answer is yes!+ </p>+ <p>+ The syntax is very similar. This example shows how you might achieve the same thing with+ Apollo GraphQL and Supabase.+ <br />+ <br />+ </p>+ <h4>Still want GraphQL?</h4>+ <p>+ If you still want to use GraphQL, you can. Supabase provides you with a full Postgres+ database, so as long as your middleware can connect to the database then you can still+ use the tools you love. You can find the database connection details{' '}+ <Link href={`/project/${ref}/settings/database`}>in the settings.</Link>+ </p>+ </article>+ <article className="code">+ <CodeSnippet selectedLang={selectedLang} snippet={localSnippets.withApollo()} />+ <CodeSnippet selectedLang={selectedLang} snippet={localSnippets.withSupabase()} />+ </article>+ </div>+ </>+ )+}++const localSnippets = {+ withApollo: () => ({+ title: 'With Apollo GraphQL',+ bash: {+ language: 'js',+ code: `+const { loading, error, data } = useQuery(gql\`+ query GetDogs {+ dogs {+ id+ breed+ owner {+ id+ name+ }+ }+ }+\`)`,+ },+ js: {+ language: 'js',+ code: `+const { loading, error, data } = useQuery(gql\`+ query GetDogs {+ dogs {+ id+ breed+ owner {+ id+ name+ }+ }+ }+\`)`,+ },+ }),+ withSupabase: () => ({+ title: 'With Supabase',+ bash: {+ language: 'js',+ code: `+const { data, error } = await supabase+ .from('dogs')+ .select(\`+ id, breed,+ owner (id, name)+ \`)+`,+ },+ js: {+ language: 'js',+ code: `+const { data, error } = await supabase+ .from('dogs')+ .select(\`+ id, breed,+ owner (id, name)+ \`)+`,+ },+ }),+}++export default Introductiondiff --git a/studio/components/interfaces/Docs/Pages/UserManagement.tsx b/studio/components/interfaces/Docs/Pages/UserManagement.tsxnew file mode 100644index 00000000000..7184b7e8002--- /dev/null+++ b/studio/components/interfaces/Docs/Pages/UserManagement.tsx@@ -0,0 +1,306 @@+import Link from 'next/link'+import { useRouter } from 'next/router'++import { AutoApiService } from 'data/config/project-api-query'+import { makeRandomString } from 'lib/helpers'+import CodeSnippet from '../CodeSnippet'+import Snippets from '../Snippets'++const randomPassword = makeRandomString(20)++interface UserManagementProps {+ autoApiService: AutoApiService+ selectedLang: 'bash' | 'js'+ showApiKey: string+}++export default function UserManagement({+ autoApiService,+ selectedLang,+ showApiKey,+}: UserManagementProps) {+ const router = useRouter()++ const keyToShow = showApiKey ? showApiKey : 'SUPABASE_KEY'++ return (+ <>+ <h2 className="doc-heading">User Management</h2>+ <div className="doc-section">+ <article className="code-column text-foreground">+ <p>Supabase makes it easy to manage your users.</p>+ <p>+ Supabase assigns each user a unique ID. You can reference this ID anywhere in your+ database. For example, you might create a <code>profiles</code> table references the+ user using a <code>user_id</code> field.+ </p>+ <p>+ Supabase already has built in the routes to sign up, login, and log out for managing+ users in your apps and websites.+ </p>+ </article>+ </div>++ <h2 className="doc-heading">Sign up</h2>+ <div className="doc-section ">+ <article className="code-column text-foreground">+ <p>Allow your users to sign up and create a new account.</p>+ <p>+ After they have signed up, all interactions using the Supabase JS client will be+ performed as "that user".+ </p>+ </article>+ <article className="code">+ <CodeSnippet+ selectedLang={selectedLang}+ snippet={Snippets.authSignup(autoApiService.endpoint, keyToShow, randomPassword)}+ />+ </article>+ </div>++ <h2 className="doc-heading">Log in with Email/Password</h2>+ <div className="doc-section ">+ <article className="code-column text-foreground">+ <p>If an account is created, users can login to your app.</p>+ <p>+ After they have logged in, all interactions using the Supabase JS client will be+ performed as "that user".+ </p>+ </article>+ <article className="code">+ <CodeSnippet+ selectedLang={selectedLang}+ snippet={Snippets.authLogin(autoApiService.endpoint, keyToShow, randomPassword)}+ />+ </article>+ </div>++ <h2 className="doc-heading">Log in with Magic Link via Email</h2>+ <div className="doc-section ">+ <article className="code-column text-foreground">+ <p>Send a user a passwordless link which they can use to redeem an access_token.</p>+ <p>+ After they have clicked the link, all interactions using the Supabase JS client will be+ performed as "that user".+ </p>+ </article>+ <article className="code">+ <CodeSnippet+ selectedLang={selectedLang}+ snippet={Snippets.authMagicLink(autoApiService.endpoint, keyToShow)}+ />+ </article>+ </div>++ <h2 className="doc-heading">Sign Up with Phone/Password</h2>+ <div className="doc-section ">+ <article className="code-column text-foreground">+ <p>+ A phone number can be used instead of an email as a primary account confirmation+ mechanism.+ </p>+ <p>+ The user will receive a mobile OTP via sms with which they can verify that they control+ the phone number.+ </p>+ <p>+ You must enter your own twilio credentials on the auth settings page to enable sms+ confirmations.+ </p>+ </article>+ <article className="code">+ <CodeSnippet+ selectedLang={selectedLang}+ snippet={Snippets.authPhoneSignUp(autoApiService.endpoint, keyToShow)}+ />+ </article>+ </div>++ <h2 className="doc-heading">Login via SMS OTP</h2>+ <div className="doc-section ">+ <article className="code-column text-foreground">+ <p>+ SMS OTPs work like magic links, except you have to provide an interface for the user to+ verify the 6 digit number they receive.+ </p>+ <p>+ You must enter your own twilio credentials on the auth settings page to enable SMS-based+ Logins.+ </p>+ </article>+ <article className="code">+ <CodeSnippet+ selectedLang={selectedLang}+ snippet={Snippets.authMobileOTPLogin(autoApiService.endpoint, keyToShow)}+ />+ </article>+ </div>++ <h2 className="doc-heading">Verify an SMS OTP</h2>+ <div className="doc-section ">+ <article className="code-column text-foreground">+ <p>+ Once the user has received the OTP, have them enter it in a form and send it for+ verification+ </p>+ <p>+ You must enter your own twilio credentials on the auth settings page to enable SMS-based+ OTP verification.+ </p>+ </article>+ <article className="code">+ <CodeSnippet+ selectedLang={selectedLang}+ snippet={Snippets.authMobileOTPVerify(autoApiService.endpoint, keyToShow)}+ />+ </article>+ </div>++ <h2 className="doc-heading">Log in with Third Party OAuth</h2>+ <div className="doc-section ">+ <article className="code-column text-foreground">+ <p>+ Users can log in with Third Party OAuth like Google, Facebook, GitHub, and more. You+ must first enable each of these in the Auth Providers settings{' '}+ <span className="text-green-500">+ <Link key={'AUTH'} href={`/project/${router.query.ref}/auth/providers`}>+ here+ </Link>+ </span>{' '}+ .+ </p>+ <p>+ View all the available{' '}+ <a+ href="https://supabase.com/docs/guides/auth#providers"+ target="_blank"+ rel="noreferrer"+ >+ Third Party OAuth providers+ </a>+ </p>+ <p>+ After they have logged in, all interactions using the Supabase JS client will be+ performed as "that user".+ </p>+ <p>+ Generate your Client ID and secret from:{` `}+ <a+ href="https://console.developers.google.com/apis/credentials"+ target="_blank"+ rel="noreferrer"+ >+ </a>+ ,{` `}+ <a href="https://github.com/settings/applications/new" target="_blank" rel="noreferrer">+ GitHub+ </a>+ ,{` `}+ <a href="https://gitlab.com/oauth/applications" target="_blank" rel="noreferrer">+ GitLab+ </a>+ ,{` `}+ <a href="https://developers.facebook.com/apps/" target="_blank" rel="noreferrer">+ </a>+ ,{` `}+ <a+ href="https://support.atlassian.com/bitbucket-cloud/docs/use-oauth-on-bitbucket-cloud/"+ target="_blank"+ rel="noreferrer"+ >+ Bitbucket+ </a>+ .+ </p>+ </article>+ <article className="code">+ <CodeSnippet selectedLang={selectedLang} snippet={Snippets.authThirdPartyLogin()} />+ </article>+ </div>++ <h2 className="doc-heading">User</h2>+ <div className="doc-section ">+ <article className="code-column text-foreground">+ <p>Get the JSON object for the logged in user.</p>+ </article>+ <article className="code">+ <CodeSnippet+ selectedLang={selectedLang}+ snippet={Snippets.authUser(autoApiService.endpoint, keyToShow)}+ />+ </article>+ </div>++ <h2 className="doc-heading">Forgotten Password Email</h2>+ <div className="doc-section ">+ <article className="code-column text-foreground">+ <p>+ Sends the user a log in link via email. Once logged in you should direct the user to a+ new password form. And use "Update User" below to save the new password.+ </p>+ </article>+ <article className="code">+ <CodeSnippet+ selectedLang={selectedLang}+ snippet={Snippets.authRecover(autoApiService.endpoint, keyToShow)}+ />+ </article>+ </div>++ <h2 className="doc-heading">Update User</h2>+ <div className="doc-section ">+ <article className="code-column text-foreground">+ <p>+ Update the user with a new email or password. Each key (email, password, and data) is+ optional+ </p>+ </article>+ <article className="code">+ <CodeSnippet+ selectedLang={selectedLang}+ snippet={Snippets.authUpdate(autoApiService.endpoint, keyToShow)}+ />+ </article>+ </div>++ <h2 className="doc-heading">Log out</h2>+ <div className="doc-section ">+ <article className="code-column text-foreground">+ <p>+ After calling log out, all interactions using the Supabase JS client will be+ "anonymous".+ </p>+ </article>+ <article className="code">+ <CodeSnippet+ selectedLang={selectedLang}+ snippet={Snippets.authLogout(autoApiService.endpoint, keyToShow)}+ />+ </article>+ </div>++ <h2 className="doc-heading">Send a User an Invite over Email</h2>+ <div className="doc-section ">+ <article className="code-column text-foreground">+ <p>Send a user a passwordless link which they can use to sign up and log in.</p>+ <p>+ After they have clicked the link, all interactions using the Supabase JS client will be+ performed as "that user".+ </p>+ <p>+ This endpoint requires you use the <code>service_role_key</code> when initializing the+ client, and should only be invoked from the server, never from the client.+ </p>+ </article>+ <article className="code">+ <CodeSnippet+ selectedLang={selectedLang}+ snippet={Snippets.authInvite(autoApiService.endpoint, keyToShow)}+ />+ </article>+ </div>+ </>+ )+}diff --git a/studio/components/interfaces/Docs/Param.tsx b/studio/components/interfaces/Docs/Param.tsxnew file mode 100644index 00000000000..4a97f170848--- /dev/null+++ b/studio/components/interfaces/Docs/Param.tsx@@ -0,0 +1,104 @@+import { noop } from 'lodash'+import { Badge, IconCode, IconDatabase } from 'ui'++import Description from 'components/interfaces/Docs/Description'++function getColumnType(type: string, format: string) {+ // json and jsonb both have type=undefined, so check format instead+ if (type === undefined && (format === 'jsonb' || format === 'json')) return 'json'++ switch (type) {+ case 'string':+ return 'string'+ case 'integer':+ return 'number'+ case 'json':+ return 'json'+ case 'number':+ return 'number'+ case 'boolean':+ return 'boolean'+ default:+ return ''+ }+}++interface ParamProps {+ name: string+ type: string+ format: string+ required: boolean+ description: boolean+ metadata?: any+ onDesciptionUpdated?: () => void+}+const Param = ({+ name,+ type,+ format,+ required,+ description,+ metadata = {},+ onDesciptionUpdated = noop,+}: ParamProps) => {+ return (+ <>+ <div className="mb-4 flex items-center justify-between ">+ <div className="flex gap-2 items-center">+ <div className="flex items-center gap-2">+ <label className="font-mono text-xs uppercase text-foreground-lighter min-w-[55px]">+ Column+ </label>++ <div className="flex items-center gap-4">+ <span className="text-md text-foreground pb-0.5">{name}</span>+ </div>+ </div>+ </div>++ <Badge color={required ? 'amber' : 'scale'}>{required ? 'Required' : 'Optional'}</Badge>+ </div>+ {format && (+ <div className="grid gap-2 mt-6">+ <div className="mb-4 flex items-center gap-2">+ <label className="font-mono text-xs uppercase text-foreground-lighter min-w-[55px]">+ Type+ </label>+ <div>+ <span className="flex grow-0 bg-slate-300 px-2 py-0.5 rounded-md text-foreground-light">+ <span className="flex items-center gap-2 text-sm">+ <IconCode size="tiny" />+ <span>{getColumnType(type, format)}</span>+ </span>+ </span>+ </div>+ </div>+ <div className="mb-4 flex items-center gap-2">+ <label className="font-mono text-xs uppercase text-foreground-lighter min-w-[55px]">+ Format+ </label>+ <div>+ <span className="flex grow-0 bg-slate-300 px-2 py-0.5 rounded-md text-foreground-light">+ <span className="flex items-center gap-2 text-sm">+ <IconDatabase size="tiny" />+ <span>{format}</span>+ </span>+ </span>+ </div>+ </div>+ </div>+ )}+ {description !== false && (+ <div className="grid gap-2 mt-2">+ <label className="font-mono text-xs uppercase text-foreground-lighter">Description</label>+ <Description+ content={description?.toString()}+ metadata={metadata}+ onChange={onDesciptionUpdated}+ />+ </div>+ )}+ </>+ )+}+export default Paramdiff --git a/studio/components/interfaces/Docs/ResourceContent.tsx b/studio/components/interfaces/Docs/ResourceContent.tsxnew file mode 100644index 00000000000..ff01c1648f4--- /dev/null+++ b/studio/components/interfaces/Docs/ResourceContent.tsx@@ -0,0 +1,318 @@+import { useParams } from 'common'+import { IconTable } from 'ui'++import CodeSnippet from 'components/interfaces/Docs/CodeSnippet'+import Description from 'components/interfaces/Docs/Description'+import Param from 'components/interfaces/Docs/Param'+import Snippets from 'components/interfaces/Docs/Snippets'+import { useCustomDomainsQuery } from 'data/custom-domains/custom-domains-query'+import { useIsFeatureEnabled } from 'hooks'++const ResourceContent = ({+ autoApiService,+ resourceId,+ resources,+ definitions,+ paths,+ selectedLang,+ showApiKey,+ refreshDocs,+}: any) => {+ const { ref } = useParams()+ const { data: customDomainData } = useCustomDomainsQuery({ projectRef: ref })+ const endpoint =+ customDomainData?.customDomain?.status === 'active'+ ? `https://${customDomainData.customDomain.hostname}`+ : autoApiService.endpoint++ const keyToShow = !!showApiKey ? showApiKey : 'SUPABASE_KEY'+ const resourcePaths = paths[`/${resourceId}`]+ const resourceDefinition = definitions[resourceId]+ const resourceMeta = resources[resourceId]+ const description = resourceDefinition?.description || null+ const methods = Object.keys(resourcePaths).map((x) => x.toUpperCase())+ const properties = Object.entries(resourceDefinition.properties || []).map(([id, val]: any) => ({+ ...val,+ id,+ required: resourceDefinition?.required?.includes(id),+ }))++ const { realtimeAll: realtimeEnabled } = useIsFeatureEnabled(['realtime:all'])++ if (!paths || !definitions) return null++ return (+ <>+ <h2 className="doc-section__table-name text-foreground mt-0 flex items-center px-6 gap-2">+ <span className="bg-slate-300 dark:bg-slate-400 p-2 rounded-lg">+ <IconTable size="small" />+ </span>+ <span className="text-2xl font-bold">{resourceId}</span>+ </h2>++ <div className="doc-section">+ <article className="code-column text-foreground">+ <label className="font-mono text-xs uppercase text-foreground-lighter inline-block mb-2">+ Description+ </label>+ <Description+ content={description}+ metadata={{ table: resourceId }}+ onChange={refreshDocs}+ />+ </article>+ <article className="code"></article>+ </div>+ {properties.length > 0 && (+ <div>+ {properties.map((x) => (+ <div className="doc-section py-4" key={x.id}>+ <div className="code-column text-foreground">+ <Param+ key={x.id}+ name={x.id}+ type={x.type}+ format={x.format}+ required={x.required}+ description={x.description}+ metadata={{+ table: resourceId,+ column: x.id,+ }}+ onDesciptionUpdated={refreshDocs}+ />+ </div>+ <div className="code">+ <CodeSnippet+ selectedLang={selectedLang}+ snippet={Snippets.readColumns({+ title: `Select ${x.id}`,+ resourceId,+ endpoint: endpoint,+ apiKey: keyToShow,+ columnName: x.id,+ })}+ />+ </div>+ </div>+ ))}+ </div>+ )}+ {methods.includes('GET') && (+ <>+ <h3 className="text-foreground mt-4 px-6">Read rows</h3>+ <div className="doc-section">+ <article className="code-column text-foreground">+ <p>+ To read rows in <code>{resourceId}</code>, use the <code>select</code> method.+ </p>+ <p>+ <a+ href="https://supabase.com/docs/reference/javascript/select"+ target="_blank"+ rel="noreferrer"+ >+ Learn more+ </a>+ </p>+ </article>+ <article className="code">+ <CodeSnippet+ selectedLang={selectedLang}+ snippet={Snippets.readAll(resourceId, endpoint, keyToShow)}+ />+ <CodeSnippet+ selectedLang={selectedLang}+ snippet={Snippets.readColumns({+ resourceId,+ endpoint: endpoint,+ apiKey: keyToShow,+ })}+ />+ <CodeSnippet+ selectedLang={selectedLang}+ snippet={Snippets.readForeignTables(resourceId, endpoint, keyToShow)}+ />+ <CodeSnippet+ selectedLang={selectedLang}+ snippet={Snippets.readRange(resourceId, endpoint, keyToShow)}+ />+ </article>+ </div>+ <div className="doc-section">+ <article className="code-column text-foreground">+ <h4 className="mt-0 text-white">Filtering</h4>+ <p>Supabase provides a wide range of filters.</p>+ <p>+ <a+ href="https://supabase.com/docs/reference/javascript/using-filters"+ target="_blank"+ rel="noreferrer"+ >+ Learn more+ </a>+ </p>+ </article>+ <article className="code">+ <CodeSnippet+ selectedLang={selectedLang}+ snippet={Snippets.readFilters(resourceId, endpoint, keyToShow)}+ />+ </article>+ </div>+ </>+ )}+ {methods.includes('POST') && (+ <>+ <h3 className="text-foreground mt-4 px-6">Insert rows</h3>+ <div className="doc-section">+ <article className="code-column text-foreground">+ <p>+ <code>insert</code> lets you insert into your tables. You can also insert in bulk+ and do UPSERT.+ </p>+ <p>+ <code>insert</code> will also return the replaced values for UPSERT.+ </p>+ <p>+ <a+ href="https://supabase.com/docs/reference/javascript/insert"+ target="_blank"+ rel="noreferrer"+ >+ Learn more+ </a>+ </p>+ </article>+ <article className="code">+ <CodeSnippet+ selectedLang={selectedLang}+ snippet={Snippets.insertSingle(resourceId, endpoint, keyToShow)}+ />+ <CodeSnippet+ selectedLang={selectedLang}+ snippet={Snippets.insertMany(resourceId, endpoint, keyToShow)}+ />+ <CodeSnippet+ selectedLang={selectedLang}+ snippet={Snippets.upsert(resourceId, endpoint, keyToShow)}+ />+ </article>+ </div>+ </>+ )}+ {methods.includes('PATCH') && (+ <>+ <h3 className="text-foreground mt-4 px-6">Update rows</h3>+ <div className="doc-section">+ <article className="code-column text-foreground">+ <p>+ <code>update</code> lets you update rows. <code>update</code> will match all rows by+ default. You can update specific rows using horizontal filters, e.g. <code>eq</code>+ , <code>lt</code>, and <code>is</code>.+ </p>+ <p>+ <code>update</code> will also return the replaced values for UPDATE.+ </p>+ <p>+ <a+ href="https://supabase.com/docs/reference/javascript/update"+ target="_blank"+ rel="noreferrer"+ >+ Learn more+ </a>+ </p>+ </article>+ <article className="code">+ <CodeSnippet+ selectedLang={selectedLang}+ snippet={Snippets.update(resourceId, endpoint, keyToShow)}+ />+ </article>+ </div>+ </>+ )}+ {methods.includes('DELETE') && (+ <>+ <h3 className="text-foreground mt-4 px-6">Delete rows</h3>+ <div className="doc-section">+ <article className="code-column text-foreground">+ <p>+ <code>delete</code> lets you delete rows. <code>delete</code> will match all rows by+ default, so remember to specify your filters!+ </p>+ <p>+ <a+ href="https://supabase.com/docs/reference/javascript/delete"+ target="_blank"+ rel="noreferrer"+ >+ Learn more+ </a>+ </p>+ </article>+ <article className="code">+ <CodeSnippet+ selectedLang={selectedLang}+ snippet={Snippets.delete(resourceId, endpoint, keyToShow)}+ />+ </article>+ </div>+ </>+ )}+ {realtimeEnabled &&+ (methods.includes('DELETE') || methods.includes('POST') || methods.includes('PATCH')) && (+ <>+ <h3 className="text-foreground mt-4 px-6">Subscribe to changes</h3>+ <div className="doc-section">+ <article className="code-column text-foreground">+ <p>+ Supabase provides realtime functionality and broadcasts database changes to+ authorized users depending on Row Level Security (RLS) policies.+ </p>+ <p>+ <a+ href="https://supabase.com/docs/reference/javascript/subscribe"+ target="_blank"+ rel="noreferrer"+ >+ Learn more+ </a>+ </p>+ </article>+ <article className="code">+ <CodeSnippet+ selectedLang={selectedLang}+ snippet={Snippets.subscribeAll(resourceMeta.camelCase, resourceId)}+ />+ <CodeSnippet+ selectedLang={selectedLang}+ snippet={Snippets.subscribeInserts(resourceMeta.camelCase, resourceId)}+ />+ <CodeSnippet+ selectedLang={selectedLang}+ snippet={Snippets.subscribeUpdates(resourceMeta.camelCase, resourceId)}+ />+ <CodeSnippet+ selectedLang={selectedLang}+ snippet={Snippets.subscribeDeletes(resourceMeta.camelCase, resourceId)}+ />+ <CodeSnippet+ selectedLang={selectedLang}+ snippet={Snippets.subscribeEq(+ resourceMeta.camelCase,+ resourceId,+ 'column_name',+ 'someValue'+ )}+ />+ </article>+ </div>+ </>+ )}+ </>+ )+}++export default ResourceContentdiff --git a/studio/components/interfaces/Docs/RpcContent.tsx b/studio/components/interfaces/Docs/RpcContent.tsxnew file mode 100644index 00000000000..73c541a015d--- /dev/null+++ b/studio/components/interfaces/Docs/RpcContent.tsx@@ -0,0 +1,88 @@+import CodeSnippet from 'components/interfaces/Docs/CodeSnippet'+import Description from 'components/interfaces/Docs/Description'+import Param from 'components/interfaces/Docs/Param'+import Snippets from 'components/interfaces/Docs/Snippets'++/**+ * TODO: need to support rpc with the same name and different params type+ */+const RpcContent = ({+ autoApiService,+ rpcId,+ rpcs,+ paths,+ selectedLang,+ refreshDocs,+ showApiKey,+}: any) => {+ const meta = rpcs[rpcId]+ const pathKey = `/rpc/${rpcId}`+ const path = paths && pathKey in paths ? paths[pathKey] : undefined+ const keyToShow = !!showApiKey ? showApiKey : 'SUPABASE_KEY'++ if (!path) return null++ const {+ post: { parameters, summary },+ } = path+ const rpcParamsObject =+ parameters && parameters[0] && parameters[0].schema && parameters[0].schema.properties+ ? parameters[0].schema.properties+ : {}+ const rpcParams = Object.entries(rpcParamsObject)+ .map(([k, v]: any) => ({ name: k, ...v }))+ .filter((x) => !!x.name)+ const paramList = rpcParams.map((x) => x.type).join(', ')++ return (+ <>+ <h2 className="text-foreground mt-0">+ <span className="px-6 text-2xl">{meta.id}</span>+ </h2>++ <div className="doc-section">+ <article className="code-column text-foreground">+ <label className="font-mono text-xs uppercase text-foreground-lighter">Description</label>+ <Description content={summary} metadata={{ rpc: rpcId }} onChange={refreshDocs} />+ </article>+ <article className="code">+ <CodeSnippet+ selectedLang={selectedLang}+ snippet={Snippets.rpcSingle({+ rpcName: rpcId,+ // @ts-ignore+ rpcCamelCase: meta.camelCase,+ rpcParams: rpcParams,+ apiKey: keyToShow,+ endpoint: autoApiService.endpoint,+ })}+ />+ </article>+ </div>+ {rpcParams.length > 0 && (+ <div>+ <h3 className="text-foreground mt-0 px-6 capitalize">Function Arguments</h3>+ {rpcParams.map((x, i) => {+ return (+ <div key={i} className="doc-section">+ <article className="code-column text-foreground">+ <Param+ key={x.name}+ name={x.name}+ type={x.type}+ format={x.format}+ required={true}+ description={false}+ />+ </article>+ <article className="code"></article>+ </div>+ )+ })}+ </div>+ )}+ </>+ )+}++export default RpcContentdiff --git a/studio/components/interfaces/Docs/Snippets.ts b/studio/components/interfaces/Docs/Snippets.tsnew file mode 100644index 00000000000..a6fb8f1ce7a--- /dev/null+++ b/studio/components/interfaces/Docs/Snippets.ts@@ -0,0 +1,755 @@+const snippets = {+ endpoint: (endpoint: string) => ({+ title: 'API URL',+ bash: {+ language: 'bash',+ code: `${endpoint}`,+ },+ js: {+ language: 'bash',+ code: `${endpoint}`,+ },+ }),+ install: () => ({+ title: 'Install',+ bash: null,+ js: {+ language: 'bash',+ code: `npm install --save @supabase/supabase-js`,+ },+ }),+ init: (endpoint: string) => ({+ title: 'Initializing',+ bash: {+ language: 'bash',+ code: `# No client library required for Bash.`,+ },+ js: {+ language: 'js',+ code: `+import { createClient } from '@supabase/supabase-js'+const supabaseUrl = '${endpoint}'+const supabaseKey = process.env.SUPABASE_KEY+const supabase = createClient(supabaseUrl, supabaseKey)`,+ },+ python: {+ language: 'python',+ code: `+import os+from supabase import create_client, Client+url: str = '${endpoint}'+key: str = os.environ.get("SUPABASE_KEY")+supabase: Client = create_client(url, key)+`,+ },+ dart: {+ language: 'dart',+ code: `+const supabaseUrl = '${endpoint}';+const supabaseKey = String.fromEnvironment('SUPABASE_KEY');+Future<void> main() async {+ await Supabase.initialize(url: supabaseUrl, anonKey: supabaseKey);+ runApp(MyApp());+}`,+ },+ }),+ authKey: (title: string, varName: string, apikey: string) => ({+ title: `${title}`,+ bash: {+ language: 'bash',+ code: `${apikey}`,+ },+ js: {+ language: 'js',+ code: `const ${varName} = '${apikey}'`,+ },+ }),+ authKeyExample: (+ defaultApiKey: string,+ endpoint: string,+ { keyName, showBearer = true }: { keyName?: string; showBearer?: boolean }+ ) => ({+ title: 'Example usage',+ bash: {+ language: 'bash',+ code: `+curl '${endpoint}/rest/v1/' \\+-H "apikey: ${defaultApiKey}" ${+ showBearer+ ? `\\+-H "Authorization: Bearer ${defaultApiKey}"`+ : ''+ }+`,+ },+ js: {+ language: 'js',+ code: `+const SUPABASE_URL = "${endpoint}"+const supabase = createClient(SUPABASE_URL, process.env.${keyName || 'SUPABASE_KEY'});+`,+ },+ }),+ rpcSingle: ({+ rpcName,+ rpcParams,+ endpoint,+ apiKey,+ showBearer = true,+ }: {+ rpcName: string+ rpcParams: any[]+ endpoint: string+ apiKey: string+ showBearer: boolean+ }) => {+ let rpcList = rpcParams.map((x) => `"${x.name}": "value"`).join(', ')+ let noParams = !rpcParams.length+ let bashParams = noParams ? '' : `\n-d '{ ${rpcList} }' \\`+ let jsParams = noParams+ ? ''+ : `, {${+ rpcParams.length+ ? rpcParams+ .map((x) => `\n ${x.name}`)+ .join(`, `)+ .concat('\n ')+ : ''+ }}`+ return {+ title: 'Invoke function ',+ bash: {+ language: 'bash',+ code: `+curl -X POST '${endpoint}/rest/v1/rpc/${rpcName}' \\${bashParams}+-H "Content-Type: application/json" \\+-H "apikey: ${apiKey}" ${+ showBearer+ ? `\\+-H "Authorization: Bearer ${apiKey}"`+ : ''+ }+`,+ },+ js: {+ language: 'js',+ code: `+let { data, error } = await supabase+ .rpc('${rpcName}'${jsParams})+if (error) console.error(error)+else console.log(data)+`,+ },+ }+ },+ subscribeAll: (listenerName: string, resourceId: string) => ({+ title: 'Subscribe to all events',+ bash: {+ language: 'bash',+ code: `# Realtime streams are only supported by our client libraries`,+ },+ js: {+ language: 'js',+ code: `+const ${listenerName} = supabase.channel('custom-all-channel')+ .on(+ 'postgres_changes',+ { event: '*', schema: 'public', table: '${resourceId}' },+ (payload) => {+ console.log('Change received!', payload)+ }+ )+ .subscribe()`,+ },+ }),+ subscribeInserts: (listenerName: string, resourceId: string) => ({+ title: 'Subscribe to inserts',+ bash: {+ language: 'bash',+ code: `# Realtime streams are only supported by our client libraries`,+ },+ js: {+ language: 'js',+ code: `+const ${listenerName} = supabase.channel('custom-insert-channel')+ .on(+ 'postgres_changes',+ { event: 'INSERT', schema: 'public', table: '${resourceId}' },+ (payload) => {+ console.log('Change received!', payload)+ }+ )+ .subscribe()`,+ },+ }),+ subscribeUpdates: (listenerName: string, resourceId: string) => ({+ title: 'Subscribe to updates',+ bash: {+ language: 'bash',+ code: `# Realtime streams are only supported by our client libraries`,+ },+ js: {+ language: 'js',+ code: `+const ${listenerName} = supabase.channel('custom-update-channel')+ .on(+ 'postgres_changes',+ { event: 'UPDATE', schema: 'public', table: '${resourceId}' },+ (payload) => {+ console.log('Change received!', payload)+ }+ )+ .subscribe()`,+ },+ }),+ subscribeDeletes: (listenerName: string, resourceId: string) => ({+ title: 'Subscribe to deletes',+ bash: {+ language: 'bash',+ code: `# Realtime streams are only supported by our client libraries`,+ },+ js: {+ language: 'js',+ code: `+const ${listenerName} = supabase.channel('custom-delete-channel')+ .on(+ 'postgres_changes',+ { event: 'DELETE', schema: 'public', table: '${resourceId}' },+ (payload) => {+ console.log('Change received!', payload)+ }+ )+ .subscribe()`,+ },+ }),+ subscribeEq: (listenerName: string, resourceId: string, columnName: string, value: string) => ({+ title: 'Subscribe to specific rows',+ bash: {+ language: 'bash',+ code: `# Realtime streams are only supported by our client libraries`,+ },+ js: {+ language: 'js',+ code: `+const ${listenerName} = supabase.channel('custom-filter-channel')+ .on(+ 'postgres_changes',+ { event: '*', schema: 'public', table: '${resourceId}', filter: '${columnName}=eq.${value}' },+ (payload) => {+ console.log('Change received!', payload)+ }+ )+ .subscribe()`,+ },+ }),+ readAll: (resourceId: string, endpoint: string, apiKey: string) => ({+ title: 'Read all rows',+ bash: {+ language: 'bash',+ code: `+curl '${endpoint}/rest/v1/${resourceId}?select=*' \\+-H "apikey: ${apiKey}" \\+-H "Authorization: Bearer ${apiKey}"+`,+ },+ js: {+ language: 'js',+ code: `+let { data: ${resourceId}, error } = await supabase+ .from('${resourceId}')+ .select('*')+`,+ },+ }),+ readColumns: ({+ title = 'Read specific columns',+ resourceId,+ endpoint,+ apiKey,+ columnName = 'some_column,other_column',+ }: {+ title?: string+ resourceId: string+ endpoint: string+ apiKey: string+ columnName?: string+ }) => ({+ title,+ bash: {+ language: 'bash',+ code: `+curl '${endpoint}/rest/v1/${resourceId}?select=${columnName}' \\+-H "apikey: ${apiKey}" \\+-H "Authorization: Bearer ${apiKey}"+`,+ },+ js: {+ language: 'js',+ code: `+let { data: ${resourceId}, error } = await supabase+ .from('${resourceId}')+ .select('${columnName}')+`,+ },+ }),+ readForeignTables: (resourceId: string, endpoint: string, apiKey: string) => ({+ title: 'Read foreign tables',+ bash: {+ language: 'bash',+ code: `+curl '${endpoint}/rest/v1/${resourceId}?select=some_column,other_table(foreign_key)' \\+-H "apikey: ${apiKey}" \\+-H "Authorization: Bearer ${apiKey}"+`,+ },+ js: {+ language: 'js',+ code: `+let { data: ${resourceId}, error } = await supabase+ .from('${resourceId}')+ .select(\`+ some_column,+ other_table (+ foreign_key+ )+ \`)+`,+ },+ }),+ readRange: (resourceId: string, endpoint: string, apiKey: string) => ({+ title: 'With pagination',+ bash: {+ language: 'bash',+ code: `+curl '${endpoint}/rest/v1/${resourceId}?select=*' \\+-H "apikey: ${apiKey}" \\+-H "Authorization: Bearer ${apiKey}" \\+-H "Range: 0-9"+`,+ },+ js: {+ language: 'js',+ code: `+let { data: ${resourceId}, error } = await supabase+ .from('${resourceId}')+ .select('*')+ .range(0, 9)+`,+ },+ }),+ readFilters: (resourceId: string, endpoint: string, apiKey: string) => ({+ title: 'With filtering',+ bash: {+ language: 'bash',+ code: `+curl '${endpoint}/rest/v1/${resourceId}?id=eq.1&select=*' \\+-H "apikey: ${apiKey}" \\+-H "Authorization: Bearer ${apiKey}" \\+-H "Range: 0-9"+`,+ },+ js: {+ language: 'js',+ code: `+let { data: ${resourceId}, error } = await supabase+ .from('${resourceId}')+ .select("*")+ // Filters+ .eq('column', 'Equal to')+ .gt('column', 'Greater than')+ .lt('column', 'Less than')+ .gte('column', 'Greater than or equal to')+ .lte('column', 'Less than or equal to')+ .like('column', '%CaseSensitive%')+ .ilike('column', '%CaseInsensitive%')+ .is('column', null)+ .in('column', ['Array', 'Values'])+ .neq('column', 'Not equal to')+ // Arrays+ .cs('array_column', ['array', 'contains'])+ .cd('array_column', ['contained', 'by'])+`,+ },+ }),+ insertSingle: (resourceId: string, endpoint: string, apiKey: string) => ({+ title: 'Insert a row',+ bash: {+ language: 'bash',+ code: `+curl -X POST '${endpoint}/rest/v1/${resourceId}' \\+-H "apikey: ${apiKey}" \\+-H "Authorization: Bearer ${apiKey}" \\+-H "Content-Type: application/json" \\+-H "Prefer: return=minimal" \\+-d '{ "some_column": "someValue", "other_column": "otherValue" }'+`,+ },+ js: {+ language: 'js',+ code: `+const { data, error } = await supabase+ .from('${resourceId}')+ .insert([+ { some_column: 'someValue', other_column: 'otherValue' },+ ])+ .select()+`,+ },+ }),+ insertMany: (resourceId: string, endpoint: string, apiKey: string) => ({+ title: 'Insert many rows',+ bash: {+ language: 'bash',+ code: `+curl -X POST '${endpoint}/rest/v1/${resourceId}' \\+-H "apikey: ${apiKey}" \\+-H "Authorization: Bearer ${apiKey}" \\+-H "Content-Type: application/json" \\+-d '[{ "some_column": "someValue" }, { "other_column": "otherValue" }]'+`,+ },+ js: {+ language: 'js',+ code: `+const { data, error } = await supabase+ .from('${resourceId}')+ .insert([+ { some_column: 'someValue' },+ { some_column: 'otherValue' },+ ])+ .select()+`,+ },+ }),+ upsert: (resourceId: string, endpoint: string, apiKey: string) => ({+ title: 'Upsert matching rows',+ bash: {+ language: 'bash',+ code: `+curl -X POST '${endpoint}/rest/v1/${resourceId}' \\+-H "apikey: ${apiKey}" \\+-H "Authorization: Bearer ${apiKey}" \\+-H "Content-Type: application/json" \\+-H "Prefer: resolution=merge-duplicates" \\+-d '{ "some_column": "someValue", "other_column": "otherValue" }'+`,+ },+ js: {+ language: 'js',+ code: `+const { data, error } = await supabase+ .from('${resourceId}')+ .upsert({ some_column: 'someValue' })+ .select()+`,+ },+ }),+ update: (resourceId: string, endpoint: string, apiKey: string) => ({+ title: 'Update matching rows',+ bash: {+ language: 'bash',+ code: `+curl -X PATCH '${endpoint}/rest/v1/${resourceId}?some_column=eq.someValue' \\+-H "apikey: ${apiKey}" \\+-H "Authorization: Bearer ${apiKey}" \\+-H "Content-Type: application/json" \\+-H "Prefer: return=minimal" \\+-d '{ "other_column": "otherValue" }'+`,+ },+ js: {+ language: 'js',+ code: `+const { data, error } = await supabase+ .from('${resourceId}')+ .update({ other_column: 'otherValue' })+ .eq('some_column', 'someValue')+ .select()+`,+ },+ }),+ delete: (resourceId: string, endpoint: string, apiKey: string) => ({+ title: 'Delete matching rows',+ bash: {+ language: 'bash',+ code: `+curl -X DELETE '${endpoint}/rest/v1/${resourceId}?some_column=eq.someValue' \\+-H "apikey: ${apiKey}" \\+-H "Authorization: Bearer ${apiKey}"+`,+ },+ js: {+ language: 'js',+ code: `+const { error } = await supabase+ .from('${resourceId}')+ .delete()+ .eq('some_column', 'someValue')+`,+ },+ }),+ authSignup: (endpoint: string, apiKey: string, randomPassword: string) => ({+ title: 'User signup',+ bash: {+ language: 'bash',+ code: `+curl -X POST '${endpoint}/auth/v1/signup' \\+-H "apikey: ${apiKey}" \\+-H "Content-Type: application/json" \\+-d '{+ "email": "[email protected]",+ "password": "${randomPassword}"+}'+`,+ },+ js: {+ language: 'js',+ code: `+let { data, error } = await supabase.auth.signUp({+ email: '[email protected]',+ password: '${randomPassword}'+})+`,+ },+ }),+ authLogin: (endpoint: string, apiKey: string, randomPassword: string) => ({+ title: 'User login',+ bash: {+ language: 'bash',+ code: `+curl -X POST '${endpoint}/auth/v1/token?grant_type=password' \\+-H "apikey: ${apiKey}" \\+-H "Content-Type: application/json" \\+-d '{+ "email": "[email protected]",+ "password": "${randomPassword}"+}'+`,+ },+ js: {+ language: 'js',+ code: `+let { data, error } = await supabase.auth.signInWithPassword({+ email: '[email protected]',+ password: '${randomPassword}'+})+`,+ },+ }),+ authMagicLink: (endpoint: string, apiKey: string) => ({+ title: 'User login',+ bash: {+ language: 'bash',+ code: `+curl -X POST '${endpoint}/auth/v1/magiclink' \\+-H "apikey: ${apiKey}" \\+-H "Content-Type: application/json" \\+-d '{+ "email": "[email protected]"+}'+`,+ },+ js: {+ language: 'js',+ code: `+let { data, error } = await supabase.auth.signInWithOtp({+ email: '[email protected]'+})+`,+ },+ }),+ authPhoneSignUp: (endpoint: string, apiKey: string) => ({+ title: 'Phone Signup',+ bash: {+ language: 'bash',+ code: `+curl -X POST '${endpoint}/auth/v1/signup' \\+-H "apikey: ${apiKey}" \\+-H "Content-Type: application/json" \\+-d '{+ "phone": "+13334445555",+ "password": "some-password"+}'+`,+ },+ js: {+ language: 'js',+ code: `+let { data, error } = await supabase.auth.signUp({+ phone: '+13334445555',+ password: 'some-password'+})+`,+ },+ }),+ authMobileOTPLogin: (endpoint: string, apiKey: string) => ({+ title: 'Phone Login',+ bash: {+ language: 'bash',+ code: `+curl -X POST '${endpoint}/auth/v1/otp' \\+-H "apikey: ${apiKey}" \\+-H "Content-Type: application/json" \\+-d '{+ "phone": "+13334445555"+}'+`,+ },+ js: {+ language: 'js',+ code: `+let { data, error } = await supabase.auth.signInWithOtp({+ phone: '+13334445555'+})+`,+ },+ }),+ authMobileOTPVerify: (endpoint: string, apiKey: string) => ({+ title: 'Verify Pin',+ bash: {+ language: 'bash',+ code: `+curl -X POST '${endpoint}/auth/v1/verify' \\+-H "apikey: ${apiKey}" \\+-H "Content-Type: application/json" \\+-d '{+ "type": "sms",+ "phone": "+13334445555",+ "token": "123456"+}'+`,+ },+ js: {+ language: 'js',+ code: `+let { data, error } = await supabase.auth.verifyOtp({+ phone: '+13334445555',+ token: '123456',+ type: 'sms'+})+`,+ },+ }),+ authInvite: (endpoint: string, apiKey: string) => ({+ title: 'Invite User',+ bash: {+ language: 'bash',+ code: `+curl -X POST '${endpoint}/auth/v1/invite' \\+-H "apikey: ${apiKey}" \\+-H "Authorization: Bearer ${apiKey}" \\+-H "Content-Type: application/json" \\+-d '{+ "email": "[email protected]"+}'+`,+ },+ js: {+ language: 'js',+ code: `+let { data, error } = await supabase.auth.api.inviteUserByEmail('[email protected]')+`,+ },+ }),+ authThirdPartyLogin: () => ({+ title: 'Third Party Login',+ bash: {+ language: 'bash',+ code: ``,+ },+ js: {+ language: 'js',+ code: `+let { data, error } = await supabase.auth.signInWithOAuth({+ provider: 'github'+})+`,+ },+ }),+ authUser: (endpoint: string, apiKey: string) => ({+ title: 'Get User',+ bash: {+ language: 'bash',+ code: `+curl -X GET '${endpoint}/auth/v1/user' \\+-H "apikey: ${apiKey}" \\+-H "Authorization: Bearer USER_TOKEN"+`,+ },+ js: {+ language: 'js',+ code: `+const { data: { user } } = await supabase.auth.getUser()+`,+ },+ }),+ authRecover: (endpoint: string, apiKey: string) => ({+ title: 'Password Recovery',+ bash: {+ language: 'bash',+ code: `+ curl -X POST '${endpoint}/auth/v1/recover' \\+-H "apikey: ${apiKey}" \\+-H "Content-Type: application/json" \\+-d '{+ "email": "[email protected]"+}'+`,+ },+ js: {+ language: 'js',+ code: `+let { data, error } = await supabase.auth.resetPasswordForEmail(email)+`,+ },+ }),+ authUpdate: (endpoint: string, apiKey: string) => ({+ title: 'Update User',+ bash: {+ language: 'bash',+ code: `+ curl -X PUT '${endpoint}/auth/v1/user' \\+-H "apikey: ${apiKey}" \\+-H "Authorization: Bearer <USERS-ACCESS-TOKEN>" \\+-H "Content-Type: application/json" \\+-d '{+ "email": "[email protected]",+ "password": "new-password",+ "data": {+ "key": "value"+ }+}'+`,+ },+ js: {+ language: 'js',+ code: `+const { data, error } = await supabase.auth.updateUser({+ email: "[email protected]",+ password: "new-password",+ data: { hello: 'world' }+})+`,+ },+ }),+ authLogout: (endpoint: string, apiKey: string) => ({+ title: 'User logout',+ bash: {+ language: 'bash',+ code: `+curl -X POST '${endpoint}/auth/v1/logout' \\+-H "apikey: ${apiKey}" \\+-H "Content-Type: application/json" \\+-H "Authorization: Bearer USER_TOKEN"+`,+ },+ js: {+ language: 'js',+ code: `+let { error } = await supabase.auth.signOut()+`,+ },+ }),+}++export default snippetsdiff --git a/studio/components/interfaces/Docs/index.ts b/studio/components/interfaces/Docs/index.tsnew file mode 100644index 00000000000..8eaff962f84--- /dev/null+++ b/studio/components/interfaces/Docs/index.ts@@ -0,0 +1,5 @@+import GeneralContent from './GeneralContent'+import ResourceContent from './ResourceContent'+import RpcContent from './RpcContent'++export { GeneralContent, ResourceContent, RpcContent }diff --git a/studio/components/interfaces/ProjectAPIDocs/Content/Bucket.tsx b/studio/components/interfaces/ProjectAPIDocs/Content/Bucket.tsxindex b473075172c..b156deec8db 100644--- a/studio/components/interfaces/ProjectAPIDocs/Content/Bucket.tsx+++ b/studio/components/interfaces/ProjectAPIDocs/Content/Bucket.tsx@@ -23,7 +23,7 @@ const Bucket = ({ language, apikey, endpoint }: ContentProps) => {return (<div className="divide-y">- <div className="space-y-1 px-4 py-6">+ <div className="space-y-1 px-4 py-4"><div className="flex items-center space-x-2"><h2 className="text-xl">{bucket.name}</h2><Badge color={bucket.public ? 'amber' : 'scale'}>diff --git a/studio/components/interfaces/ProjectAPIDocs/Content/EdgeFunction.tsx b/studio/components/interfaces/ProjectAPIDocs/Content/EdgeFunction.tsxindex 7e1022ea6d7..0bc0fcd63c8 100644--- a/studio/components/interfaces/ProjectAPIDocs/Content/EdgeFunction.tsx+++ b/studio/components/interfaces/ProjectAPIDocs/Content/EdgeFunction.tsx@@ -19,7 +19,7 @@ const Bucket = ({ language, apikey = 'API_KEY', endpoint }: ContentProps) => {return (<div className="divide-y">- <div className="space-y-1 px-4 py-6">+ <div className="space-y-1 px-4 py-4"><div className="flex items-center space-x-2"><h2 className="text-xl">{edgeFunction.name}</h2></div>diff --git a/studio/components/interfaces/ProjectAPIDocs/Content/Entity.tsx b/studio/components/interfaces/ProjectAPIDocs/Content/Entity.tsxindex c2881822275..b9a82d656eb 100644--- a/studio/components/interfaces/ProjectAPIDocs/Content/Entity.tsx+++ b/studio/components/interfaces/ProjectAPIDocs/Content/Entity.tsx@@ -8,6 +8,7 @@ import { DOCS_RESOURCE_CONTENT } from '../ProjectAPIDocs.constants'import ResourceContent from '../ResourceContent'import { ContentProps } from './Content.types'import { tempRemovePostgrestText } from './Content.utils'+import LanguageSelector from '../LanguageSelector'function getColumnType(type: string, format: string) {// json and jsonb both have type=undefined, so check format instead@@ -52,14 +53,17 @@ const Entity = ({ language, apikey = '', endpoint = '' }: ContentProps) => {if (resource === undefined) return nullreturn (- <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 className="divide-y relative">+ <div className="flex items-center justify-between px-4 py-4 sticky top-0 bg-surface-100 z-10 border-b shadow-md">+ <div className="flex flex-col gap-y-1">+ <h2 className="text-xl">{resource}</h2>+ <p className="text-sm text-foreground-light">+ {definition?.description ?? 'No description available'}+ </p>+ </div>+ <LanguageSelector /></div>- <div className="space-y-2 px-4 py-4">+ <div className="space-y-2 px-4 py-4 !border-t-0"><p className="text-sm text-foreground-light">Columns</p><Tablehead={[diff --git a/studio/components/interfaces/ProjectAPIDocs/Content/RPC.tsx b/studio/components/interfaces/ProjectAPIDocs/Content/RPC.tsxindex a3cfb857d85..f57d4af9d25 100644--- a/studio/components/interfaces/ProjectAPIDocs/Content/RPC.tsx+++ b/studio/components/interfaces/ProjectAPIDocs/Content/RPC.tsx@@ -38,7 +38,7 @@ const RPC = ({ language }: ContentProps) => {return (<div className="divide-y">- <div className="space-y-1 px-4 py-6">+ <div className="space-y-1 px-4 py-4"><h2 className="text-xl">{rpc.name}</h2><p className="text-sm text-foreground-light">{summary ?? 'No description available'}</p></div>diff --git a/studio/components/interfaces/ProjectAPIDocs/FirstLevelNav.tsx b/studio/components/interfaces/ProjectAPIDocs/FirstLevelNav.tsxindex 6f8bde06fa3..39085d76089 100644--- a/studio/components/interfaces/ProjectAPIDocs/FirstLevelNav.tsx+++ b/studio/components/interfaces/ProjectAPIDocs/FirstLevelNav.tsx@@ -23,12 +23,19 @@ const FirstLevelNav = () => {projectAuthAll: authEnabled,projectStorageAll: storageEnabled,projectEdgeFunctionAll: edgeFunctionsEnabled,- } = useIsFeatureEnabled(['project_auth:all', 'project_storage:all', 'project_edge_function:all'])+ realtimeAll: realtimeEnabled,+ } = useIsFeatureEnabled([+ 'project_auth:all',+ 'project_storage:all',+ 'project_edge_function:all',+ 'realtime:all',+ ])const docsMenu = DOCS_MENU.filter((item) => {if (item.key === 'user-management') return authEnabledif (item.key === 'storage') return storageEnabledif (item.key === 'edge-functions') return edgeFunctionsEnabled+ if (item.key === 'realtime') return realtimeEnabledreturn true})@@ -140,27 +147,8 @@ const FirstLevelNav = () => {)})}</div>- <div className="px-2 py-4">- <Button block asChild type="text" size="small" icon={<IconBook />}>- <Link- href="https://supabase.com/docs"- target="_blank"- rel="noreferrer"- className="!justify-start"- >- Documentation- </Link>- </Button>- <Button block asChild type="text" size="small" icon={<IconBookOpen />}>- <Link- href="https://supabase.com/docs/guides/api"- target="_blank"- rel="noreferrer"- className="!justify-start"- >- REST guide- </Link>- </Button>++ <div className="px-2 py-4 border-b"><ButtonblockasChild@@ -174,7 +162,13 @@ const FirstLevelNav = () => {preProcessor={(code) => code.replace(/svg/, 'svg class="m-auto text-color-inherit"')}/>}+ onClick={() => snap.setShowProjectApiDocs(false)}>+ <Link className="!justify-start" href={`/project/${ref}/api/graphiql`}>+ GraphiQL+ </Link>+ </Button>+ <Button block asChild type="text" size="small" icon={<IconBookOpen />}><Linkhref="https://supabase.com/docs/guides/graphql"target="_blank"@@ -185,6 +179,29 @@ const FirstLevelNav = () => {</Link></Button></div>++ <div className="px-2 py-4">+ <Button block asChild type="text" size="small" icon={<IconBook />}>+ <Link+ href="https://supabase.com/docs"+ target="_blank"+ rel="noreferrer"+ className="!justify-start"+ >+ Documentation+ </Link>+ </Button>+ <Button block asChild type="text" size="small" icon={<IconBookOpen />}>+ <Link+ href="https://supabase.com/docs/guides/api"+ target="_blank"+ rel="noreferrer"+ className="!justify-start"+ >+ REST guide+ </Link>+ </Button>+ </div></>)}diff --git a/studio/components/interfaces/ProjectAPIDocs/LanguageSelector.tsx b/studio/components/interfaces/ProjectAPIDocs/LanguageSelector.tsxnew file mode 100644index 00000000000..60b5bfca4e4--- /dev/null+++ b/studio/components/interfaces/ProjectAPIDocs/LanguageSelector.tsx@@ -0,0 +1,87 @@+import { BASE_PATH } from 'lib/constants'+import { useState } from 'react'+import { useAppStateSnapshot } from 'state/app-state'+import {+ Button,+ CommandGroup_Shadcn_,+ CommandItem_Shadcn_,+ CommandList_Shadcn_,+ Command_Shadcn_,+ IconChevronDown,+ IconTerminal,+ PopoverContent_Shadcn_,+ PopoverTrigger_Shadcn_,+ Popover_Shadcn_,+} from 'ui'++interface LanguageSelectorProps {+ /**+ * Only show icons to represent the language+ */+ simplifiedVersion?: boolean+}++const LanguageSelector = ({ simplifiedVersion = false }: LanguageSelectorProps) => {+ const snap = useAppStateSnapshot()+ const [showLanguage, setShowLanguage] = useState(false)++ const updateLanguage = (value: 'js' | 'bash') => {+ snap.setDocsLanguage(value)+ setShowLanguage(false)+ }++ return (+ <div className="flex items-center gap-x-2">+ <Popover_Shadcn_ modal={false} open={showLanguage} onOpenChange={setShowLanguage}>+ <PopoverTrigger_Shadcn_ asChild>+ <Button+ type="default"+ className={simplifiedVersion ? 'px-1' : ''}+ icon={+ simplifiedVersion ? (+ snap.docsLanguage === 'js' ? (+ <img+ src={`${BASE_PATH}/img/libraries/javascript-icon.svg`}+ alt={`javascript logo`}+ width="14"+ />+ ) : (+ <IconTerminal size={14} strokeWidth={2.5} />+ )+ ) : undefined+ }+ iconRight={!simplifiedVersion && <IconChevronDown size={14} strokeWidth={2} />}+ >+ {!simplifiedVersion+ ? `Language: ${snap.docsLanguage === 'js' ? 'Javascript' : 'Bash'}`+ : undefined}+ </Button>+ </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_>+ </div>+ )+}++export default LanguageSelectordiff --git a/studio/components/interfaces/ProjectAPIDocs/ProjectAPIDocs.tsx b/studio/components/interfaces/ProjectAPIDocs/ProjectAPIDocs.tsxindex 366e71d8ecb..49675cbd624 100644--- a/studio/components/interfaces/ProjectAPIDocs/ProjectAPIDocs.tsx+++ b/studio/components/interfaces/ProjectAPIDocs/ProjectAPIDocs.tsx@@ -1,21 +1,9 @@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 { Button, 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,@@ -31,15 +19,28 @@ import {UserManagement,} from './Content'import FirstLevelNav from './FirstLevelNav'+import LanguageSelector from './LanguageSelector'import SecondLevelNav from './SecondLevelNav'+/**+ * [Joshen] Reminder: when we choose to release this as a main feature+ * Ensure that UX is better than the existing, and make sure we do the+ * necessary communications around releasing this.+ *+ * Problems:+ * - Needs URL support+ * - Language selector is not clear, users are missing the bash language option+ * - GraphiQL needs a better home, cannot be placed under Database as its "API"+ */+const ProjectAPIDocs = () => {const { ref } = useParams()const snap = useAppStateSnapshot()+ const isEntityDocs =+ snap.activeDocsSection.length === 2 && snap.activeDocsSection[0] === 'entities'- const [openLanguage, setOpenLanguage] = useState(false)const [showKeys, setShowKeys] = useState(false)- const [language, setLanguage] = useState<'js' | 'bash'>('js')+ const language = snap.docsLanguageconst { data } = useProjectApiQuery({ projectRef: ref })const { data: customDomainData } = useCustomDomainsQuery({ projectRef: ref })@@ -52,11 +53,6 @@ const ProjectAPIDocs = () => {? `https://${customDomainData.customDomain?.hostname}/auth/v1/callback`: `https://${data?.autoApiService.endpoint ?? ''}`- const updateLanguage = (value: 'js' | 'bash') => {- setLanguage(value)- setOpenLanguage(false)- }-return (<SidePanelhideFooter@@ -70,47 +66,7 @@ const ProjectAPIDocs = () => {<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_>+ {!isEntityDocs && <LanguageSelector simplifiedVersion />}<Button type="default" onClick={() => setShowKeys(!showKeys)}>{showKeys ? 'Hide keys' : 'Show keys'}</Button>@@ -120,7 +76,7 @@ const ProjectAPIDocs = () => {{snap.activeDocsSection.length === 1 ? <FirstLevelNav /> : <SecondLevelNav />}</div>- <div className="flex-1 divide-y space-y-4 max-h-screen overflow-auto px-4">+ <div className="flex-1 divide-y space-y-4 max-h-screen overflow-auto">{snap.activeDocsSection[0] === 'introduction' && (<IntroductionshowKeys={showKeys}diff --git a/studio/components/interfaces/ProjectAPIDocs/SecondLevelNav.tsx b/studio/components/interfaces/ProjectAPIDocs/SecondLevelNav.tsxindex f156d2eee35..0cd9c7f92ca 100644--- a/studio/components/interfaces/ProjectAPIDocs/SecondLevelNav.tsx+++ b/studio/components/interfaces/ProjectAPIDocs/SecondLevelNav.tsx@@ -22,6 +22,7 @@ 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 { useIsAPIDocsSidePanelEnabled } from '../App/FeaturePreview/FeaturePreviewContext'import { navigateToSection } from './Content/Content.utils'import { DOCS_RESOURCE_CONTENT } from './ProjectAPIDocs.constants'@@ -29,6 +30,7 @@ const SecondLevelNav = () => {const { ref } = useParams()const snap = useAppStateSnapshot()const [open, setOpen] = useState(false)+ const isNewAPIDocsEnabled = useIsAPIDocsSidePanelEnabled()const { data } = useOpenAPISpecQuery({ projectRef: ref })const tables = data?.tables ?? []@@ -74,12 +76,14 @@ const SecondLevelNav = () => {return (<div className="py-4"><div className="px-4 flex items-center space-x-2 mb-2">- <Button- type="text"- icon={<IconChevronLeft />}- className="px-1"- onClick={() => snap.setActiveDocsSection([snap.activeDocsSection[0]])}- />+ {isNewAPIDocsEnabled && (+ <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>diff --git a/studio/components/layouts/DatabaseLayout/DatabaseMenu.utils.ts b/studio/components/layouts/DatabaseLayout/DatabaseMenu.utils.tsindex 1e848f9f042..2815632c18f 100644--- a/studio/components/layouts/DatabaseLayout/DatabaseMenu.utils.ts+++ b/studio/components/layouts/DatabaseLayout/DatabaseMenu.utils.ts@@ -89,12 +89,6 @@ export const generateDatabaseMenu = (url: `/project/${ref}/database/types`,items: [],},- {- name: 'GraphiQL',- key: 'graphiql',- url: `/project/${ref}/database/graphiql`,- items: [],- },],},]diff --git a/studio/components/layouts/DocsLayout/DocsLayout.tsx b/studio/components/layouts/DocsLayout/DocsLayout.tsxnew file mode 100644index 00000000000..ad531768f7a--- /dev/null+++ b/studio/components/layouts/DocsLayout/DocsLayout.tsx@@ -0,0 +1,70 @@+import { observer } from 'mobx-react-lite'+import { useRouter } from 'next/router'+import { ReactElement, useEffect } from 'react'++import Error from 'components/ui/Error'+import ProductMenu from 'components/ui/ProductMenu'+import { useIsFeatureEnabled, useSelectedProject, useStore, withAuth } from 'hooks'+import { PROJECT_STATUS } from 'lib/constants'+import ProjectLayout from '../'+import { generateDocsMenu } from './DocsLayout.utils'+import { useIsAPIDocsSidePanelEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'++function DocsLayout({ title, children }: { title: string; children: ReactElement }) {+ const router = useRouter()+ const { ui, meta } = useStore()+ const { data, isLoading, error } = meta.openApi+ const selectedProject = useSelectedProject()+ const isPaused = selectedProject?.status === PROJECT_STATUS.INACTIVE++ const isNewAPIDocsEnabled = useIsAPIDocsSidePanelEnabled()+ const hideMenu = isNewAPIDocsEnabled && router.pathname.endsWith('/graphiql')++ const { projectAuthAll: authEnabled } = useIsFeatureEnabled(['project_auth:all'])++ const getPage = () => {+ if (router.pathname.endsWith('graphiql')) return 'graphiql'++ const { page, resource } = router.query+ if (!page && !resource) return 'introduction'+ return (page || resource || '') as string+ }++ useEffect(() => {+ if (ui.selectedProjectRef && !isPaused) {+ meta.openApi.load()+ }+ }, [ui.selectedProjectRef, isPaused])++ if (error) {+ return (+ <ProjectLayout product="API Docs">+ <Error error={error} />+ </ProjectLayout>+ )+ }++ const projectRef = selectedProject?.ref ?? 'default'+ const tableNames = (data?.tables ?? []).map((table: any) => table.name)+ const functionNames = (data?.functions ?? []).map((fn: any) => fn.name)++ return (+ <ProjectLayout+ title={title || 'API Docs'}+ isLoading={isLoading}+ product="API Docs"+ productMenu={+ !hideMenu && (+ <ProductMenu+ page={getPage()}+ menu={generateDocsMenu(projectRef, tableNames, functionNames, { authEnabled })}+ />+ )+ }+ >+ {children}+ </ProjectLayout>+ )+}++export default withAuth(observer(DocsLayout))diff --git a/studio/components/layouts/DocsLayout/DocsLayout.utils.tsx b/studio/components/layouts/DocsLayout/DocsLayout.utils.tsxnew file mode 100644index 00000000000..beb9bf2efce--- /dev/null+++ b/studio/components/layouts/DocsLayout/DocsLayout.utils.tsx@@ -0,0 +1,109 @@+import SVG from 'react-inlinesvg'+import { ProductMenuGroup } from 'components/ui/ProductMenu/ProductMenu.types'+import { IconBook, IconBookOpen } from 'ui'+import { BASE_PATH } from 'lib/constants'++export const generateDocsMenu = (+ ref: string,+ tables: string[],+ functions: string[],+ flags?: { authEnabled: boolean }+): ProductMenuGroup[] => {+ return [+ {+ title: 'Getting Started',+ items: [+ { name: 'Introduction', key: 'introduction', url: `/project/${ref}/api`, items: [] },+ {+ name: 'Authentication',+ key: 'auth',+ url: `/project/${ref}/api?page=auth`,+ items: [],+ },+ ...(flags?.authEnabled+ ? [+ {+ name: 'User Management',+ key: 'users',+ url: `/project/${ref}/api?page=users`,+ items: [],+ },+ ]+ : []),+ ],+ },+ {+ title: 'Tables and Views',+ items: [+ {+ name: 'Introduction',+ key: 'tables-intro',+ url: `/project/${ref}/api?page=tables-intro`,+ items: [],+ },+ ...tables.sort().map((table) => {+ return {+ name: table,+ key: table,+ url: `/project/${ref}/api?resource=${table}`,+ items: [],+ }+ }),+ ],+ },+ {+ title: 'Stored Procedures',+ items: [+ {+ name: 'Introduction',+ key: 'rpc-intro',+ url: `/project/${ref}/api?page=rpc-intro`,+ items: [],+ },+ ...functions.map((fn) => {+ return { name: fn, key: fn, url: `/project/${ref}/api?rpc=${fn}`, items: [] }+ }),+ ],+ },+ {+ title: 'GraphQL',+ items: [+ {+ name: 'GraphiQL',+ key: 'graphiql',+ url: `/project/${ref}/api/graphiql`,+ icon: (+ <SVG+ src={`${BASE_PATH}/img/graphql.svg`}+ style={{ width: `${16}px`, height: `${16}px` }}+ className="text-foreground"+ preProcessor={(code) => code.replace(/svg/, 'svg class="m-auto text-color-inherit"')}+ />+ ),+ items: [],+ },+ ],+ },+ {+ title: 'More Resources',+ items: [+ {+ name: 'Guides',+ key: 'guides',+ url: `https://supabase.com/docs`,+ icon: <IconBook size={14} strokeWidth={2} />,+ items: [],+ isExternal: true,+ },+ {+ name: 'API Reference',+ key: 'api-reference',+ url: `https://supabase.com/docs/guides/api`,+ icon: <IconBookOpen size={14} strokeWidth={2} />,+ items: [],+ isExternal: true,+ },+ ],+ },+ ]+}diff --git a/studio/components/layouts/FunctionsLayout.tsx b/studio/components/layouts/FunctionsLayout.tsxindex 7ade497184b..ebeed817dc1 100644--- a/studio/components/layouts/FunctionsLayout.tsx+++ b/studio/components/layouts/FunctionsLayout.tsx@@ -5,12 +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 APIDocsButton from 'components/ui/APIDocsButton'import NoPermission from 'components/ui/NoPermission'import { useEdgeFunctionQuery } from 'data/edge-functions/edge-function-query'import { useEdgeFunctionsQuery } from 'data/edge-functions/edge-functions-query'import { useCheckPermissions, withAuth } from 'hooks'-import { useAppStateSnapshot } from 'state/app-state'import FunctionsNav from '../interfaces/Functions/FunctionsNav'import ProjectLayout from './'@@ -19,8 +19,8 @@ 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 })@@ -113,13 +113,15 @@ const FunctionsLayout = ({ title, children }: PropsWithChildren<FunctionsLayoutP<Button asChild type="default"><Link href={`/project/${ref}/settings/functions`}>Manage secrets</Link></Button>- <APIDocsButton- section={- functionSlug !== undefined- ? ['edge-functions', functionSlug]- : ['edge-functions']- }- />+ {isNewAPIDocsEnabled && (+ <APIDocsButton+ section={+ functionSlug !== undefined+ ? ['edge-functions', functionSlug]+ : ['edge-functions']+ }+ />+ )}<ButtonasChildtype="default"diff --git a/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.tsx b/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.tsxindex 2ef5eba751a..a4f08f32f3b 100644--- a/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.tsx+++ b/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.tsx@@ -37,6 +37,7 @@ import {generateToolRoutes,} from './NavigationBar.utils'import NavigationIconButton from './NavigationIconButton'+import { useIsAPIDocsSidePanelEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'const NavigationBar = () => {const os = detectOS()@@ -50,6 +51,7 @@ const NavigationBar = () => {const navLayoutV2 = useFlag('navigationLayoutV2')const supabaseAIEnabled = useFlag('sqlEditorSupabaseAI')const showFeaturePreviews = useFlag('featurePreviews')+ const isNewAPIDocsEnabled = useIsAPIDocsSidePanelEnabled()const {projectAuthAll: authEnabled,@@ -119,7 +121,7 @@ const NavigationBar = () => {))}<div className="h-px w-full bg-border"></div>{otherRoutes.map((route) => {- if (route.key === 'api') {+ if (route.key === 'api' && isNewAPIDocsEnabled) {return (<Tooltip.Root delayDuration={0} key={route.key}><Tooltip.Trigger asChild>diff --git a/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.utils.tsx b/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.utils.tsxindex 3d64960358a..d06acaae64c 100644--- a/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.utils.tsx+++ b/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.utils.tsx@@ -221,7 +221,7 @@ export const generateOtherRoutes = (ref?: string, project?: ProjectBase): Route[key: 'api',label: 'API Docs',icon: <IconFileText size={18} strokeWidth={2} />,- link: undefined,+ link: ref && (isProjectBuilding ? buildingUrl : `/project/${ref}/api`),},...(IS_PLATFORM? [diff --git a/studio/components/layouts/index.ts b/studio/components/layouts/index.tsindex 4357b8a770d..fed0a94a6e0 100644--- a/studio/components/layouts/index.ts+++ b/studio/components/layouts/index.ts@@ -1,45 +1,45 @@+import AccountLayout, { AccountLayoutWithoutAuth } from './AccountLayout/AccountLayout'import AuthLayout from './AuthLayout/AuthLayout'-import SignInLayout from './SignInLayout/SignInLayout'-import ForgotPasswordLayout from './SignInLayout/ForgotPasswordLayout'+import BillingLayout from './BillingLayout'+import DatabaseLayout from './DatabaseLayout/DatabaseLayout'+import DocsLayout from './DocsLayout/DocsLayout'+import LogsLayout from './LogsLayout/LogsLayout'+import OrganizationLayout from './OrganizationLayout'import ProjectLayout, {- ProjectLayoutWithAuth,ProjectLayoutNonBlocking,+ ProjectLayoutWithAuth,} from './ProjectLayout/ProjectLayout'-import TableEditorLayout from './TableEditorLayout/TableEditorLayout'-import SQLEditorLayout from './SQLEditorLayout/SQLEditorLayout'-import DatabaseLayout from './DatabaseLayout/DatabaseLayout'import SettingsLayout from './ProjectSettingsLayout/SettingsLayout'+import ReportsLayout from './ReportsLayout/ReportsLayout'+import SQLEditorLayout from './SQLEditorLayout/SQLEditorLayout'+import ForgotPasswordLayout from './SignInLayout/ForgotPasswordLayout'+import SignInLayout from './SignInLayout/SignInLayout'import StorageLayout from './StorageLayout/StorageLayout'-import AccountLayout from './AccountLayout/AccountLayout'-import { AccountLayoutWithoutAuth } from './AccountLayout/AccountLayout'-import WizardLayout from './WizardLayout'-import { WizardLayoutWithoutAuth } from './WizardLayout'+import TableEditorLayout from './TableEditorLayout/TableEditorLayout'import VercelIntegrationLayout from './VercelIntegrationLayout'-import BillingLayout from './BillingLayout'-import LogsLayout from './LogsLayout/LogsLayout'-import ReportsLayout from './ReportsLayout/ReportsLayout'-import OrganizationLayout from './OrganizationLayout'+import WizardLayout, { WizardLayoutWithoutAuth } from './WizardLayout'export {- ProjectLayoutWithAuth,- ProjectLayoutNonBlocking,+ AccountLayout,+ AccountLayoutWithoutAuth,AuthLayout,- SignInLayout,- ForgotPasswordLayout,+ BillingLayout,DatabaseLayout,- TableEditorLayout,+ DocsLayout,+ ForgotPasswordLayout,+ LogsLayout,+ OrganizationLayout,+ ProjectLayoutNonBlocking,+ ProjectLayoutWithAuth,+ ReportsLayout,SQLEditorLayout,SettingsLayout,+ SignInLayout,StorageLayout,- AccountLayout,- AccountLayoutWithoutAuth,+ TableEditorLayout,+ VercelIntegrationLayout,WizardLayout,WizardLayoutWithoutAuth,- VercelIntegrationLayout,- BillingLayout,- LogsLayout,- ReportsLayout,- OrganizationLayout,}export default ProjectLayoutdiff --git a/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerHeader.tsx b/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerHeader.tsxindex faf394a62d0..289a0ce414e 100644--- a/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerHeader.tsx+++ b/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerHeader.tsx@@ -38,6 +38,7 @@ import { useStorageExplorerStateSnapshot } from 'state/storage-explorer'import { STORAGE_SORT_BY, STORAGE_SORT_BY_ORDER, STORAGE_VIEWS } from '../Storage.constants'import { useAppStateSnapshot } from 'state/app-state'import APIDocsButton from 'components/ui/APIDocsButton'+import { useIsAPIDocsSidePanelEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'const VIEW_OPTIONS = [{ key: STORAGE_VIEWS.COLUMNS, name: 'As columns' },@@ -140,8 +141,8 @@ 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('')@@ -514,11 +515,14 @@ const FileExplorerHeader = ({)}</div>- <div className="h-6 border-r border-control" />-- <div className="mx-2">- <APIDocsButton section={['storage', selectedBucket.name]} />- </div>+ {isNewAPIDocsEnabled && (+ <>+ <div className="h-6 border-r border-control" />+ <div className="mx-2">+ <APIDocsButton section={['storage', selectedBucket.name]} />+ </div>+ </>+ )}</div></div>)diff --git a/studio/next.config.js b/studio/next.config.jsindex fab20a78315..1521074f428 100644--- a/studio/next.config.js+++ b/studio/next.config.js@@ -116,6 +116,11 @@ const nextConfig = {destination: '/project/:ref/database/tables',permanent: true,},+ {+ source: '/project/:ref/database/graphiql',+ destination: '/project/:ref/api/graphiql',+ permanent: true,+ },{source: '/project/:ref/storage',destination: '/project/:ref/storage/buckets',diff --git a/studio/pages/project/[ref]/database/graphiql.tsx b/studio/pages/project/[ref]/api/graphiql.tsxsimilarity index 94%rename from studio/pages/project/[ref]/database/graphiql.tsxrename to studio/pages/project/[ref]/api/graphiql.tsxindex 3dcfec5dd06..bd72fde7eed 100644--- a/studio/pages/project/[ref]/database/graphiql.tsx+++ b/studio/pages/project/[ref]/api/graphiql.tsx@@ -1,24 +1,24 @@+import '@graphiql/react/dist/style.css'import { createGraphiQLFetcher, Fetcher } from '@graphiql/toolkit'+import { useParams } from 'common'import { observer } from 'mobx-react-lite'+import { useTheme } from 'next-themes'import { useEffect, useMemo } from 'react'-import '@graphiql/react/dist/style.css'-import { useParams } from 'common/hooks'import ExtensionCard from 'components/interfaces/Database/Extensions/ExtensionCard'import GraphiQL from 'components/interfaces/GraphQL/GraphiQL'-import { DatabaseLayout } from 'components/layouts'+import { DocsLayout } from 'components/layouts'import Connecting from 'components/ui/Loading/Loading'import { useSessionAccessTokenQuery } from 'data/auth/session-access-token-query'import { useProjectApiQuery } from 'data/config/project-api-query'import { useStore } from 'hooks'import { API_URL, IS_PLATFORM } from 'lib/constants'-import { useTheme } from 'next-themes'import { NextPageWithLayout } from 'types'const GraphiQLPage: NextPageWithLayout = () => {- const { ref: projectRef } = useParams()const { ui, meta } = useStore()const { resolvedTheme } = useTheme()+ const { ref: projectRef } = useParams()const currentTheme = resolvedTheme === 'dark' ? 'dark' : 'light'const isExtensionsLoading = meta.extensions.isLoading@@ -83,6 +83,5 @@ const GraphiQLPage: NextPageWithLayout = () => {return <GraphiQL fetcher={fetcher} theme={currentTheme} accessToken={anonKey} />}-GraphiQLPage.getLayout = (page) => <DatabaseLayout title="GraphiQL">{page}</DatabaseLayout>-+GraphiQLPage.getLayout = (page) => <DocsLayout title="GraphiQL">{page}</DocsLayout>export default observer(GraphiQLPage)diff --git a/studio/pages/project/[ref]/api/index.tsx b/studio/pages/project/[ref]/api/index.tsxnew file mode 100644index 00000000000..c159b220e02--- /dev/null+++ b/studio/pages/project/[ref]/api/index.tsx@@ -0,0 +1,164 @@+import { useParams } from 'common'+import { observer, useLocalObservable } from 'mobx-react-lite'+import { useRouter } from 'next/router'+import { createContext, useContext, useEffect, useState } from 'react'++import { GeneralContent, ResourceContent, RpcContent } from 'components/interfaces/Docs'+import LangSelector from 'components/interfaces/Docs/LangSelector'+import { DocsLayout } from 'components/layouts'+import { useProjectApiQuery } from 'data/config/project-api-query'+import { useProjectJsonSchemaQuery } from 'data/docs/project-json-schema-query'+import { snakeToCamel } from 'lib/helpers'+import { NextPageWithLayout } from 'types'++const PageContext = createContext(null)++const PageConfig: NextPageWithLayout = () => {+ const PageState: any = useLocalObservable(() => ({+ projectRef: '',+ jsonSchema: {},+ resources: {},+ rpcs: {},+ setJsonSchema(value: any) {+ const { paths } = value || {}+ const functionPath = 'rpc/'+ let resources: any = {}+ let rpcs: any = {}++ Object.entries(paths || []).forEach(([name, val]) => {+ let trimmed = name.slice(1)+ let id = trimmed.replace(functionPath, '')+ let displayName = id.replace(/_/g, ' ')+ let camelCase = snakeToCamel(id)+ let enriched = { id, displayName, camelCase }+ if (!trimmed.length) return+ else if (trimmed.includes(functionPath)) rpcs[id] = enriched+ else resources[id] = enriched+ })++ PageState.jsonSchema = value+ PageState.resources = resources+ PageState.rpcs = rpcs+ },+ }))++ const router = useRouter()+ const { query } = router+ PageState.projectRef = query.ref++ return (+ <PageContext.Provider value={PageState}>+ <DocView />+ </PageContext.Provider>+ )+}++PageConfig.getLayout = (page) => <DocsLayout title="API">{page}</DocsLayout>++export default observer(PageConfig)++const DEFAULT_KEY = { name: 'hide', key: 'SUPABASE_KEY' }++const DocView = observer(() => {+ const PageState: any = useContext(PageContext)+ const { ref: projectRef, page, resource, rpc } = useParams()+ const [selectedLang, setSelectedLang] = useState<any>('js')+ const [showApiKey, setShowApiKey] = useState<any>(DEFAULT_KEY)++ const { data, error } = useProjectApiQuery({+ projectRef,+ })++ const apiService = data?.autoApiService+ const anonKey = apiService?.service_api_keys.find((x) => x.name === 'anon key')+ ? apiService.defaultApiKey+ : undefined++ const {+ data: jsonSchema,+ error: jsonSchemaError,+ refetch,+ } = useProjectJsonSchemaQuery({ projectRef })++ useEffect(() => {+ PageState.setJsonSchema(jsonSchema)+ }, [jsonSchema])++ const refreshDocs = async () => {+ await refetch()+ }++ if (error || jsonSchemaError)+ return (+ <div className="p-6 mx-auto text-center sm:w-full md:w-3/4">+ <p className="text-foreground-light">+ <p>Error connecting to API</p>+ <p>{`${error || jsonSchemaError}`}</p>+ </p>+ </div>+ )+ if (!data || !jsonSchema || !PageState.jsonSchema)+ return (+ <div className="p-6 mx-auto text-center sm:w-full md:w-3/4">+ <h3 className="text-xl">Building docs ...</h3>+ </div>+ )++ // Data Loaded+ const autoApiService = {+ ...data.autoApiService,+ endpoint: `${data.autoApiService.protocol ?? 'https'}://${data.autoApiService.endpoint ?? '-'}`,+ }++ const { paths, definitions } = PageState.jsonSchema++ const PAGE_KEY: any = resource || rpc || page || 'index'++ return (+ <div className="w-full h-full overflow-y-auto Docs Docs--api-page" key={PAGE_KEY}>+ <div className="Docs--inner-wrapper">+ <div className="sticky top-0 z-40 flex flex-row-reverse w-full ">+ <LangSelector+ selectedLang={selectedLang}+ setSelectedLang={setSelectedLang}+ showApiKey={showApiKey}+ setShowApiKey={setShowApiKey}+ apiKey={anonKey}+ autoApiService={autoApiService}+ />+ </div>+ <div className="">+ {resource ? (+ <ResourceContent+ autoApiService={autoApiService}+ selectedLang={selectedLang}+ resourceId={resource}+ resources={PageState.resources}+ definitions={definitions}+ paths={paths}+ showApiKey={showApiKey.key}+ refreshDocs={refreshDocs}+ />+ ) : rpc ? (+ <RpcContent+ autoApiService={autoApiService}+ selectedLang={selectedLang}+ rpcId={rpc}+ paths={paths}+ rpcs={PageState.rpcs}+ showApiKey={showApiKey.key}+ refreshDocs={refreshDocs}+ />+ ) : (+ <GeneralContent+ autoApiService={autoApiService}+ selectedLang={selectedLang}+ showApiKey={showApiKey.key}+ page={page}+ />+ )}+ </div>+ </div>+ </div>+ )+})diff --git a/studio/state/app-state.ts b/studio/state/app-state.tsindex b85ddf1b8d7..b04623aab6c 100644--- a/studio/state/app-state.ts+++ b/studio/state/app-state.ts@@ -23,6 +23,7 @@ export const appState = proxy({},activeDocsSection: ['introduction'],+ docsLanguage: 'js' as 'js' | 'bash',showProjectApiDocs: false,setShowProjectApiDocs: (value: boolean) => {appState.showProjectApiDocs = value@@ -30,6 +31,9 @@ export const appState = proxy({setActiveDocsSection: (value: string[]) => {appState.activeDocsSection = value},+ setDocsLanguage: (value: 'js' | 'bash') => {+ appState.docsLanguage = value+ },isOptedInTelemetry: false,setIsOptedInTelemetry: (value: boolean) => {