Files
supabase/apps/studio/components/interfaces/Functions/EdgeFunctionOverview/EdgeFunctionRecentErrors.tsx
Alaister YoungandAlaister Young d8568215ad [FE-5109] (part 4) refactor(studio): migrate database, editor, storage, and functions interfaces off next/router (#54056)
Part 4 of a 6-PR stack migrating all `next/router` and
`next/compat/router` imports in `apps/studio` onto TanStack Router hooks
and removing the router shims.

| Part | PR | Scope |
| --- | --- | --- |
| 1 | #54053 | Core navigation helpers, `hooks/**`, `lib/**`,
`data/prefetchers/**` |
| 2 | #54054 | `components/ui/**` |
| 3 | #54055 | `components/layouts/**` and `state/tabs.tsx` |
| **4** | **#54056 ← this PR** | **Database, Branching, Compute, Edge
Functions, Explorer, SQL Editor, Storage, Table Editor** |
| 5 | #54057 | Remaining `components/interfaces/**` and
`QueryInsightsTable` router events |
| 6 | #54058 | Remove `next/router` & `next/compat/router` shims,
`_router-events.ts`, Vite aliases, and test mocks |

Migrates the database, branching, compute, functions, explorer, SQL
editor, storage, and table editor interfaces off `next/router` and
`next/compat/router`.

**Changed:**

- Migrated the sole `next/compat/router` consumer
(`components/interfaces/Database/Replication/Destinations.tsx`) to
`useNavigate`
- Replaced `useRouter` across `BranchManagement`, `Branching`,
`Compute`, `Database` (`Backups`, `Functions`, `Replication`, `Schemas`,
`Tables`, `Triggers`), `EdgeFunctions`, `Explorer`, `Functions`,
`SQLEditor`, `Storage` (`AnalyticsBuckets`, `FilesBuckets`,
`VectorBuckets`, `StorageMenuV2`, `Storage.utils`), and
`TableGridEditor` with TanStack Router hooks (`useNavigate`,
`useLocation`, `useRoutePattern`) and `useParams` from `common`
- Updated unit and component tests across `Database/Replication`,
`Explorer`, `Functions`, and
`Storage/FilesBuckets/DeleteBucketModal.test.tsx` to use TanStack Router

**Simplified:**

- `useSnippetEditor` and `useRedirectLegacyReadReplicaDestination` read
search values from `useParams` instead of casting `location.search`
- `resolveSourceSwitch` returns `replace: boolean` instead of a
`push`/`replace` method name
- `ExplorerQueryTab` and `EdgeFunctionDetails` guard on a defined ref
instead of navigating with `ref ?? ''`
- `useFunctionsDetailShortcuts` and `StorageMenuV2` use a local `goTo`
helper for their navigation shortcuts
- Tests use the shared `createTestRouter` and `customRender` router, use
`toMatchObject` for search assertions, and drop duplicate assertions

Addresses
[FE-5109](https://linear.app/supabase/issue/FE-5109/replace-the-nextrouter-shims-with-tanstack-router-hooks)

## To test

- [ ] SQL Editor: creating, renaming, moving, opening
templates/examples, and keyboard shortcuts navigate between snippets
cleanly
- [ ] Table Editor & Database: opening tables, schema table nodes,
triggers, functions, backups/PITR, and replication destination flows
navigate as expected
- [ ] Storage: switching between Files, Analytics, and Vector buckets
and deleting a bucket navigates cleanly
- [ ] Edge Functions & Explorer: opening function details/logs, explorer
chat/query tabs, and branch management actions navigate properly

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-12-01 14:44:59 +08:00

196 lines
6.9 KiB
TypeScript

import { useNavigate } from '@tanstack/react-router'
import { CheckIcon, ExternalLinkIcon, EyeIcon } from 'lucide-react'
import { useMemo } from 'react'
import { Button, Card } from 'ui'
import {
PageSection,
PageSectionAside,
PageSectionContent,
PageSectionMeta,
PageSectionSummary,
PageSectionTitle,
} from 'ui-patterns/PageSection'
import {
EDGE_FUNCTION_LOGS_VIEW,
getEdgeFunctionLogsScope,
getEdgeFunctionLogsUrl,
getLegacyEdgeFunctionLogsUrl,
} from './EdgeFunctionOverview.utils'
import {
getSinceLastDeployInvocationPhrase,
getSinceLastDeployLogRange,
} from './EdgeFunctionRecentErrors.utils'
import { EdgeFunctionRecentErrorsActions } from './EdgeFunctionRecentErrorsActions'
import { useUnifiedLogsPreview } from '@/components/interfaces/App/FeaturePreview/FeaturePreviewContext'
import { EmbeddedLogsTable } from '@/components/interfaces/UnifiedLogs/components/EmbeddedLogsTable'
import type { ColumnSchema } from '@/components/interfaces/UnifiedLogs/UnifiedLogs.schema'
import {
createUnifiedLogsSearch,
getFacetValueCount,
getUniqueLogRows,
} from '@/components/interfaces/UnifiedLogs/UnifiedLogs.utils'
import { useUnifiedLogsCountQuery } from '@/data/logs/unified-logs-count-query'
import { useUnifiedLogsInfiniteQuery } from '@/data/logs/unified-logs-infinite-query'
import { navigateToUrl } from '@/lib/navigation'
const ERROR_LOG_FILTERS = ['level:eq:error']
const MAX_VISIBLE_ERRORS = 5
interface EdgeFunctionRecentErrorsProps {
functionId?: string
functionSlug?: string
projectRef?: string
updatedAt?: string | number
}
export const EdgeFunctionRecentErrors = ({
functionId,
functionSlug,
projectRef,
updatedAt,
}: EdgeFunctionRecentErrorsProps) => {
const navigate = useNavigate()
const { isEnabled: isUnifiedLogsEnabled } = useUnifiedLogsPreview()
const { isoTimestampStart, isoTimestampEnd } = useMemo(
() => getSinceLastDeployLogRange(updatedAt),
[updatedAt]
)
const { errorsSearch, countsSearch } = useMemo(() => {
const scope = functionId ? getEdgeFunctionLogsScope(functionId) : undefined
const date =
isoTimestampStart && isoTimestampEnd
? [new Date(isoTimestampStart), new Date(isoTimestampEnd)]
: null
return {
errorsSearch: createUnifiedLogsSearch({ filter: ERROR_LOG_FILTERS, date }, scope),
countsSearch: createUnifiedLogsSearch({ date }, scope),
}
}, [functionId, isoTimestampStart, isoTimestampEnd])
const isQueryEnabled = Boolean(projectRef && functionId && isoTimestampStart)
const { data, error, isError, isPending, isFetching } = useUnifiedLogsInfiniteQuery(
{ projectRef, search: errorsSearch, pageSize: MAX_VISIBLE_ERRORS },
{ enabled: isQueryEnabled, placeholderData: undefined }
)
const { data: counts } = useUnifiedLogsCountQuery(
{ projectRef, search: countsSearch },
{ enabled: isQueryEnabled }
)
const rows = useMemo(() => getUniqueLogRows<ColumnSchema>(data?.pages), [data?.pages])
const errorCount = counts ? getFacetValueCount(counts.facets, 'level', 'error') : rows.length
const hiddenErrorCount = Math.max(errorCount - rows.length, 0)
const invocationCount = counts
? getFacetValueCount(counts.facets, 'log_type', 'edge function')
: undefined
const getLogsUrl = (row?: ColumnSchema) => {
const target = {
projectRef: projectRef ?? '',
functionSlug: functionSlug ?? '',
start: isoTimestampStart,
end: isoTimestampEnd,
logId: row?.id,
}
if (isUnifiedLogsEnabled) {
return getEdgeFunctionLogsUrl({ ...target, filters: ERROR_LOG_FILTERS })
}
const tab = row?.log_type === 'edge function' ? 'invocations' : 'logs'
return getLegacyEdgeFunctionLogsUrl({ ...target, tab })
}
const handleOpenLogs = () => void navigateToUrl(navigate, getLogsUrl())
const handleOpenLog = (logId: string) => {
void navigateToUrl(navigate, getLogsUrl(rows.find((row) => row.id === logId)))
}
const isLoading = !functionId || (isQueryEnabled && isPending)
const hasNoErrors = !isLoading && !isError && rows.length === 0
return (
<PageSection>
<PageSectionMeta>
<PageSectionSummary>
<PageSectionTitle>Errors in the last 24h</PageSectionTitle>
</PageSectionSummary>
<PageSectionAside>
<EdgeFunctionRecentErrorsActions rows={rows} omittedCount={hiddenErrorCount} />
<Button size="tiny" icon={<ExternalLinkIcon size={14} />} onClick={handleOpenLogs}>
View logs
</Button>
</PageSectionAside>
</PageSectionMeta>
<PageSectionContent>
{hasNoErrors && (
<div className="rounded-md border border-dashed px-5 py-6 text-sm text-foreground-light">
<div className="flex items-start gap-3">
{invocationCount !== undefined && invocationCount > 0 && (
<CheckIcon
size={16}
strokeWidth={1.5}
className="mt-0.5 shrink-0 text-primary"
aria-hidden="true"
/>
)}
{invocationCount === 0 && (
<EyeIcon
size={16}
strokeWidth={1.5}
className="mt-0.5 shrink-0 text-foreground-muted"
aria-hidden="true"
/>
)}
<div>
{invocationCount !== undefined ? (
<>
There {invocationCount === 1 ? 'has' : 'have'} <span>been</span>{' '}
<span className="text-foreground">
{getSinceLastDeployInvocationPhrase(invocationCount)}
</span>{' '}
<span>since last deploy and no errors.</span>
</>
) : (
'Runtime errors since the last deploy will appear here when this function returns a 5xx response.'
)}
</div>
</div>
</div>
)}
{!hasNoErrors && (
<Card className="overflow-hidden">
<EmbeddedLogsTable
rows={rows}
isLoading={isLoading}
isFetching={isFetching}
error={error}
isError={isError}
onRowClick={handleOpenLog}
skeletonRowCount={MAX_VISIBLE_ERRORS}
columnPreferencesKey={EDGE_FUNCTION_LOGS_VIEW.columnPreferencesKey}
footer={
hiddenErrorCount > 0 && (
<div className="px-0.5 py-0.5">
<Button
variant="text"
size="tiny"
className="text-foreground-lighter"
onClick={handleOpenLogs}
>
+{hiddenErrorCount.toLocaleString('en-US')} more
</Button>
</div>
)
}
/>
</Card>
)}
</PageSectionContent>
</PageSection>
)
}