Files
supabase/apps/studio/components/interfaces/Functions/EdgeFunctionsListItem.tsx
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

182 lines
6.6 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { IS_PLATFORM, useFlag } from 'common'
import { useParams } from 'common/hooks'
import dayjs from 'dayjs'
import { CheckIcon, CopyIcon } from 'lucide-react'
import { useRouter } from 'next/router'
import { useMemo, useState, type MouseEvent } from 'react'
import { cn, copyToClipboard, TableCell, TableRow } from 'ui'
import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'
import { TimestampInfo } from 'ui-patterns/TimestampInfo'
import { formatErrorRate } from './EdgeFunctionsListItem.utils'
import { useProjectApiUrl } from '@/data/config/project-endpoint-query'
import { useEdgeFunctionsLastHourStatsQuery } from '@/data/edge-functions/edge-functions-last-hour-stats-query'
import {
useEdgeFunctionsQuery,
type EdgeFunctionsResponse,
} from '@/data/edge-functions/edge-functions-query'
import { normalizeFunctionIds } from '@/data/edge-functions/keys'
import { createNavigationHandler } from '@/lib/navigation'
interface EdgeFunctionsListItemProps {
function: EdgeFunctionsResponse
}
export const EdgeFunctionsListItem = ({ function: item }: EdgeFunctionsListItemProps) => {
const router = useRouter()
const { ref } = useParams()
const [isCopied, setIsCopied] = useState(false)
const showLastHourStats = useFlag('edgeFunctionsRequestMetrics')
const { data: endpoint, isPending: isEndpointPending } = useProjectApiUrl({ projectRef: ref })
const functionUrl = endpoint ? `${endpoint}/functions/v1/${item.slug}` : undefined
const isFunctionUrlLoading = !functionUrl && isEndpointPending
const handleNavigation = createNavigationHandler(
`/project/${ref}/functions/${item.slug}${IS_PLATFORM ? '' : `/code`}`,
router
)
const { data: functions } = useEdgeFunctionsQuery({ projectRef: ref })
const functionIds = useMemo(() => {
if (!showLastHourStats || !functions) return []
return normalizeFunctionIds(functions.map((item) => item.id))
}, [functions, showLastHourStats])
// [Joshen] We may be paginating the edge functions query in the future
// So this will eventually need to be a list of visibleFunctionIds instead + debounced
const {
data: lastHourStatsAll,
isPending: isStatsPending,
isError: isStatsError,
} = useEdgeFunctionsLastHourStatsQuery(
{ projectRef: ref, functionIds },
{ enabled: showLastHourStats }
)
const lastHourStats = lastHourStatsAll?.[item.id]
return (
<TableRow
key={item.id}
onClick={handleNavigation}
onAuxClick={handleNavigation}
onKeyDown={handleNavigation}
tabIndex={0}
className="cursor-pointer focus-inset"
>
<TableCell>
<p className="text-sm text-foreground whitespace-nowrap py-2">{item.name}</p>
</TableCell>
<TableCell>
<div className="text-xs text-foreground-light flex gap-2 items-center truncate">
{isFunctionUrlLoading && <ShimmeringLoader className="w-48 py-2" />}
{functionUrl && (
<>
<p title={functionUrl} className="font-mono truncate hidden md:inline max-w-120">
{functionUrl}
</p>
<button
type="button"
tabIndex={0}
aria-label="Copy function URL"
className="text-foreground-lighter hover:text-foreground transition"
onClick={(event: MouseEvent<HTMLButtonElement>) => {
function onCopy(value: string) {
setIsCopied(true)
copyToClipboard(value)
setTimeout(() => setIsCopied(false), 3000)
}
event.stopPropagation()
onCopy(functionUrl)
}}
>
{isCopied ? (
<div className="text-primary">
<CheckIcon size={14} strokeWidth={3} />
</div>
) : (
<div className="relative">
<div className="block">
<CopyIcon size={14} strokeWidth={1.5} />
</div>
</div>
)}
</button>
</>
)}
</div>
</TableCell>
<TableCell className="hidden 2xl:table-cell whitespace-nowrap">
{item.created_at ? (
<TimestampInfo
className="text-sm text-foreground-light whitespace-nowrap"
utcTimestamp={item.created_at}
label={dayjs(item.created_at).fromNow()}
/>
) : (
<span className="text-sm text-foreground-light">–</span>
)}
</TableCell>
<TableCell className="lg:table-cell">
{item.updated_at ? (
<TimestampInfo
className="text-sm text-foreground-light whitespace-nowrap"
utcTimestamp={item.updated_at}
label={dayjs(item.updated_at).fromNow()}
/>
) : (
<span className="text-sm text-foreground-light">–</span>
)}
</TableCell>
{showLastHourStats && (
<>
<TableCell className="lg:table-cell whitespace-nowrap">
{isStatsPending ? (
<ShimmeringLoader className="w-12" />
) : isStatsError ? (
<p className="text-foreground-lighter" title="Failed to load stats">
-
</p>
) : (
<p className="text-foreground-light">
{lastHourStats !== undefined ? lastHourStats.requestsCount.toLocaleString() : '-'}
</p>
)}
</TableCell>
<TableCell className="lg:table-cell whitespace-nowrap">
{isStatsPending ? (
<ShimmeringLoader className="w-12" />
) : isStatsError ? (
<p className="text-foreground-lighter" title="Failed to load stats">
-
</p>
) : lastHourStats !== undefined ? (
<span
className={cn(
'text-sm',
lastHourStats.errorRate >= 1
? 'text-destructive'
: lastHourStats.errorRate > 0.1
? 'text-warning'
: 'text-foreground-light'
)}
>
{formatErrorRate(lastHourStats.errorRate)}
</span>
) : (
<p className="text-foreground-lighter">-</p>
)}
</TableCell>
</>
)}
<TableCell className="hidden 2xl:table-cell">
<p className="text-foreground-light">{item.version}</p>
<button tabIndex={-1} className="sr-only">
Go to function details
</button>
</TableCell>
</TableRow>
)
}