Files
Alaister YoungandAlaister Young 3b57afc40c fix(studio): wait for project endpoint before showing function url (#53255)
`EdgeFunctionsListItem` built its URL as ``
`${endpoint}/functions/v1/${slug}` `` from `useProjectApiUrl`, whose
`data` is `undefined` while the project settings query is still pending.
On a cold load, each row showed `undefined/functions/v1/<slug>`, and the
copy button copied that string. `EdgeFunctionDetails` and
`TerminalInstructions` interpolated the endpoint the same way.

**Changed:**
-
`apps/studio/components/interfaces/Functions/EdgeFunctionsListItem.tsx`:
only builds the URL once `endpoint` is defined. While it's pending, the
row shows a `ShimmeringLoader` in place of the URL and no copy button.
The copy button now has an accessible name ("Copy function URL").
-
`apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx`:
the "Invoke function" snippets wait for both the endpoint and the
function. Until then they show a skeleton, so the cURL tab no longer
renders or copies `undefined/functions/v1/...`. If either query fails,
the card shows an `AlertError` instead.
-
`apps/studio/components/interfaces/Functions/TerminalInstructions.tsx`:
the "Invoke your function" curl command is only added once the endpoint
resolves, with a loader in its place until then.

Also checked: `EdgeFunctionOverviewHeader` already guards on `endpoint
&& slug`, so it's unchanged. `EdgeFunctionTesterSheet` doesn't use
`useProjectApiUrl`: it builds the URL from project settings at submit
time and never renders it, so it's also unchanged. `useProjectApiUrl`
itself is unchanged.

**Added:**
-
`apps/studio/components/interfaces/Functions/EdgeFunctionsListItem.test.tsx`:
renders a row while the settings request is in flight and asserts
there's no `undefined/functions/v1` text, a loader is shown and there's
no copy button. Once settings resolve, it asserts the full URL and that
the copy button copies it. It fails on the old component.
-
`apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.platform.test.tsx`:
a case where project settings fail to load, asserting the invoke card
shows the error and no cURL snippet.

## To test
- [ ] Open a project's Edge Functions page (`/project/<ref>/functions`)
with a hard reload and network throttling (for example "Slow 4G"). The
URL column never shows `undefined`: it shows a loader, then
`https://<ref>.supabase.co/functions/v1/<slug>`.
- [ ] Click a row's copy icon: the clipboard has the full function URL
and the page doesn't navigate.
- [ ] Click a row: it still navigates to that function's page.
- [ ] Hard reload a function's Details page
(`/project/<ref>/functions/<slug>/details`) with throttling. The cURL
snippet under "Invoke function" shows a skeleton, then the real URL.
- [ ] Open `/project/<ref>/functions?create=cli` with throttling. The
"Invoke your function" curl command shows a loader, then the real URL.

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-11-11 15:57:40 +09:00

169 lines
6.5 KiB
TypeScript

import { useQuery } from '@tanstack/react-query'
import { useParams } from 'common'
import { ExternalLinkIcon, Maximize2Icon, Minimize2Icon, TerminalIcon } from 'lucide-react'
import { useRouter } from 'next/router'
import { ComponentPropsWithoutRef, ElementRef, forwardRef, useState } from 'react'
import { Button, Collapsible, CollapsibleContent, CollapsibleTrigger } from 'ui'
import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'
import type { Commands } from './Functions.types'
import CommandRender from '@/components/interfaces/Functions/CommandRender'
import { ApiKeysAccessNote } from '@/components/ui/ApiKeysAccessNote'
import { DocsButton } from '@/components/ui/DocsButton'
import { useAccessTokensQuery } from '@/data/access-tokens/access-tokens-query'
import { apiKeysQueryOptions, getKeys } from '@/data/api-keys/api-keys-query'
import { useProjectApiUrl } from '@/data/config/project-endpoint-query'
import { DOCS_URL } from '@/lib/constants'
import { useGrant } from '@/lib/grants'
interface TerminalInstructionsProps extends ComponentPropsWithoutRef<typeof Collapsible> {
closable?: boolean
removeBorder?: boolean
}
export const TerminalInstructions = forwardRef<
ElementRef<typeof Collapsible>,
TerminalInstructionsProps
>(({ closable = false, removeBorder = false, ...props }, ref) => {
const router = useRouter()
const { ref: projectRef } = useParams()
const [showInstructions, setShowInstructions] = useState(!closable)
const { data: tokens } = useAccessTokensQuery()
const apiKeysGrant = useGrant('GET /v1/projects/{ref}/api-keys', { projectRef })
const { data: apiKeyData } = useQuery(
apiKeysQueryOptions(
{ projectRef, grant: apiKeysGrant.grant },
{
// A skipped query still returns cached data, so ignore it unless the grant is granted
select: (data) => getKeys(apiKeysGrant.status === 'granted' ? data : []),
}
)
)
const { anonKey, publishableKey } = apiKeyData ?? {}
const { data: endpoint, isPending: isEndpointPending } = useProjectApiUrl({ projectRef })
const functionsEndpoint = endpoint ? `${endpoint}/functions/v1` : undefined
const isFunctionsEndpointLoading = !functionsEndpoint && isEndpointPending
const apiKey = publishableKey?.api_key ?? anonKey?.api_key ?? '[YOUR ANON KEY]'
const commands: Commands[] = [
{
command: 'supabase functions new hello-world',
description: ' creates a function stub at ./functions/hello-world/index.ts',
jsx: () => {
return (
<>
<span className="text-brand-600">supabase</span> functions new hello-world
</>
)
},
comment: 'Create a function',
},
{
command: `supabase functions deploy hello-world --project-ref ${projectRef}`,
description: 'Deploys function at ./functions/hello-world/index.ts',
jsx: () => {
return (
<>
<span className="text-brand-600">supabase</span> functions deploy hello-world
--project-ref {projectRef}
</>
)
},
comment: 'Deploy your function',
},
]
if (functionsEndpoint) {
commands.push({
command: `curl -L -X POST '${functionsEndpoint}/hello-world' -H 'Authorization: Bearer ${apiKey}'${anonKey?.type === 'publishable' ? ` -H 'apikey: ${apiKey}'` : ''} --data '{"name":"Functions"}'`,
description: 'Invokes the hello-world function',
jsx: () => {
return (
<>
<span className="text-brand-600">curl</span> -L -X POST '{functionsEndpoint}
/hello-world' -H 'Authorization: Bearer [YOUR ANON KEY]'
{anonKey?.type === 'publishable' ? " -H 'apikey: [YOUR ANON KEY]' " : ''}
{`--data '{"name":"Functions"}'`}
</>
)
},
comment: 'Invoke your function',
})
}
return (
<Collapsible
ref={ref}
open={showInstructions}
className="w-full"
onOpenChange={() => setShowInstructions(!showInstructions)}
{...props}
>
<CollapsibleTrigger className="flex w-full justify-between" disabled={!closable}>
<div className="flex items-center gap-x-3">
<div className="flex items-center justify-center w-8 h-8 p-2 border rounded-sm bg-alternative">
<TerminalIcon strokeWidth={2} />
</div>
<h4>Create your first Edge Function via the CLI</h4>
</div>
{closable && (
<div className="cursor-pointer" onClick={() => setShowInstructions(!showInstructions)}>
{showInstructions ? (
<Minimize2Icon size={16} strokeWidth={1.5} />
) : (
<Maximize2Icon size={16} strokeWidth={1.5} />
)}
</div>
)}
</CollapsibleTrigger>
<CollapsibleContent className="w-full transition-all data-closed:animate-collapsible-up data-open:animate-collapsible-down">
<div className="my-4 space-y-4">
<CommandRender commands={commands} />
{isFunctionsEndpointLoading && <ShimmeringLoader className="w-3/4" />}
</div>
<ApiKeysAccessNote
grant={apiKeysGrant}
fallback="Replace the placeholder with your own key."
className="mb-4"
/>
{tokens && tokens.length === 0 ? (
<div className="py-4 space-y-3 border-t">
<div>
<p className="text-sm text-foreground">You may need to create an access token</p>
<p className="text-sm text-foreground-light">
You can create a secure access token in your account section
</p>
</div>
<Button onClick={() => router.push('/account/tokens')}>Access tokens</Button>
</div>
) : (
<div className="py-4 space-y-3 border-t">
<div>
<h3 className="text-base text-foreground">Need help?</h3>
<p className="text-sm text-foreground-light">
Read the documentation, or browse some sample code.
</p>
</div>
<div className="flex gap-2">
<DocsButton href={`${DOCS_URL}/guides/functions`} />
<Button asChild icon={<ExternalLinkIcon />}>
<a
target="_blank"
rel="noreferrer"
href="https://github.com/supabase/supabase/tree/master/examples/edge-functions/supabase/functions"
>
Examples
</a>
</Button>
</div>
</div>
)}
</CollapsibleContent>
</Collapsible>
)
})
TerminalInstructions.displayName = 'TerminalInstructions'