The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(studio): use bucket pagination for api docs (#41090)
Charis9225eebccb0f
diff --git a/apps/studio/components/interfaces/ProjectAPIDocs/Content/Bucket.tsx b/apps/studio/components/interfaces/ProjectAPIDocs/Content/Bucket.tsxindex b366b1f17e4..1da02d31f55 100644--- a/apps/studio/components/interfaces/ProjectAPIDocs/Content/Bucket.tsx+++ b/apps/studio/components/interfaces/ProjectAPIDocs/Content/Bucket.tsx@@ -1,7 +1,8 @@import { useParams } from 'common'import { Badge } from 'ui'-import { useBucketsQuery } from 'data/storage/buckets-query'+import { useQueryClient } from '@tanstack/react-query'+import { useBucketInfoQueryPreferCached } from 'data/storage/buckets-query'import { formatBytes } from 'lib/helpers'import { useAppStateSnapshot } from 'state/app-state'import { DOCS_RESOURCE_CONTENT } from '../ProjectAPIDocs.constants'@@ -9,13 +10,13 @@ import ResourceContent from '../ResourceContent'import type { ContentProps } from './Content.types'export const Bucket = ({ language, apikey, endpoint }: ContentProps) => {+ const queryClient = useQueryClient()const { ref } = useParams()- const snap = useAppStateSnapshot()- const { data } = useBucketsQuery({ projectRef: ref })+ const snap = useAppStateSnapshot()const resource = snap.activeDocsSection[1]- const buckets = data ?? []- const bucket = buckets.find((b) => b.name === resource)++ const bucket = useBucketInfoQueryPreferCached(resource, ref)const allowedMimeTypes = bucket?.allowed_mime_typesconst maxFileSizeLimit = bucket?.file_size_limitdiff --git a/apps/studio/components/interfaces/ProjectAPIDocs/Content/Content.utils.ts b/apps/studio/components/interfaces/ProjectAPIDocs/Content/Content.utils.tsindex da308eb6068..1310c97b20b 100644--- a/apps/studio/components/interfaces/ProjectAPIDocs/Content/Content.utils.ts+++ b/apps/studio/components/interfaces/ProjectAPIDocs/Content/Content.utils.ts@@ -1,7 +1,14 @@export const navigateToSection = (key: string) => {if (typeof window !== 'undefined') {+ const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches+const el = document.getElementById(key)- if (el) el.scrollIntoView({ behavior: 'smooth' })+ if (el) {+ el.scrollIntoView({ behavior: prefersReducedMotion ? 'instant' : 'smooth' })+ // Timeout needed to make sure the focus behavior doesn't interrupt the+ // scrolling. Timing selected by trial and error.+ setTimeout(() => el.focus(), 300)+ }}}diff --git a/apps/studio/components/interfaces/ProjectAPIDocs/ContentSnippet.tsx b/apps/studio/components/interfaces/ProjectAPIDocs/ContentSnippet.tsxindex 7c9cc1a9f51..01804b8d584 100644--- a/apps/studio/components/interfaces/ProjectAPIDocs/ContentSnippet.tsx+++ b/apps/studio/components/interfaces/ProjectAPIDocs/ContentSnippet.tsx@@ -1,10 +1,10 @@import { useParams } from 'common'-import { SimpleCodeBlock } from 'ui'-import { Markdown } from '../Markdown'-import { PropsWithChildren } from 'react'import { useSendEventMutation } from 'data/telemetry/send-event-mutation'import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'+import { PropsWithChildren } from 'react'+import { SimpleCodeBlock } from 'ui'+import { Markdown } from '../Markdown'interface ContentSnippetProps {apikey?: string@@ -51,9 +51,11 @@ const ContentSnippet = ({}return (- <div id={snippet.key} className="space-y-4 py-6 pb-2 last:pb-6">+ <div className="space-y-4 py-6 pb-2 last:pb-6"><div className="px-4 space-y-4">- <h2 className="doc-heading">{snippet.title}</h2>+ <h2 id={snippet.key} tabIndex={-1} className="doc-heading">+ {snippet.title}+ </h2>{snippet.description !== undefined && (<div className="doc-section"><article className="text text-sm text-foreground-light">diff --git a/apps/studio/components/interfaces/ProjectAPIDocs/FirstLevelNav.tsx b/apps/studio/components/interfaces/ProjectAPIDocs/FirstLevelNav.tsxindex b915dcc99e5..ce2206a198b 100644--- a/apps/studio/components/interfaces/ProjectAPIDocs/FirstLevelNav.tsx+++ b/apps/studio/components/interfaces/ProjectAPIDocs/FirstLevelNav.tsx@@ -1,25 +1,41 @@-import { useParams } from 'common'import Link from 'next/link'-import { Fragment } from 'react'+import { Fragment, type ReactNode } from 'react'import SVG from 'react-inlinesvg'+import { useParams } from 'common'+import { InfiniteListDefault, type RowComponentBaseProps } from 'components/ui/InfiniteList'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 { usePaginatedBucketsQuery, type Bucket } from 'data/storage/buckets-query'import { useIsFeatureEnabled } from 'hooks/misc/useIsFeatureEnabled'import { BASE_PATH, DOCS_URL } from 'lib/constants'import { Book, BookOpen } from 'lucide-react'import { useAppStateSnapshot } from 'state/app-state'-import { Button } from 'ui'+import { Button, cn } from 'ui'+import { ShimmeringLoader } from 'ui-patterns'import { navigateToSection } from './Content/Content.utils'-import { DOCS_CONTENT, DOCS_MENU } from './ProjectAPIDocs.constants'+import { API_DOCS_CATEGORIES, DOCS_CONTENT, DOCS_MENU } from './ProjectAPIDocs.constants'-const Separator = () => <div className="border-t !mt-3 pb-1 mx-3" />+type DocsSections = typeof DOCS_MENU+type DocsSection = DocsSections[number]+type DocsSectionsSubset = readonly DocsSection[]+type DocsCategory = DocsSection['key']+type DocsContentRegistry = typeof DOCS_CONTENT+type DocsSnippet = DocsContentRegistry[keyof DocsContentRegistry]-const FirstLevelNav = () => {- const { ref } = useParams()- const snap = useAppStateSnapshot()+const Separator = () => <hr className="border-t !mt-3 pb-1 mx-3" />++const MENU_BUTTON_CLASSES = cn(+ 'w-full px-4',+ 'text-left text-sm text-foreground-light',+ 'transition hover:text-foreground'+)+/**+ * Gets the docs menu items based on feature flags.+ * @returns An array of menu items to be displayed in the docs navigation.+ */+const useDocsMenu = (): DocsSectionsSubset => {const {projectAuthAll: authEnabled,projectStorageAll: storageEnabled,@@ -32,122 +48,59 @@ const FirstLevelNav = () => {'realtime:all',])- const docsMenu = DOCS_MENU.filter((item) => {+ return DOCS_MENU.filter((item) => {if (item.key === 'user-management') return authEnabledif (item.key === 'storage') return storageEnabledif (item.key === 'edge-functions') return edgeFunctionsEnabledif (item.key === 'realtime') return realtimeEnabledreturn true})+}- const { data } = useOpenAPISpecQuery({ projectRef: ref })- const tables = data?.tables ?? []- const functions = data?.functions ?? []+/**+ * Gets the content snippets for a given documentation category.+ * @param category - The category of documentation to retrieve snippets for.+ * @returns An array of content snippets belonging to the specified category.+ */+const getSectionSnippets = (category: DocsCategory): DocsSnippet[] =>+ Object.values(DOCS_CONTENT).filter((snippet) => snippet.category === category)++export const FirstLevelNav = (): ReactNode => {+ const { ref } = useParams()- const { data: buckets } = useBucketsQuery({ projectRef: ref })- const { data: edgeFunctions } = useEdgeFunctionsQuery({ projectRef: ref })+ const snap = useAppStateSnapshot()+ const currentSection = snap.activeDocsSection[0]++ const docsMenu = useDocsMenu()return (<>- <div className="px-2 py-4 border-b">+ <nav aria-labelledby="api-docs-rest-categories" className="px-2 py-4 border-b">+ <h2 id="api-docs-rest-categories" className="sr-only">+ REST API Docs+ </h2>{docsMenu.map((item) => {- const isActive = snap.activeDocsSection[0] === item.key- const sections = Object.values(DOCS_CONTENT).filter(- (snippet) => snippet.category === item.key- )+ const isActive = currentSection === item.key- // [Joshen] Need to find the right UI component for accessbilityreturn (<Fragment key={item.key}>- <div- className={`cursor-pointer text-sm py-2 px-3 rounded-md transition ${- isActive ? 'bg-surface-300' : ''- }`}+ <button+ aria-current={isActive ? 'page' : undefined}+ className={cn(+ 'w-full px-3 py-2 rounded-md',+ 'text-left text-sm',+ 'transition',+ isActive && 'bg-surface-300'+ )}onClick={() => snap.setActiveDocsSection([item.key])}>{item.name}- </div>- {isActive && sections.length > 0 && (- <div className="space-y-2 py-2">- {sections.map((section) => (- <p- key={section.key}- title={section.title}- className="text-sm text-foreground-light px-4 hover:text-foreground transition cursor-pointer"- onClick={() => {- snap.setActiveDocsSection([item.key])- navigateToSection(section.key)- }}- >- {section.title}- </p>- ))}- {item.key === 'entities' && (- <>- {tables.length > 0 && <Separator />}- {tables.map((table) => (- <p- key={table.name}- title={table.name}- className="text-sm text-foreground-light px-4 hover:text-foreground transition cursor-pointer"- onClick={() => snap.setActiveDocsSection([item.key, table.name])}- >- {table.name}- </p>- ))}- </>- )}- {item.key === 'stored-procedures' && (- <>- {functions.length > 0 && <Separator />}- {functions.map((fn) => (- <p- key={fn.name}- title={fn.name}- className="text-sm text-foreground-light px-4 hover:text-foreground transition cursor-pointer"- onClick={() => snap.setActiveDocsSection([item.key, fn.name])}- >- {fn.name}- </p>- ))}- </>- )}- {item.key === 'storage' && (- <>- {(buckets ?? []).length > 0 && <Separator />}- {(buckets ?? []).map((bucket) => (- <p- key={bucket.name}- title={bucket.name}- className="text-sm text-foreground-light px-4 hover:text-foreground transition cursor-pointer"- onClick={() => snap.setActiveDocsSection([item.key, bucket.name])}- >- {bucket.name}- </p>- ))}- </>- )}- {item.key === 'edge-functions' && (- <>- {(edgeFunctions ?? []).length > 0 && <Separator />}- {(edgeFunctions ?? []).map((fn) => (- <p- key={fn.name}- title={fn.name}- className="text-sm text-foreground-light px-4 hover:text-foreground transition cursor-pointer"- onClick={() => snap.setActiveDocsSection([item.key, fn.name])}- >- {fn.name}- </p>- ))}- </>- )}- </div>- )}+ </button>+ {isActive && <Subsections category={item.key} />}</Fragment>)})}- </div>+ </nav><div className="px-2 py-4 border-b"><Button@@ -202,4 +155,164 @@ const FirstLevelNav = () => {)}-export default FirstLevelNav+type SubsectionsProps = {+ category: DocsCategory+}++const Subsections = ({ category }: SubsectionsProps): ReactNode => {+ const snippets = getSectionSnippets(category)++ return (+ <div className="space-y-2 py-2">+ {snippets.map((snippet) => (+ <button+ key={snippet.key}+ className={MENU_BUTTON_CLASSES}+ onClick={() => {+ navigateToSection(snippet.key)+ }}+ >+ {snippet.title}+ </button>+ ))}+ {category === API_DOCS_CATEGORIES.ENTITIES && <TablesSubsections />}+ {category === API_DOCS_CATEGORIES.STORED_PROCEDURES && <DbFunctionsSubsections />}+ {category === API_DOCS_CATEGORIES.STORAGE && <StorageSubsections />}+ {category === API_DOCS_CATEGORIES.EDGE_FUNCTIONS && <EdgeFunctionsSubsections />}+ </div>+ )+}++const TablesSubsections = (): ReactNode => {+ const { ref } = useParams()+ const snap = useAppStateSnapshot()++ const { data, isLoading } = useOpenAPISpecQuery(+ { projectRef: ref },+ { staleTime: 1000 * 60 * 10 }+ )+ const tables = data?.tables ?? []++ // TODO: handle infinite loading of tables+ return (+ <>+ {isLoading && <LoadingIndicator />}+ {tables.length > 0 && <Separator />}+ {tables.map((table) => (+ <button+ key={table.name}+ className={MENU_BUTTON_CLASSES}+ onClick={() => snap.setActiveDocsSection([API_DOCS_CATEGORIES.ENTITIES, table.name])}+ >+ {table.name}+ </button>+ ))}+ </>+ )+}++const DbFunctionsSubsections = (): ReactNode => {+ const { ref } = useParams()+ const snap = useAppStateSnapshot()++ const { data, isLoading } = useOpenAPISpecQuery(+ { projectRef: ref },+ { staleTime: 1000 * 60 * 10 }+ )+ const functions = data?.functions ?? []++ // TODO: handle virtualization of DB functions+ return (+ <>+ {isLoading && <LoadingIndicator />}+ {functions.length > 0 && <Separator />}+ {functions.map((fn) => (+ <button+ key={fn.name}+ className={MENU_BUTTON_CLASSES}+ onClick={() =>+ snap.setActiveDocsSection([API_DOCS_CATEGORIES.STORED_PROCEDURES, fn.name])+ }+ >+ {fn.name}+ </button>+ ))}+ </>+ )+}++const BucketButton = ({ item: bucket, style }: RowComponentBaseProps<Bucket>) => {+ const snap = useAppStateSnapshot()++ return (+ <button+ key={bucket.name}+ className={cn(MENU_BUTTON_CLASSES, 'py-1')}+ style={style}+ onClick={() => snap.setActiveDocsSection([API_DOCS_CATEGORIES.STORAGE, bucket.name])}+ >+ {bucket.name}+ </button>+ )+}++const StorageSubsections = (): ReactNode => {+ const { ref } = useParams()++ const { data, isLoading, isFetchingNextPage, hasNextPage, fetchNextPage } =+ usePaginatedBucketsQuery({+ projectRef: ref,+ })+ const buckets = data?.pages.flatMap((page) => page) ?? []++ return (+ <>+ {isLoading && <LoadingIndicator />}+ {buckets.length > 0 && <Separator />}+ <InfiniteListDefault+ className="max-h-80"+ items={buckets}+ getItemKey={(idx) => buckets[idx]?.name}+ getItemSize={() => 28}+ hasNextPage={!!hasNextPage}+ isLoadingNextPage={isFetchingNextPage}+ onLoadNextPage={fetchNextPage}+ ItemComponent={BucketButton}+ LoaderComponent={({ style }) => <LoadingIndicator style={{ ...style, width: '75%' }} />}+ />+ </>+ )+}++const EdgeFunctionsSubsections = (): ReactNode => {+ const { ref } = useParams()+ const snap = useAppStateSnapshot()++ const { data: edgeFunctions, isLoading } = useEdgeFunctionsQuery({ projectRef: ref })++ // TODO: handle virtualization of edge functions+ return (+ <>+ {isLoading && <LoadingIndicator />}+ {(edgeFunctions ?? []).length > 0 && <Separator />}+ {(edgeFunctions ?? []).map((fn) => (+ <button+ key={fn.name}+ className={MENU_BUTTON_CLASSES}+ onClick={() => snap.setActiveDocsSection([API_DOCS_CATEGORIES.EDGE_FUNCTIONS, fn.name])}+ >+ {fn.name}+ </button>+ ))}+ </>+ )+}++type LoadingIndicatorProps = {+ className?: string+ style?: React.CSSProperties+}++const LoadingIndicator = ({ className, style }: LoadingIndicatorProps) => (+ <ShimmeringLoader style={style} className={cn('mx-2', className)} />+)diff --git a/apps/studio/components/interfaces/ProjectAPIDocs/ProjectAPIDocs.constants.ts b/apps/studio/components/interfaces/ProjectAPIDocs/ProjectAPIDocs.constants.tsindex 93b1d3b7dfa..3ef5dc24ff5 100644--- a/apps/studio/components/interfaces/ProjectAPIDocs/ProjectAPIDocs.constants.ts+++ b/apps/studio/components/interfaces/ProjectAPIDocs/ProjectAPIDocs.constants.ts@@ -1,19 +1,29 @@import { DOCS_URL } from 'lib/constants'+export const API_DOCS_CATEGORIES = {+ INTRODUCTION: 'introduction',+ USER_MANAGEMENT: 'user-management',+ ENTITIES: 'entities',+ STORED_PROCEDURES: 'stored-procedures',+ STORAGE: 'storage',+ EDGE_FUNCTIONS: 'edge-functions',+ REALTIME: 'realtime',+}+export const DOCS_MENU = [- { name: 'Connect', key: 'introduction' },- { name: 'User Management', key: 'user-management' },- { name: 'Tables & Views', key: 'entities' },- { name: 'Stored Procedures', key: 'stored-procedures' },- { name: 'Storage', key: 'storage' },- { name: 'Edge Functions', key: 'edge-functions' },- { name: 'Realtime', key: 'realtime' },-]+ { name: 'Connect', key: API_DOCS_CATEGORIES.INTRODUCTION },+ { name: 'User Management', key: API_DOCS_CATEGORIES.USER_MANAGEMENT },+ { name: 'Tables & Views', key: API_DOCS_CATEGORIES.ENTITIES },+ { name: 'Stored Procedures', key: API_DOCS_CATEGORIES.STORED_PROCEDURES },+ { name: 'Storage', key: API_DOCS_CATEGORIES.STORAGE },+ { name: 'Edge Functions', key: API_DOCS_CATEGORIES.EDGE_FUNCTIONS },+ { name: 'Realtime', key: API_DOCS_CATEGORIES.REALTIME },+] as constexport const DOCS_CONTENT = {init: {key: 'introduction',- category: 'introduction',+ category: API_DOCS_CATEGORIES.INTRODUCTION,title: `Connect to your project`,description: `Projects have a RESTful endpoint that you can use with your project's API key to query and manage your database. Put these keys in your .env file.`,js: (apikey?: string, endpoint?: string) => `@@ -26,7 +36,7 @@ const supabase = createClient(supabaseUrl, supabaseKey)`,},clientApiKeys: {key: 'client-api-keys',- category: 'introduction',+ category: API_DOCS_CATEGORIES.INTRODUCTION,title: `Client API Keys`,description: `Client keys allow "anonymous access" to your database, until the user has logged in. After logging in, the keys will switch to the user's own login token.@@ -39,7 +49,7 @@ const supabase = createClient(SUPABASE_URL, process.env.SUPABASE_KEY);`,},serviceApiKeys: {key: 'service-keys',- category: 'introduction',+ category: API_DOCS_CATEGORIES.INTRODUCTION,title: `Service Keys`,description: `Service keys have *FULL* access to your data, bypassing any security policies. Be VERY careful where you expose these keys. They should only be used on a server and never on a client or browser.@@ -53,7 +63,7 @@ const supabase = createClient(SUPABASE_URL, process.env.SUPABASE_KEY);`,// User ManagementuserManagement: {key: 'user-management',- category: 'user-management',+ category: API_DOCS_CATEGORIES.USER_MANAGEMENT,title: `Introduction`,description: `Supabase makes it easy to manage your users.@@ -65,7 +75,7 @@ const supabase = createClient(SUPABASE_URL, process.env.SUPABASE_KEY);`,},signUp: {key: 'sign-up',- category: 'user-management',+ category: API_DOCS_CATEGORIES.USER_MANAGEMENT,title: `Sign up`,description: `Allow your users to sign up and create a new account@@ -86,7 +96,7 @@ curl -X POST '${endpoint}/auth/v1/signup' \\},emailLogin: {key: 'email-login',- category: 'user-management',+ category: API_DOCS_CATEGORIES.USER_MANAGEMENT,title: `Log in with Email/Password`,description: `If an account is created, users can login to your app.@@ -110,7 +120,7 @@ curl -X POST '${endpoint}/auth/v1/token?grant_type=password' \\},magicLinkLogin: {key: 'magic-link-login',- category: 'user-management',+ category: API_DOCS_CATEGORIES.USER_MANAGEMENT,title: `Log in with Magic Link via Email`,description: `Send a user a passwordless link which they can use to redeem an access_token.@@ -132,7 +142,7 @@ curl -X POST '${endpoint}/auth/v1/magiclink' \\},phoneLogin: {key: 'phone-log-in',- category: 'user-management',+ category: API_DOCS_CATEGORIES.USER_MANAGEMENT,title: `Sign up with Phone/Password`,description: `A phone number can be used instead of an email as a primary account confirmation mechanism.@@ -158,7 +168,7 @@ curl -X POST '${endpoint}/auth/v1/signup' \\},smsLogin: {key: 'sms-otp-log-in',- category: 'user-management',+ category: API_DOCS_CATEGORIES.USER_MANAGEMENT,title: `Login via SMS OTP`,description: `SMS OTPs work like magic links, except you have to provide an interface for the user to verify the 6 digit number they receive.@@ -180,7 +190,7 @@ curl -X POST '${endpoint}/auth/v1/otp' \\},smsVerify: {key: 'sms-verify',- category: 'user-management',+ category: API_DOCS_CATEGORIES.USER_MANAGEMENT,title: `Verify an SMS OTP`,description: `Once the user has received the OTP, have them enter it in a form and send it for verification@@ -206,7 +216,7 @@ curl -X POST '${endpoint}/auth/v1/verify' \\},oauthLogin: {key: 'oauth-login',- category: 'user-management',+ category: API_DOCS_CATEGORIES.USER_MANAGEMENT,title: `Log in with Third Party OAuth`,description: `Users can log in with Third Party OAuth like Google, Facebook, GitHub, and more. You must first enable each of these in the Auth Providers settings [here](https://supabase.com).@@ -225,7 +235,7 @@ const { data, error } = await supabase.auth.signInWithOAuth({},user: {key: 'get-user',- category: 'user-management',+ category: API_DOCS_CATEGORIES.USER_MANAGEMENT,title: `Get user`,description: `Get the JSON object for the logged in user.`,js: (apikey?: string, endpoint?: string) => `@@ -239,7 +249,7 @@ curl -X GET '${endpoint}/auth/v1/user' \\},forgotPassWordEmail: {key: 'forgot-password-email',- category: 'user-management',+ category: API_DOCS_CATEGORIES.USER_MANAGEMENT,title: `Forgot password / email`,description: `Sends the user a log in link via email. Once logged in you should direct the user to a new password form. And use "Update User" below to save the new password.`,js: (apikey?: string, endpoint?: string) => `@@ -256,7 +266,7 @@ curl -X POST '${endpoint}/auth/v1/recover' \\},updateUser: {key: 'update-user',- category: 'user-management',+ category: API_DOCS_CATEGORIES.USER_MANAGEMENT,title: `Update User`,description: `Update the user with a new email or password. Each key (email, password, and data) is optional.`,js: (apikey?: string, endpoint?: string) => `@@ -282,7 +292,7 @@ curl -X PUT '${endpoint}/auth/v1/user' \\},logout: {key: 'log-out',- category: 'user-management',+ category: API_DOCS_CATEGORIES.USER_MANAGEMENT,title: `Log out`,description: `After calling log out, all interactions using the Supabase JS client will be "anonymous".`,js: (apikey?: string, endpoint?: string) => `@@ -297,7 +307,7 @@ curl -X POST '${endpoint}/auth/v1/logout' \\},emailInvite: {key: 'email-invite',- category: 'user-management',+ category: API_DOCS_CATEGORIES.USER_MANAGEMENT,title: `Invite user over email`,description: `Send a user a passwordless link which they can use to sign up and log in.@@ -321,7 +331,7 @@ curl -X POST '${endpoint}/auth/v1/invite' \\// Storagestorage: {key: 'storage',- category: 'storage',+ category: API_DOCS_CATEGORIES.STORAGE,title: `Introduction`,description: `Supabase Storage makes it simple to upload and serve files of any size, providing a robust framework for file access controls.@@ -332,7 +342,7 @@ You can use Supabase Storage to store images, videos, documents, and any other f// Edge functionsedgeFunctions: {key: 'edge-function',- category: 'edge-functions',+ category: API_DOCS_CATEGORIES.EDGE_FUNCTIONS,title: 'Introduction',description: `Edge Functions are server-side TypeScript functions, distributed globally at the edge—close to your users. They can be used for listening to webhooks or integrating your Supabase project with third-parties like Stripe. Edge Functions are developed using Deno, which offers a few benefits to you as a developer:@@ -342,7 +352,7 @@ Edge Functions are server-side TypeScript functions, distributed globally at the},edgeFunctionsPreReq: {key: 'edge-function-pre-req',- category: 'edge-functions',+ category: API_DOCS_CATEGORIES.EDGE_FUNCTIONS,title: 'Pre-requisites',description: `Follow the steps to prepare your Supabase project on your local machine.@@ -358,7 +368,7 @@ Follow the steps to prepare your Supabase project on your local machine.},createEdgeFunction: {key: 'create-edge-function',- category: 'edge-functions',+ category: API_DOCS_CATEGORIES.EDGE_FUNCTIONS,title: 'Create an Edge Function',description: `Create a Supabase Edge Function locally via the Supabase CLI.@@ -370,7 +380,7 @@ supabase functions new hello-world},deployEdgeFunction: {key: 'deploy-edge-function',- category: 'edge-functions',+ category: API_DOCS_CATEGORIES.EDGE_FUNCTIONS,title: 'Deploy an Edge Function',description: `Deploy a Supabase Edge Function to your Supabase project via the Supabase CLI.@@ -382,7 +392,7 @@ Deploy a Supabase Edge Function to your Supabase project via the Supabase CLI.// EntitiesentitiesIntroduction: {key: 'entities-introduction',- category: 'entities',+ category: API_DOCS_CATEGORIES.ENTITIES,title: 'Introduction',description: `All views and tables in the \`public\` schema, and those accessible by the active database role for a request are available for querying via the API.@@ -394,7 +404,7 @@ If you don't want to expose tables in your API, simply add them to a different s},generatingTypes: {key: 'generating-types',- category: 'entities',+ category: API_DOCS_CATEGORIES.ENTITIES,title: 'Generating Types',description: `Supabase APIs are generated from your database, which means that we can use database introspection to generate type-safe API definitions.@@ -406,7 +416,7 @@ You can generate types from your database either through the [Supabase CLI](${DO},graphql: {key: 'graphql',- category: 'entities',+ category: API_DOCS_CATEGORIES.ENTITIES,title: 'GraphQL vs PostgREST',description: `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! The syntax is very similar. This example shows how you might achieve the same thing with Apollo GraphQL and Supabase.@@ -464,7 +474,7 @@ const { data, error } = await supabase// Stored ProceduresstoredProceduresIntroduction: {key: 'stored-procedures-introduction',- category: 'stored-procedures',+ category: API_DOCS_CATEGORIES.STORED_PROCEDURES,title: 'Introduction',description: `All of your database stored procedures are available on your API. This means you can build your logic directly into the database (if you're brave enough)!@@ -477,7 +487,7 @@ The API endpoint supports POST (and in some cases GET) to execute the function.// Realtimerealtime: {key: 'realtime-introduction',- category: 'realtime',+ category: API_DOCS_CATEGORIES.REALTIME,title: 'Introduction',description: `Supabase provides a globally distributed cluster of Realtime servers that enable the following functionality:@@ -491,7 +501,7 @@ Supabase provides a globally distributed cluster of Realtime servers that enable},subscribeChannel: {key: 'subscribe-to-channel',- category: 'realtime',+ category: API_DOCS_CATEGORIES.REALTIME,title: 'Subscribe to channel',description: `Creates an event handler that listens to changes.@@ -521,7 +531,7 @@ supabase},unsubscribeChannel: {key: 'unsubscribe-channel',- category: 'realtime',+ category: API_DOCS_CATEGORIES.REALTIME,title: 'Unsubscribe from a channel',description: `Unsubscribes and removes Realtime channel from Realtime client.@@ -533,7 +543,7 @@ Removing a channel is a great way to maintain the performance of your project's},unsubscribeChannels: {key: 'unsubscribe-channels',- category: 'realtime',+ category: API_DOCS_CATEGORIES.REALTIME,title: 'Unsubscribe from all channels',description: `Unsubscribes and removes all Realtime channels from Realtime client.@@ -545,7 +555,7 @@ Removing a channel is a great way to maintain the performance of your project's},retrieveAllChannels: {key: 'unsubscribe-channel',- category: 'realtime',+ category: API_DOCS_CATEGORIES.REALTIME,title: 'Unsubscribe from a channel',description: `Returns all Realtime channels.@@ -568,7 +578,7 @@ export const DOCS_RESOURCE_CONTENT: {rpcSingle: {key: 'invoke-function',title: 'Invoke function',- category: 'stored-procedures',+ category: API_DOCS_CATEGORIES.STORED_PROCEDURES,description: undefined,docsUrl: `${DOCS_URL}/reference/javascript/rpc`,code: ({@@ -625,7 +635,7 @@ else console.log(data)readRows: {key: 'read-rows',title: `Read rows`,- category: 'entities',+ category: API_DOCS_CATEGORIES.ENTITIES,docsUrl: `${DOCS_URL}/reference/javascript/select`,description: `To read rows in this table, use the \`select\` method.`,code: ({@@ -706,7 +716,7 @@ let { data: ${resourceId}, error } = await supabase},filtering: {key: 'filter-rows',- category: 'entities',+ category: API_DOCS_CATEGORIES.ENTITIES,title: 'Filtering',description: `Supabase provides a wide range of filters`,docsUrl: `${DOCS_URL}/reference/javascript/using-filters`,@@ -781,7 +791,7 @@ let { data: ${resourceId}, error } = await supabase},insertRows: {key: 'insert-rows',- category: 'entities',+ category: API_DOCS_CATEGORIES.ENTITIES,title: 'Insert rows',description: `\`insert\` lets you insert into your tables. You can also insert in bulk and do UPSERT.@@ -862,7 +872,7 @@ const { data, error } = await supabase},updateRows: {key: 'update-rows',- category: 'entities',+ category: API_DOCS_CATEGORIES.ENTITIES,title: 'Update rows',description: `\`update\` lets you update rows. \`update\` will match all rows by default. You can update specific rows using horizontal filters, e.g. \`eq\`, \`lt\`, and \`is\`.@@ -904,7 +914,7 @@ const { data, error } = await supabase},deleteRows: {key: 'delete-rows',- category: 'entities',+ category: API_DOCS_CATEGORIES.ENTITIES,title: 'Delete rows',description: `\`delete\` lets you delete rows. \`delete\` will match all rows by default, so remember to specify your filters!@@ -940,7 +950,7 @@ const { error } = await supabase},subscribeChanges: {key: 'subscribe-changes',- category: 'entities',+ category: API_DOCS_CATEGORIES.ENTITIES,title: 'Subscribe to changes',description: `Supabase provides realtime functionality and broadcasts database changes to authorized users depending on Row Level Security (RLS) policies.@@ -1028,7 +1038,7 @@ const channels = supabase.channel('custom-filter-channel')},uploadFile: {key: 'upload-file',- category: 'storage',+ category: API_DOCS_CATEGORIES.STORAGE,title: 'Upload a file',docsUrl: `${DOCS_URL}/reference/javascript/storage-from-upload`,description: `@@ -1064,7 +1074,7 @@ const { data, error } = await supabase},deleteFiles: {key: 'delete-files',- category: 'storage',+ category: API_DOCS_CATEGORIES.STORAGE,title: 'Delete files',docsUrl: `${DOCS_URL}/reference/javascript/storage-from-remove`,description: `@@ -1093,7 +1103,7 @@ const { data, error } = await supabase},listFiles: {key: 'list-files',- category: 'storage',+ category: API_DOCS_CATEGORIES.STORAGE,title: 'List all files',docsUrl: `${DOCS_URL}/reference/javascript/storage-from-list`,description: `@@ -1125,7 +1135,7 @@ const { data, error } = await supabase},downloadFile: {key: 'download-file',- category: 'storage',+ category: API_DOCS_CATEGORIES.STORAGE,title: 'Download a file',docsUrl: `${DOCS_URL}/reference/javascript/storage-from-download`,description: `@@ -1154,7 +1164,7 @@ const { data, error } = await supabase},createSignedURL: {key: 'create-signed-url',- category: 'storage',+ category: API_DOCS_CATEGORIES.STORAGE,title: 'Create a signed URL',docsUrl: `${DOCS_URL}/reference/javascript/storage-from-createsignedurl`,description: `@@ -1183,7 +1193,7 @@ const { data, error } = await supabase},retrievePublicURL: {key: 'retrieve-public-url',- category: 'storage',+ category: API_DOCS_CATEGORIES.STORAGE,title: 'Retrieve public URL',docsUrl: `${DOCS_URL}/reference/javascript/storage-from-getpublicurl`,description: `@@ -1216,7 +1226,7 @@ const { data } = supabase},invokeEdgeFunction: {key: 'invoke-edge-function',- category: 'edge-functions',+ category: API_DOCS_CATEGORIES.EDGE_FUNCTIONS,title: 'Invoke an edge function',docsUrl: `${DOCS_URL}/reference/javascript/functions-invoke`,description: `@@ -1245,4 +1255,4 @@ const { data, error } = await supabase},],},-}+} as constdiff --git a/apps/studio/components/interfaces/ProjectAPIDocs/ProjectAPIDocs.tsx b/apps/studio/components/interfaces/ProjectAPIDocs/ProjectAPIDocs.tsxindex f2b73315aeb..e206290a2f1 100644--- a/apps/studio/components/interfaces/ProjectAPIDocs/ProjectAPIDocs.tsx+++ b/apps/studio/components/interfaces/ProjectAPIDocs/ProjectAPIDocs.tsx@@ -18,9 +18,9 @@ import { RPC } from './Content/RPC'import { Storage } from './Content/Storage'import { StoredProcedures } from './Content/StoredProcedures'import { UserManagement } from './Content/UserManagement'-import FirstLevelNav from './FirstLevelNav'+import { FirstLevelNav } from './FirstLevelNav'import LanguageSelector from './LanguageSelector'-import SecondLevelNav from './SecondLevelNav'+import { SecondLevelNav } from './SecondLevelNav'/*** [Joshen] Reminder: when we choose to release this as a main featurediff --git a/apps/studio/components/interfaces/ProjectAPIDocs/SecondLevelNav.Layout.tsx b/apps/studio/components/interfaces/ProjectAPIDocs/SecondLevelNav.Layout.tsxnew file mode 100644index 00000000000..e8c4978a4e6--- /dev/null+++ b/apps/studio/components/interfaces/ProjectAPIDocs/SecondLevelNav.Layout.tsx@@ -0,0 +1,193 @@+import { ChevronLeft, Code } from 'lucide-react'+import { useMemo, useState, type PropsWithChildren, type ReactNode } from 'react'++import { DocsButton } from 'components/ui/DocsButton'+import { useAppStateSnapshot } from 'state/app-state'+import {+ Alert_Shadcn_,+ AlertDescription_Shadcn_,+ AlertTitle_Shadcn_,+ Button,+ cn,+ Popover_Shadcn_,+ PopoverContent_Shadcn_,+ PopoverTrigger_Shadcn_,+} from 'ui'+import { useIsAPIDocsSidePanelEnabled } from '../App/FeaturePreview/FeaturePreviewContext'+import { navigateToSection } from './Content/Content.utils'+import { DOCS_RESOURCE_CONTENT } from './ProjectAPIDocs.constants'++type DocsResourceContentItem = (typeof DOCS_RESOURCE_CONTENT)[keyof typeof DOCS_RESOURCE_CONTENT]++export type MenuItemFilter = (item: DocsResourceContentItem) => boolean+export type ResourcePickerRenderProps = {+ selectedResource?: string+ onSelect: (value: string) => void+ closePopover: () => void+}++type SecondLevelNavLayoutProps = {+ category: string+ title: string+ docsUrl: string+ menuItemFilter?: MenuItemFilter+ renderResourceList: (props: ResourcePickerRenderProps) => ReactNode+}++export const SecondLevelNavLayout = ({+ category,+ title,+ docsUrl,+ menuItemFilter,+ renderResourceList,+}: SecondLevelNavLayoutProps) => {+ const snap = useAppStateSnapshot()+ const [, resource] = snap.activeDocsSection++ return (+ <SecondLevelNavOuterContainer>+ <SecondLevelNavInnerContainer>+ <NavTitle title={title} category={category} />+ <ResourcePicker+ category={category}+ resource={resource}+ renderResourceList={renderResourceList}+ />+ <MenuItems category={category} menuItemFilter={menuItemFilter} />+ </SecondLevelNavInnerContainer>++ <SecondLevelNavInnerContainer className="py-4 border-t">+ <MoreInformation docsUrl={docsUrl} />+ </SecondLevelNavInnerContainer>+ </SecondLevelNavOuterContainer>+ )+}++const SecondLevelNavOuterContainer = ({ children }: PropsWithChildren) => {+ return <div className="py-2">{children}</div>+}++type SecondLevelLevelNavInnerContainerProps = PropsWithChildren<{+ className?: string+}>++const SecondLevelNavInnerContainer = ({+ children,+ className,+}: SecondLevelLevelNavInnerContainerProps) => {+ return <div className={cn('px-4', className)}>{children}</div>+}++type ResourcePickerProps = {+ category: string+ resource?: string+ renderResourceList: (props: ResourcePickerRenderProps) => ReactNode+}++type NavTitleProps = {+ title: string+ category: string+}++const NavTitle = ({ title, category }: NavTitleProps) => {+ const isNewAPIDocsEnabled = useIsAPIDocsSidePanelEnabled()++ const snap = useAppStateSnapshot()+ const handleBack = () => {+ snap.setActiveDocsSection([category])+ }++ return (+ <div className="flex items-center space-x-2 mb-2">+ {isNewAPIDocsEnabled && (+ <Button type="text" icon={<ChevronLeft />} className="px-1" onClick={handleBack} />+ )}+ <p className="text-sm text-foreground-light capitalize">{title}</p>+ </div>+ )+}++const ResourcePicker = ({ category, resource, renderResourceList }: ResourcePickerProps) => {+ const snap = useAppStateSnapshot()++ const [open, setOpen] = useState(false)++ const handleSelect = (value: string) => {+ snap.setActiveDocsSection([category, value])+ setOpen(false)+ }++ return (+ <Popover_Shadcn_ open={open} onOpenChange={setOpen} modal={false}>+ <PopoverTrigger_Shadcn_ asChild>+ <Button+ type="default"+ size="small"+ className="w-full justify-between gap-2"+ iconRight={<Code className="rotate-90" />}+ >+ <span className="truncate">{resource ?? 'Select a resource'}</span>+ </Button>+ </PopoverTrigger_Shadcn_>+ <PopoverContent_Shadcn_ className="p-0 w-64" side="bottom" align="center">+ {renderResourceList({+ selectedResource: resource,+ onSelect: handleSelect,+ closePopover: () => setOpen(false),+ })}+ </PopoverContent_Shadcn_>+ </Popover_Shadcn_>+ )+}++type MenuItemsProps = {+ category: string+ menuItemFilter?: MenuItemFilter+}++const MenuItems = ({ category, menuItemFilter }: MenuItemsProps) => {+ const menuItems = useMemo(() => {+ const items = Object.values(DOCS_RESOURCE_CONTENT).filter(+ (content) => content.category === category+ )+ return menuItemFilter ? items.filter(menuItemFilter) : items+ }, [category, menuItemFilter])++ return (+ <div className="py-4 space-y-2">+ {menuItems.map((item) => (+ <button+ key={item.key}+ className="w-full text-left text-sm text-foreground-light px-4 hover:text-foreground"+ onClick={() => navigateToSection(item.key)}+ >+ {item.title}+ </button>+ ))}+ </div>+ )+}++type MoreInformationProps = {+ docsUrl: string+}++const MoreInformation = ({ docsUrl }: MoreInformationProps) => {+ return (+ <Alert_Shadcn_ className="p-3">+ <AlertTitle_Shadcn_>+ <p className="text-xs">Unable to find what you're looking for?</p>+ </AlertTitle_Shadcn_>+ <AlertDescription_Shadcn_ className="space-y-1">+ <p className="text-xs !leading-normal">+ The API methods shown here are only the commonly used ones to get you started building+ quickly.+ </p>+ <p className="text-xs !leading-normal">+ Head over to our docs site for the full API documentation.+ </p>+ <DocsButton className="!mt-2" href={docsUrl} />+ </AlertDescription_Shadcn_>+ </Alert_Shadcn_>+ )+}diff --git a/apps/studio/components/interfaces/ProjectAPIDocs/SecondLevelNav.ResourcePicker.tsx b/apps/studio/components/interfaces/ProjectAPIDocs/SecondLevelNav.ResourcePicker.tsxnew file mode 100644index 00000000000..633069568e5--- /dev/null+++ b/apps/studio/components/interfaces/ProjectAPIDocs/SecondLevelNav.ResourcePicker.tsx@@ -0,0 +1,57 @@+import {+ cn,+ Command_Shadcn_,+ CommandGroup_Shadcn_,+ CommandItem_Shadcn_,+ CommandList_Shadcn_,+} from 'ui'+import type { ResourcePickerRenderProps } from './SecondLevelNav.Layout'++type NamedResource = { name: string }++type ResourcePickerListProps = ResourcePickerRenderProps & {+ items: NamedResource[]+ emptyMessage: string+}++export const ResourcePickerList = ({+ items,+ emptyMessage,+ selectedResource,+ onSelect,+ closePopover,+}: ResourcePickerListProps) => {+ const handleSelect = (value: string) => {+ onSelect(value)+ closePopover()+ }++ return (+ <Command_Shadcn_>+ <CommandList_Shadcn_>+ <CommandGroup_Shadcn_>+ {items.length === 0 && (+ <CommandItem_Shadcn_ disabled className="cursor-default px-4">+ <p className="text-foreground-light">{emptyMessage}</p>+ </CommandItem_Shadcn_>+ )}+ {items.map((item) => {+ const isActive = item.name === selectedResource+ return (+ <CommandItem_Shadcn_+ key={item.name}+ className={cn(+ 'cursor-pointer px-4',+ isActive ? 'text-foreground bg-selection' : 'text-foreground-light'+ )}+ onSelect={() => handleSelect(item.name)}+ >+ <p className="truncate">{item.name}</p>+ </CommandItem_Shadcn_>+ )+ })}+ </CommandGroup_Shadcn_>+ </CommandList_Shadcn_>+ </Command_Shadcn_>+ )+}diff --git a/apps/studio/components/interfaces/ProjectAPIDocs/SecondLevelNav.StoragePicker.tsx b/apps/studio/components/interfaces/ProjectAPIDocs/SecondLevelNav.StoragePicker.tsxnew file mode 100644index 00000000000..bc3c1fb6da1--- /dev/null+++ b/apps/studio/components/interfaces/ProjectAPIDocs/SecondLevelNav.StoragePicker.tsx@@ -0,0 +1,149 @@+import { useDebounce, useIntersectionObserver } from '@uidotdev/usehooks'+import { useEffect, useMemo, useRef, useState } from 'react'++import { usePaginatedBucketsQuery } from 'data/storage/buckets-query'+import {+ cn,+ Command_Shadcn_,+ CommandEmpty_Shadcn_,+ CommandGroup_Shadcn_,+ CommandInput_Shadcn_,+ CommandItem_Shadcn_,+ CommandList_Shadcn_,+} from 'ui'+import type { ResourcePickerRenderProps } from './SecondLevelNav.Layout'++type StorageResourceListProps = ResourcePickerRenderProps & {+ projectRef?: string+}++const SEARCH_DEBOUNCE_MS = 400++const useSearchQuery = () => {+ const [search, setSearch] = useState('')+ const debouncedSearch = useDebounce(search, SEARCH_DEBOUNCE_MS)+ const searchQuery = search.length === 0 ? undefined : debouncedSearch++ return {+ rawQuery: search,+ query: searchQuery,+ setSearch,+ }+}++type UseInfiniteLoadingBucketsParams = {+ projectRef?: string+ searchQuery?: string+ rawQuery: string+}++const useInfiniteLoadingBuckets = ({+ projectRef,+ searchQuery,+ rawQuery,+}: UseInfiniteLoadingBucketsParams) => {+ const { data, isFetching, hasNextPage, fetchNextPage, isFetchingNextPage } =+ usePaginatedBucketsQuery(+ { projectRef, search: searchQuery },+ {+ enabled: !!projectRef,+ keepPreviousData: rawQuery.length === 0,+ }+ )+ const buckets = useMemo(() => data?.pages.flatMap((page) => page) ?? [], [data])++ const scrollContainerRef = useRef<HTMLDivElement | null>(null)+ const [sentinelRef, entry] = useIntersectionObserver({+ threshold: 1,+ root: scrollContainerRef.current,+ rootMargin: '0px',+ })++ useEffect(() => {+ if (entry?.isIntersecting && hasNextPage && !isFetching) {+ fetchNextPage()+ }+ }, [entry?.isIntersecting, fetchNextPage, hasNextPage, isFetching])++ return {+ isFetching,+ hasNextPage,+ isFetchingNextPage,+ buckets,+ scrollContainerRef,+ sentinelRef,+ }+}++export const StorageResourceList = ({+ projectRef,+ selectedResource,+ onSelect,+ closePopover,+}: StorageResourceListProps) => {+ const { rawQuery, query: searchQuery, setSearch } = useSearchQuery()++ const { isFetching, hasNextPage, isFetchingNextPage, buckets, scrollContainerRef, sentinelRef } =+ useInfiniteLoadingBuckets({+ projectRef,+ searchQuery,+ rawQuery,+ })++ const handleSelect = (value: string) => {+ onSelect(value)+ closePopover()+ }++ const showEmptyState = !isFetching && buckets.length === 0+ const emptyMessage =+ rawQuery.length > 0 ? 'No buckets found for this search' : 'No buckets available'++ return (+ <Command_Shadcn_ shouldFilter={false}>+ <CommandInput_Shadcn_+ showResetIcon+ value={rawQuery}+ onValueChange={setSearch}+ placeholder="Search buckets..."+ handleReset={() => setSearch('')}+ />+ <CommandList_Shadcn_>+ <CommandEmpty_Shadcn_+ hidden={!showEmptyState}+ className="py-3 text-sm text-foreground-light"+ >+ {emptyMessage}+ </CommandEmpty_Shadcn_>+ <CommandGroup_Shadcn_>+ {isFetching && buckets.length === 0 ? (+ <div className="px-4 py-3 text-sm text-foreground-light">Loading buckets...</div>+ ) : (+ <div ref={scrollContainerRef} className="max-h-72 min-h-[150px] overflow-y-auto">+ {buckets.map((bucket) => {+ const isActive = bucket.name === selectedResource+ return (+ <CommandItem_Shadcn_+ key={bucket.id}+ value={bucket.name}+ className={cn(+ 'cursor-pointer px-4',+ isActive ? 'text-foreground bg-selection' : 'text-foreground-light'+ )}+ onSelect={() => handleSelect(bucket.name)}+ >+ <p className="truncate">{bucket.name}</p>+ </CommandItem_Shadcn_>+ )+ })}+ {hasNextPage && <div ref={sentinelRef} className="h-2 w-full" />}+ </div>+ )}+ </CommandGroup_Shadcn_>+ {isFetchingNextPage && (+ <div className="px-4 py-2 text-sm text-foreground-light">Loading more buckets...</div>+ )}+ </CommandList_Shadcn_>+ </Command_Shadcn_>+ )+}diff --git a/apps/studio/components/interfaces/ProjectAPIDocs/SecondLevelNav.tsx b/apps/studio/components/interfaces/ProjectAPIDocs/SecondLevelNav.tsxindex c4a321db4eb..d16dbb30fba 100644--- a/apps/studio/components/interfaces/ProjectAPIDocs/SecondLevelNav.tsx+++ b/apps/studio/components/interfaces/ProjectAPIDocs/SecondLevelNav.tsx@@ -1,167 +1,119 @@import { useParams } from 'common'-import { useState } from 'react'+import { type ReactNode } from 'react'-import { DocsButton } from 'components/ui/DocsButton'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 { useBucketInfoQueryPreferCached } from 'data/storage/buckets-query'import { DOCS_URL } from 'lib/constants'-import { ChevronLeft, Code } from 'lucide-react'import { useAppStateSnapshot } from 'state/app-state'-import {- AlertDescription_Shadcn_,- AlertTitle_Shadcn_,- Alert_Shadcn_,- Button,- CommandGroup_Shadcn_,- CommandItem_Shadcn_,- CommandList_Shadcn_,- Command_Shadcn_,- PopoverContent_Shadcn_,- PopoverTrigger_Shadcn_,- Popover_Shadcn_,-} from 'ui'-import { useIsAPIDocsSidePanelEnabled } from '../App/FeaturePreview/FeaturePreviewContext'-import { navigateToSection } from './Content/Content.utils'-import { DOCS_RESOURCE_CONTENT } from './ProjectAPIDocs.constants'--const SecondLevelNav = () => {+import { API_DOCS_CATEGORIES } from './ProjectAPIDocs.constants'+import { SecondLevelNavLayout, type MenuItemFilter } from './SecondLevelNav.Layout'+import { ResourcePickerList } from './SecondLevelNav.ResourcePicker'+import { StorageResourceList } from './SecondLevelNav.StoragePicker'++const OPEN_API_SPEC_STALE_TIME = 1000 * 60 * 10++const EntitiesSecondLevelNav = () => {const { ref } = useParams()- const snap = useAppStateSnapshot()- const [open, setOpen] = useState(false)- const isNewAPIDocsEnabled = useIsAPIDocsSidePanelEnabled()- const { data } = useOpenAPISpecQuery({ projectRef: ref })+ const { data } = useOpenAPISpecQuery({ projectRef: ref }, { staleTime: OPEN_API_SPEC_STALE_TIME })const tables = data?.tables ?? []++ return (+ <SecondLevelNavLayout+ category={API_DOCS_CATEGORIES.ENTITIES}+ title="Tables & Views"+ docsUrl={`${DOCS_URL}/reference/javascript/select`}+ renderResourceList={(props) => (+ <ResourcePickerList {...props} items={tables} emptyMessage="No tables available" />+ )}+ />+ )+}++const StoredProceduresSecondLevelNav = () => {+ const { ref } = useParams()++ const { data } = useOpenAPISpecQuery({ projectRef: ref }, { staleTime: OPEN_API_SPEC_STALE_TIME })const functions = data?.functions ?? []- const [section, resource] = snap.activeDocsSection- const { data: buckets } = useBucketsQuery({ projectRef: ref })+ return (+ <SecondLevelNavLayout+ category={API_DOCS_CATEGORIES.STORED_PROCEDURES}+ title="Stored Procedures"+ docsUrl={`${DOCS_URL}/reference/javascript/rpc`}+ renderResourceList={(props) => (+ <ResourcePickerList+ {...props}+ items={functions}+ emptyMessage="No stored procedures available"+ />+ )}+ />+ )+}++const EdgeFunctionsSecondLevelNav = () => {+ const { ref } = useParams()+const { data: edgeFunctions } = useEdgeFunctionsQuery({ projectRef: ref })- const bucket = (buckets ?? []).find((b) => b.name === resource)-- const content: { [key: string]: { title: string; options: any[]; docsUrl: string } } = {- entities: {- title: 'Tables & Views',- options: tables,- docsUrl: `${DOCS_URL}/reference/javascript/select`,- },- 'stored-procedures': {- title: 'Stored Procedures',- options: functions,- docsUrl: `${DOCS_URL}/reference/javascript/rpc`,- },- storage: {- title: 'Storage',- options: buckets ?? [],- docsUrl: `${DOCS_URL}/reference/javascript/storage-createbucket`,- },- 'edge-functions': {- title: 'Edge Functions',- options: edgeFunctions ?? [],- docsUrl: `${DOCS_URL}/reference/javascript/functions-invoke`,- },- }-- const updateSection = (value: string) => {- snap.setActiveDocsSection([snap.activeDocsSection[0], value])- setOpen(false)- }-- const menuItems = Object.values(DOCS_RESOURCE_CONTENT).filter(- (content) => content.category === snap.activeDocsSection[0]++ return (+ <SecondLevelNavLayout+ category={API_DOCS_CATEGORIES.EDGE_FUNCTIONS}+ title="Edge Functions"+ docsUrl={`${DOCS_URL}/reference/javascript/functions-invoke`}+ renderResourceList={(props) => (+ <ResourcePickerList+ {...props}+ items={edgeFunctions ?? []}+ emptyMessage="No edge functions available"+ />+ )}+ />)+}++const StorageSecondLevelNav = () => {+ const { ref } = useParams()++ const snap = useAppStateSnapshot()+ const [, resource] = snap.activeDocsSection++ const selectedBucket = useBucketInfoQueryPreferCached(resource, ref)++ const menuItemFilter: MenuItemFilter | undefined = selectedBucket+ ? (item) => {+ if (!selectedBucket.public && item.key === 'retrieve-public-url') return false+ if (selectedBucket.public && item.key === 'create-signed-url') return false+ return true+ }+ : undefinedreturn (- <div className="py-4">- <div className="px-4 flex items-center space-x-2 mb-2">- {isNewAPIDocsEnabled && (- <Button- type="text"- icon={<ChevronLeft />}- className="px-1"- onClick={() => snap.setActiveDocsSection([snap.activeDocsSection[0]])}- />- )}- <p className="text-sm text-foreground-light capitalize">{content[section].title}</p>- </div>-- <Popover_Shadcn_ open={open} onOpenChange={setOpen} modal={false}>- <PopoverTrigger_Shadcn_ asChild>- <div className="px-4">- <Button block type="default" size="small" className="[&>span]:w-full">- <div>- <div className="flex items-center justify-between w-full">- <p>{snap.activeDocsSection[1]}</p>- <div>- <Code className="rotate-90" strokeWidth={1.5} size={12} />- </div>- </div>- </div>- </Button>- </div>- </PopoverTrigger_Shadcn_>- <PopoverContent_Shadcn_ className="p-0 w-60" side="bottom" align="center">- <Command_Shadcn_>- <CommandList_Shadcn_>- <CommandGroup_Shadcn_>- {content[section].options.map((option) => (- <CommandItem_Shadcn_- key={option.name}- className="cursor-pointer"- onSelect={() => updateSection(option.name)}- onClick={() => updateSection(option.name)}- >- <p>{option.name}</p>- </CommandItem_Shadcn_>- ))}- </CommandGroup_Shadcn_>- </CommandList_Shadcn_>- </Command_Shadcn_>- </PopoverContent_Shadcn_>- </Popover_Shadcn_>-- <div className="px-2 py-4 space-y-2">- {menuItems.map((item) => {- if (section === 'storage' && bucket !== undefined) {- if (- (!bucket.public && item.key === 'retrieve-public-url') ||- (bucket.public && item.key === 'create-signed-url')- )- return null- }- return (- <p- key={item.key}- title={item.title}- className="text-sm text-foreground-light px-4 hover:text-foreground transition cursor-pointer"- onClick={() => navigateToSection(item.key)}- >- {item.title}- </p>- )- })}- </div>-- <div className="px-4 py-4 border-t space-y-2">- <Alert_Shadcn_ className="p-3">- <AlertTitle_Shadcn_>- <p className="text-xs">Unable to find what you're looking for?</p>- </AlertTitle_Shadcn_>- <AlertDescription_Shadcn_ className="space-y-1">- <p className="text-xs !leading-normal">- The API methods shown here are only the commonly used ones to get you started building- quickly.- </p>- <p className="text-xs !leading-normal">- Head over to our docs site for the full API documentation.- </p>- <DocsButton className="!mt-2" href={content[section].docsUrl} />- </AlertDescription_Shadcn_>- </Alert_Shadcn_>- </div>- </div>+ <SecondLevelNavLayout+ category={API_DOCS_CATEGORIES.STORAGE}+ title="Storage"+ docsUrl={`${DOCS_URL}/reference/javascript/storage-createbucket`}+ menuItemFilter={menuItemFilter}+ renderResourceList={(props) => <StorageResourceList {...props} projectRef={ref} />}+ />)}-export default SecondLevelNav+const SECTION_COMPONENTS: Record<string, () => ReactNode> = {+ [API_DOCS_CATEGORIES.ENTITIES]: EntitiesSecondLevelNav,+ [API_DOCS_CATEGORIES.STORED_PROCEDURES]: StoredProceduresSecondLevelNav,+ [API_DOCS_CATEGORIES.STORAGE]: StorageSecondLevelNav,+ [API_DOCS_CATEGORIES.EDGE_FUNCTIONS]: EdgeFunctionsSecondLevelNav,+}++export const SecondLevelNav = () => {+ const snap = useAppStateSnapshot()+ const [section] = snap.activeDocsSection++ const SectionComponent = SECTION_COMPONENTS[section]+ if (!SectionComponent) return null++ return <SectionComponent key={section} />+}diff --git a/apps/studio/components/ui/InfiniteList.tsx b/apps/studio/components/ui/InfiniteList.tsxindex eae0fb05c59..c767c247329 100644--- a/apps/studio/components/ui/InfiniteList.tsx+++ b/apps/studio/components/ui/InfiniteList.tsx@@ -20,6 +20,9 @@ import {import { Skeleton, cn } from 'ui'// Regular memo erases generics, so this helper adds them back+// any here is intentional to allow for generic components and does not affect+// type safety of the wrapped component+// eslint-disable-next-line @typescript-eslint/no-explicit-anyconst typedMemo = <Component extends (props: any) => JSX.Element | null>(component: Component,propsAreEqual?: (@@ -175,7 +178,7 @@ export const InfiniteListSizer = ({)}-type RowComponentBaseProps<Item> = {+export type RowComponentBaseProps<Item> = {index: numberitem: Itemstyle?: CSSPropertiesdiff --git a/apps/studio/data/storage/buckets-query.ts b/apps/studio/data/storage/buckets-query.tsindex 2aa128ac434..b082ed2a09c 100644--- a/apps/studio/data/storage/buckets-query.ts+++ b/apps/studio/data/storage/buckets-query.ts@@ -1,4 +1,10 @@-import { useInfiniteQuery, useQuery } from '@tanstack/react-query'+import {+ useInfiniteQuery,+ useQuery,+ useQueryClient,+ type UseInfiniteQueryResult,+} from '@tanstack/react-query'+import { useMemo } from 'react'import { components } from 'api-types'import { get, handleError } from 'data/fetchers'@@ -18,6 +24,26 @@ export type Bucket = components['schemas']['StorageBucketResponse']export type BucketType = Bucket['type']+type GetBucketParams = {+ projectRef?: string+ bucketId?: string+}++async function getBucket({ projectRef, bucketId }: GetBucketParams, signal?: AbortSignal) {+ if (!projectRef) throw new Error('projectRef is required')+ if (!bucketId) throw new Error('bucketId is required')++ const { data, error } = await get('/platform/storage/{ref}/buckets/{id}', {+ params: {+ path: { ref: projectRef, id: bucketId },+ },+ signal,+ })++ if (error) handleError(error)+ return data+}+export async function getBuckets({ projectRef }: BucketsVariables, signal?: AbortSignal) {if (!projectRef) throw new Error('projectRef is required')@@ -84,10 +110,27 @@ const getBucketsPaginated = async (return data}+type BucketData = Awaited<ReturnType<typeof getBucket>>export type BucketsData = Awaited<ReturnType<typeof getBuckets>>export type BucketsWithPaginationData = Awaited<ReturnType<typeof getBucketsPaginated>>export type BucketsError = ResponseError+const useBucketQuery = <TData = BucketData>(+ { projectRef, bucketId }: GetBucketParams,+ { enabled = true, ...options }: UseCustomQueryOptions<BucketData, BucketsError, TData>+) => {+ const { data: project } = useSelectedProjectQuery()+ const isActive = project?.status === PROJECT_STATUS.ACTIVE_HEALTHY++ return useQuery<BucketData, BucketsError, TData>({+ queryKey: storageKeys.bucket(projectRef, bucketId),+ queryFn: ({ signal }) => getBucket({ projectRef, bucketId }, signal),+ enabled: enabled && !!bucketId && isActive,+ ...options,+ retry: shouldRetryBucketsQuery,+ })+}+export const useBucketsQuery = <TData = BucketsData>({ projectRef }: BucketsVariables,{ enabled = true, ...options }: UseCustomQueryOptions<BucketsData, BucketsError, TData> = {}@@ -136,6 +179,38 @@ export const usePaginatedBucketsQuery = <TData = BucketsWithPaginationData>(})}+/**+ * Tries to get the bucket info from the cache first. If not found, fetches+ * from remote by name.+ */+export const useBucketInfoQueryPreferCached = (bucketId?: string, projectRef?: string) => {+ const queryClient = useQueryClient()++ const cachedBucketInfo = useMemo(() => {+ if (!bucketId) return undefined++ const bucketsPages = queryClient.getQueryData(storageKeys.bucketsList(projectRef)) as+ | UseInfiniteQueryResult<Bucket[]>['data']+ | undefined+ const buckets = bucketsPages?.pages.flatMap((page) => page) ?? []+ return buckets.find((b) => b.name === bucketId)+ }, [bucketId, projectRef, queryClient])++ const shouldFetchBucketInfo = !!bucketId && !cachedBucketInfo+ const { data: remoteBucketInfo } = useBucketQuery(+ {+ projectRef,+ bucketId,+ },+ {+ enabled: shouldFetchBucketInfo,+ }+ )++ if (!bucketId) return undefined+ return cachedBucketInfo ?? remoteBucketInfo+}+const shouldRetryBucketsQuery = (failureCount: number, error: unknown) => {if (error instanceof ResponseError) {if (diff --git a/apps/studio/data/storage/keys.ts b/apps/studio/data/storage/keys.tsindex e80babe426a..02c7fdf95db 100644--- a/apps/studio/data/storage/keys.ts+++ b/apps/studio/data/storage/keys.ts@@ -1,4 +1,6 @@export const storageKeys = {+ bucket: (projectRef: string | undefined, bucketId: string | undefined) =>+ ['projects', projectRef, 'buckets', bucketId] as const,buckets: (projectRef: string | undefined) => ['projects', projectRef, 'buckets'] as const,bucketsList: (projectRef: string | undefined,diff --git a/packages/ui-patterns/src/ShimmeringLoader/index.tsx b/packages/ui-patterns/src/ShimmeringLoader/index.tsxindex 50fe487884c..025351459c5 100644--- a/packages/ui-patterns/src/ShimmeringLoader/index.tsx+++ b/packages/ui-patterns/src/ShimmeringLoader/index.tsx@@ -1,13 +1,16 @@+import type { CSSProperties } from 'react'import { Card, cn, Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from 'ui'export interface ShimmeringLoader {className?: string+ style?: CSSPropertiesdelayIndex?: numberanimationDelay?: number}export const ShimmeringLoader = ({className,+ style,delayIndex = 0,animationDelay = 150,}: ShimmeringLoader) => {@@ -15,6 +18,7 @@ export const ShimmeringLoader = ({<divclassName={cn('shimmering-loader rounded py-3', className)}style={{+ ...style,animationFillMode: 'backwards',animationDelay: `${delayIndex * animationDelay}ms`,}}