Files
Alaister YoungandAlaister Young 0f14ef4d67 [FE-5109] (part 5) refactor(studio): migrate remaining interfaces and router events off next/router (#54057)
Part 5 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 | Database, Branching, Compute, Edge Functions, Explorer,
SQL Editor, Storage, Table Editor |
| **5** | **#54057 ← this PR** | **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 all remaining `apps/studio/components/interfaces/**`
directories off `next/router`, including the last production
`router.events` consumer (`QueryInsightsTable`) and the only default
`next/router` import (`DiscordCTACard`). After this PR, zero files under
`apps/studio/components/**` import `next/router` or
`next/compat/router`.

**Added:**

-
`apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.test.tsx`:
verifies that pathname changes clear selected query state without
mutating destination or history search params, while same-pathname
search updates preserve selection

**Changed:**

- Replaced the sole production `router.events.on('routeChangeStart',
...)` consumer in `QueryInsightsTable.tsx` with a `pathname` effect that
clears `onCurrentSelectQuery` on pathname changes, and derived
`searchQuery` directly from `nuqs` (`urlSearch`) instead of mirroring it
in local state. Drops the legacy `setQueryStates({ search: null })` call
on leave, which ran after `history.push` on TanStack Router (targeting
the destination URL rather than the previous history entry, while
browser Back is expected to restore previous search params).
- Removed the `router: NextRouter` prop from `ReportWidgetRendererProps`
in `Reports/ReportWidget.tsx` and updated its callers (`ChartBlock`,
`ReportHeader`, `CreateReportModal`)
- Updated `LOG_ROUTES_WITH_REPLICA_SUPPORT` in
`Settings/Logs/Logs.constants.ts` from `[ref]` to `$ref` for TanStack
route patterns
- Replaced the default `import router from 'next/router'` in
`Support/DiscordCTACard.tsx` with `useNavigate`
- Replaced `useRouter` across `Account`, `Advisors`, `App`, `Auth`,
`ErrorHandling`, `Home`, `HomePageActions`, `Integrations`, `Linter`,
`LocalDropdown`, `Observability`, `Organization`, `OrganizationInvite`,
`Platform/Webhooks`, `Project`, `ProjectCreation`, `ProjectHome`,
`QueryPerformance`, `RedeemCredits`, `Settings`, `Sidebar`, `SignIn`,
`Support`, `UnifiedLogs`, and `UserDropdown`
- Updated affected tests (`Auth/Users/UserPanel`, `Home/ProjectList`,
`LocalDropdown`, `Organization/*`, `OrganizationInvite`,
`RedeemCredits`, `Settings/General/*`, `SignIn/SignInRecoveryCodeForm`,
`UnifiedLogs/*`)

**Simplified:**

- `LocalDropdown`, `UserDropdown` and `RedeemCredits` build the current
route from `location.href`, so the hash keeps its leading `#`
- `NewOrgForm` navigates to the `returnTo` path instead of an absolute
URL, which was being treated as external. It also uses a typed
`/new/$slug` navigate.
- Read search params from `useParams()` instead of `location.search`
casts (`CronJobPage`, `QueuePage`, `LogsPreviewer`,
`LinkSupportTicketPage`, `MarketplaceSidebar`, `PlanCards`,
`SignUpForm`)
- Dropped the dead `isReady`/`isRouterReady` constants and the
`navigate<AnyRouter, string>` casts where typed routes work
(`ForgotPasswordWizard`, `SignInPartner`, `ReportWidget`,
`ProjectUpgradeAlert`)
- Linter, `ReportHeader` and `LogsPreviewer` use `to: '.'` instead of a
separate pathname subscription. `CreateReportModal` builds the preserved
query params in `onSuccess` instead of a `useMemo`.
- Tests use the shared `createTestRouter` and `customRender` router.
`LocalDropdown` now tests that the hash is kept.

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

## To test

- [x] Query Insights: select a query and confirm search/filter updates
keep selection while switching projects/routes clears it; navigating to
Logs keeps Logs' query params intact and pressing Back restores Query
Insights' `?search=` param cleanly
- [x] Auth / Sign-in flows: sign in, sign up, MFA, recovery code,
forgot/reset password, and partner sign-in preserve `returnTo` and
redirect as expected
- [x] Organization & Project flows: creating an org/project, accepting
an org invite, claiming a project, redeeming credits, and
deleting/pausing/restarting a project or branch navigate cleanly
- [ ] Logs & Reports: replica selector appears on supported log routes
(`LOG_ROUTES_WITH_REPLICA_SUPPORT`), saved log queries open, and custom
reports create/navigate properly
- [ ] Sidebar, LocalDropdown, UserDropdown, Integrations
(Cron/Queues/Marketplace), Advisors/Linter, and Unified Logs navigate
cleanly

---------

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

578 lines
22 KiB
TypeScript

import { safeSql, type SafeSqlFragment } from '@supabase/pg-meta'
import { wrapWithRollback } from '@supabase/pg-meta/src/query'
import { useLocation, useNavigate } from '@tanstack/react-router'
import { useParams } from 'common'
import { SearchIcon, TextSearchIcon, XIcon } from 'lucide-react'
import { parseAsArrayOf, parseAsString, useQueryStates } from 'nuqs'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import DataGrid, { DataGridHandle, Row } from 'react-data-grid'
import { Button, cn, FloatingPlate, Tabs, TabsList, TabsTrigger } from 'ui'
import { Input } from 'ui-patterns/DataInputs/Input'
import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'
import { buildQueryInsightFixPrompt } from '../../QueryPerformance/QueryPerformance.ai'
import type { QueryPerformanceRow } from '../../QueryPerformance/QueryPerformance.types'
import { useQueryInsightsIssues } from '../hooks/useQueryInsightsIssues'
import { useQueryInsightsTableColumns } from '../hooks/useQueryInsightsTableColumns'
import type { ClassifiedQuery } from '../QueryInsightsHealth/QueryInsightsHealth.types'
import { QueryInsightsDetailSheet } from './QueryInsightsDetailSheet'
import type { IssueFilter, Mode } from './QueryInsightsTable.types'
import {
formatDuration,
getColumnName,
getQueryType,
getTableName,
} from './QueryInsightsTable.utils'
import type { QueryPlanRow } from '@/components/interfaces/ExplainVisualizer/ExplainVisualizer.types'
import { FilterPill } from '@/components/interfaces/QueryPerformance/components/FilterPill'
import { SIDEBAR_KEYS } from '@/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'
import { FilterPopover } from '@/components/ui/FilterPopover'
import { TwoOptionToggle } from '@/components/ui/TwoOptionToggle'
import { isUserFaultForStatsStatement } from '@/data/database/pg-stat-statements-sqlstate'
import { unguarded } from '@/data/fetchers'
import { useExecuteSqlMutation } from '@/data/sql/execute-sql-mutation'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { navigateToUrl } from '@/lib/navigation'
import { useAiAssistantStateSnapshot } from '@/state/ai-assistant-state'
import { useSidebarManagerSnapshot } from '@/state/sidebar-manager-state'
interface QueryInsightsTableProps {
data: QueryPerformanceRow[]
isLoading: boolean
currentSelectedQuery?: string | null
onCurrentSelectQuery?: (query: string | null) => void
}
export const QueryInsightsTable = ({
data,
isLoading,
currentSelectedQuery,
onCurrentSelectQuery,
}: QueryInsightsTableProps) => {
const [mode, setMode] = useState<Mode>('triage')
const [filter, setFilter] = useState<IssueFilter>('all')
const [
{ search: urlSearch, sort: urlSortCol, order: urlSortOrder, source: urlSource },
setQueryStates,
] = useQueryStates({
search: parseAsString.withDefault(''),
sort: parseAsString,
order: parseAsString,
source: parseAsArrayOf(parseAsString).withDefault([]),
})
const searchQuery = urlSearch
const setSearchQuery = useCallback(
(value: string) => setQueryStates({ search: value || null }),
[setQueryStates]
)
const appNameFilter = urlSource
const setAppNameFilter = (names: string[]) =>
setQueryStates({ source: names.length ? names : null })
const appNameOptions = useMemo(() => {
const names = Array.from(
new Set(data.map((r) => r.application_name).filter(Boolean))
) as string[]
return names.map((name) => ({ value: name, label: name }))
}, [data])
const filteredData = useMemo(() => {
if (appNameFilter.length === 0) return data
return data.filter((r) => appNameFilter.includes(r.application_name ?? ''))
}, [data, appNameFilter])
const { classified, errors, indexIssues, slowQueries } = useQueryInsightsIssues(filteredData)
const [selectedRow, setSelectedRow] = useState<number>()
const [selectedTriageRow, setSelectedTriageRow] = useState<number | undefined>()
const [sheetView, setSheetView] = useState<'details' | 'indexes' | 'explain'>('details')
const gridRef = useRef<DataGridHandle>(null)
const triageGridRef = useRef<DataGridHandle>(null)
const dataGridContainerRef = useRef<HTMLDivElement>(null)
const triageContainerRef = useRef<HTMLDivElement>(null)
const scrollContainerRef = useRef<HTMLDivElement>(null)
const [triageContainerWidth, setTriageContainerWidth] = useState(0)
const sort = useMemo<{ column: string; order: 'asc' | 'desc' }>(
() =>
urlSortCol && urlSortOrder && ['asc', 'desc'].includes(urlSortOrder)
? { column: urlSortCol, order: urlSortOrder as 'asc' | 'desc' }
: { column: 'prop_total_time', order: 'desc' },
[urlSortCol, urlSortOrder]
)
const setSort = useCallback(
(config: { column: string; order: 'asc' | 'desc' } | null) =>
setQueryStates(
config ? { sort: config.column, order: config.order } : { sort: null, order: null }
),
[setQueryStates]
)
const [explainResults, setExplainResults] = useState<Record<string, QueryPlanRow[]>>({})
const [explainLoadingQuery, setExplainLoadingQuery] = useState<string | null>(null)
const { ref } = useParams()
const navigate = useNavigate()
const pathname = useLocation({ select: (location) => location.pathname })
const { openSidebar } = useSidebarManagerSnapshot()
const aiSnap = useAiAssistantStateSnapshot()
const { data: project } = useSelectedProjectQuery()
const { mutate: executeExplain } = useExecuteSqlMutation()
const triageItems = useMemo(() => classified.filter((q) => q.issueType !== null), [classified])
const filteredTriageItems = useMemo(() => {
const filtered =
filter === 'all' ? triageItems : triageItems.filter((q) => q.issueType === filter)
return filtered.map((item) => ({
...item,
queryType: getQueryType(item.query),
}))
}, [triageItems, filter])
const explorerItems = useMemo(() => {
let items = [...classified]
if (searchQuery.trim()) {
const searchLower = searchQuery.toLowerCase()
items = items.filter((item) => {
const queryType = getQueryType(item.query) ?? ''
const tableName = getTableName(item.query) ?? ''
const columnName = getColumnName(item.query) ?? ''
const appName = item.application_name ?? ''
const query = item.query ?? ''
return (
queryType.toLowerCase().includes(searchLower) ||
tableName.toLowerCase().includes(searchLower) ||
columnName.toLowerCase().includes(searchLower) ||
appName.toLowerCase().includes(searchLower) ||
query.toLowerCase().includes(searchLower)
)
})
}
if (sort) {
items.sort((a, b) => {
if (sort.column === 'query') {
const aDate = a.first_seen ? new Date(a.first_seen).getTime() : 0
const bDate = b.first_seen ? new Date(b.first_seen).getTime() : 0
return sort.order === 'asc' ? aDate - bDate : bDate - aDate
}
const aValue: unknown = a[sort.column as keyof typeof a]
const bValue: unknown = b[sort.column as keyof typeof b]
if (typeof aValue === 'number' && typeof bValue === 'number') {
return sort.order === 'asc' ? aValue - bValue : bValue - aValue
}
return 0
})
}
return items
}, [classified, searchQuery, sort])
const activeSheetRow: ClassifiedQuery | undefined = useMemo(() => {
if (mode === 'triage') {
return selectedTriageRow !== undefined ? filteredTriageItems[selectedTriageRow] : undefined
}
return selectedRow !== undefined ? (explorerItems[selectedRow] as ClassifiedQuery) : undefined
}, [mode, selectedTriageRow, selectedRow, filteredTriageItems, explorerItems])
const runExplain = useCallback(
(query: SafeSqlFragment) => {
if (explainResults[query]) return
if (explainLoadingQuery) return
const requestQuery = query
setExplainLoadingQuery(requestQuery)
executeExplain(
{
projectRef: project?.ref,
connectionString: project?.connectionString,
sql: wrapWithRollback(safeSql`EXPLAIN ANALYZE ${requestQuery}`),
// The query text comes from pg_stat_statements, so the user wrote it
sqlOrigin: 'studio',
queryName: 'query-insights-explain',
isUserFaultSqlState: isUserFaultForStatsStatement,
grant: unguarded.migrating,
},
{
onSuccess(data) {
setExplainResults((prev) => ({ ...prev, [requestQuery]: data.result }))
setExplainLoadingQuery(null)
},
onError() {
setExplainLoadingQuery(null)
},
}
)
},
[explainResults, explainLoadingQuery, executeExplain, project]
)
const handleGoToLogs = useCallback(() => {
navigateToUrl(navigate, `/project/${ref}/logs/postgres-logs`)
}, [navigate, ref])
const handleAiSuggestedFix = useCallback(
(item: ClassifiedQuery) => {
const { query, prompt } = buildQueryInsightFixPrompt(item)
openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)
aiSnap.newChat({
sqlSnippets: [{ label: 'Query', content: query }],
initialMessage: prompt,
})
},
[openSidebar, aiSnap]
)
useEffect(() => {
if (sheetView === 'explain' && activeSheetRow?.query) {
runExplain(activeSheetRow.query)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [sheetView, activeSheetRow?.query])
const prevPathnameRef = useRef(pathname)
useEffect(() => {
if (prevPathnameRef.current !== pathname) {
prevPathnameRef.current = pathname
onCurrentSelectQuery?.(null)
}
}, [pathname, onCurrentSelectQuery])
const timeConsumedWidth = useMemo(() => {
if (!explorerItems.length) return 150
let maxWidth = 150
explorerItems.forEach((row) => {
const pct = row.prop_total_time || 0
const total = row.total_time || 0
if (pct && total) {
const text = `${pct.toFixed(1)}% / ${formatDuration(total)}`
maxWidth = Math.max(maxWidth, text.length * 8 + 40)
}
})
return Math.min(maxWidth, 300)
}, [explorerItems])
const triageQueryColWidth = useMemo(() => {
if (!triageContainerWidth) return 380
const fixed = timeConsumedWidth + 100 + 300 + 4
return Math.max(380, triageContainerWidth - fixed - 120)
}, [triageContainerWidth, timeConsumedWidth])
const { columns, triageColumns } = useQueryInsightsTableColumns({
sort,
setSort,
timeConsumedWidth,
triageQueryColWidth,
gridRef,
setSelectedRow,
setSelectedTriageRow,
setSheetView,
handleGoToLogs,
handleAiSuggestedFix,
})
const handleKeyDown = useCallback(
(event: KeyboardEvent) => {
if (!explorerItems.length || selectedRow === undefined) return
if (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') return
event.stopPropagation()
let nextIndex = selectedRow
if (event.key === 'ArrowUp' && selectedRow > 0) {
nextIndex = selectedRow - 1
} else if (event.key === 'ArrowDown' && selectedRow < explorerItems.length - 1) {
nextIndex = selectedRow + 1
}
if (nextIndex !== selectedRow) {
setSelectedRow(nextIndex)
gridRef.current?.scrollToCell({ idx: 0, rowIdx: nextIndex })
}
},
[explorerItems, selectedRow]
)
useEffect(() => {
window.addEventListener('keydown', handleKeyDown, true)
return () => {
window.removeEventListener('keydown', handleKeyDown, true)
}
}, [handleKeyDown])
useEffect(() => {
setSelectedRow(undefined)
}, [searchQuery, sort])
useEffect(() => {
if (mode === 'triage') {
triageGridRef.current?.scrollToCell({ idx: 0, rowIdx: 0 })
} else {
gridRef.current?.scrollToCell({ idx: 0, rowIdx: 0 })
}
}, [mode])
useEffect(() => {
const el = triageContainerRef.current
if (!el) return
const observer = new ResizeObserver(([entry]) => {
setTriageContainerWidth(entry.contentRect.width)
})
observer.observe(el)
return () => observer.disconnect()
}, [])
const errorCount = errors.length
const indexCount = indexIssues.length
const slowCount = slowQueries.length
return (
<div className="flex flex-col flex-1 min-h-0">
<div className="overflow-x-auto shrink-0 bg-surface-100 border-b">
<div className="flex items-center justify-between px-6 h-10 min-w-max">
<div className="flex items-center gap-x-1.5">
<TwoOptionToggle
width={75}
options={['explorer', 'triage']}
activeOption={mode}
borderOverride="border"
onClickOption={(mode) => setMode(mode as Mode)}
/>
{appNameFilter.length > 0 ? (
<FilterPill
label="Source"
value={appNameFilter.join(', ')}
onClear={() => setAppNameFilter([])}
/>
) : (
<FilterPopover
name="Source"
options={appNameOptions}
activeOptions={appNameFilter}
valueKey="value"
labelKey="label"
onSaveFilters={setAppNameFilter}
showOnlyButton={false}
/>
)}
</div>
<div className="flex items-center">
{mode === 'triage' ? (
<Tabs value={filter} onValueChange={(v) => setFilter(v as IssueFilter)}>
<TabsList className="flex gap-x-4 rounded-none mt-0! pt-0 border-none!">
<TabsTrigger value="all" className="text-xs py-3 border-b font-mono uppercase">
All{triageItems.length > 0 && <span>{` (${triageItems.length})`}</span>}
</TabsTrigger>
<TabsTrigger value="error" className="text-xs py-3 border-b font-mono uppercase">
Errors{errorCount > 0 && <span>{` (${errorCount})`}</span>}
</TabsTrigger>
<TabsTrigger value="index" className="text-xs py-3 border-b font-mono uppercase">
Index{indexCount > 0 && <span>{` (${indexCount})`}</span>}
</TabsTrigger>
<TabsTrigger value="slow" className="text-xs py-3 border-b font-mono uppercase">
Slow{slowCount > 0 && <span>{` (${slowCount})`}</span>}
</TabsTrigger>
</TabsList>
</Tabs>
) : (
<Input
size="tiny"
autoComplete="off"
icon={<SearchIcon className="h-4 w-4" />}
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
name="search"
id="search"
placeholder="Search queries..."
className="w-64"
actions={[
searchQuery && (
<Button
key="clear"
size="tiny"
variant="text"
icon={<XIcon className="h-4 w-4" />}
onClick={() => setSearchQuery('')}
className="p-0 h-5 w-5"
/>
),
]}
/>
)}
</div>
</div>
</div>
<div
ref={scrollContainerRef}
className="relative flex-1 min-h-0 flex flex-col overflow-hidden"
>
<div
className={[
'absolute bottom-8 left-0 right-0 flex justify-center z-10 pointer-events-none',
'transition-all duration-200',
currentSelectedQuery
? 'opacity-100 translate-y-0 pointer-events-auto'
: 'opacity-0 translate-y-4 pointer-events-none',
].join(' ')}
>
<FloatingPlate rounded="full">
<Button
size="tiny"
className="rounded-full shadow-md"
onClick={() => onCurrentSelectQuery?.(null)}
>
Clear query
</Button>
</FloatingPlate>
</div>
{isLoading ? (
<div className="px-6 py-4">
<GenericSkeletonLoader />
</div>
) : mode === 'triage' ? (
<div ref={triageContainerRef} className="flex-1 min-h-0 min-w-0 overflow-x-auto">
<DataGrid
ref={triageGridRef}
style={{ height: '100%' }}
className="flex-1 grow h-full border-t-0! border-b-0!"
rowHeight={60}
headerRowHeight={36}
columns={triageColumns}
rows={filteredTriageItems}
rowClass={(_, idx) => {
const isSelected = idx === selectedTriageRow
const query = filteredTriageItems[idx]?.query
const isCharted = currentSelectedQuery ? currentSelectedQuery === query : false
return [
`${isSelected ? 'bg-surface-300 dark:bg-surface-300' : isCharted ? 'bg-surface-200 dark:bg-surface-200' : 'bg-200 hover:bg-surface-200'} cursor-pointer`,
'[&>div:first-child]:border-l-4 [&>div:first-child]:pl-5 [&>div:last-child]:pr-6',
`${isSelected || isCharted ? '[&>div:first-child]:border-l-foreground' : '[&>div:first-child]:border-l-transparent'}`,
'[&>.rdg-cell]:box-border [&>.rdg-cell]:outline-hidden [&>.rdg-cell]:shadow-none [&>.rdg-cell]:py-3',
'[&>.rdg-cell.column-prop_total_time]:relative',
].join(' ')
}}
renderers={{
renderRow(idx, props) {
return (
<Row
{...props}
key={`triage-row-${props.rowIdx}`}
onClick={(event) => {
event.stopPropagation()
if (typeof idx === 'number' && idx >= 0) {
const query = filteredTriageItems[idx]?.query
if (query && onCurrentSelectQuery) {
onCurrentSelectQuery(currentSelectedQuery === query ? null : query)
}
}
}}
/>
)
},
noRowsFallback: (
<div className="absolute top-20 px-6 flex flex-col items-center justify-center w-full gap-y-2">
<TextSearchIcon className="text-foreground-muted" strokeWidth={1} />
<div className="text-center">
<p className="text-foreground">No issues found</p>
<p className="text-foreground-light">
{data.length === 0
? 'No query data available yet'
: 'No issues detected for the selected filter'}
</p>
</div>
</div>
),
}}
/>
</div>
) : (
<div ref={dataGridContainerRef} className="flex-1 min-h-0 min-w-0 overflow-x-auto">
<DataGrid
ref={gridRef}
style={{ height: '100%' }}
className={cn('flex-1 grow h-full border-t-0! border-b-0!')}
rowHeight={44}
headerRowHeight={36}
columns={columns}
rows={explorerItems}
rowClass={(_, idx) => {
const isSelected = idx === selectedRow
const query = explorerItems[idx]?.query
const isCharted = currentSelectedQuery ? currentSelectedQuery === query : false
return [
`${isSelected ? 'bg-surface-300 dark:bg-surface-300' : isCharted ? 'bg-surface-200 dark:bg-surface-200' : 'bg-200 hover:bg-surface-200'} cursor-pointer`,
'[&>div:first-child]:border-l-4 [&>div:first-child]:pl-5 [&>div:last-child]:pr-6',
`${isSelected || isCharted ? '[&>div:first-child]:border-l-foreground' : '[&>div:first-child]:border-l-transparent'}`,
'[&>.rdg-cell]:box-border [&>.rdg-cell]:outline-hidden [&>.rdg-cell]:shadow-none [&>.rdg-cell]:py-3',
'[&>.rdg-cell.column-prop_total_time]:relative',
].join(' ')
}}
renderers={{
renderRow(idx, props) {
return (
<Row
{...props}
key={`explorer-row-${props.rowIdx}`}
onClick={(event) => {
event.stopPropagation()
if (typeof idx === 'number' && idx >= 0) {
const query = explorerItems[idx]?.query
if (query && onCurrentSelectQuery) {
onCurrentSelectQuery(currentSelectedQuery === query ? null : query)
}
}
}}
/>
)
},
noRowsFallback: (
<div className="absolute top-20 px-6 flex flex-col items-center justify-center w-full gap-y-2">
<TextSearchIcon className="text-foreground-muted" strokeWidth={1} />
<div className="text-center">
<p className="text-foreground">No queries found</p>
<p className="text-foreground-light">
{searchQuery.trim()
? 'No queries match your search criteria'
: 'No query data available yet'}
</p>
</div>
</div>
),
}}
/>
</div>
)}
</div>
<QueryInsightsDetailSheet
open={activeSheetRow !== undefined}
onOpenChange={(open) => {
if (!open) {
setSelectedTriageRow(undefined)
setSelectedRow(undefined)
}
}}
activeSheetRow={activeSheetRow}
sheetView={sheetView}
onSheetViewChange={setSheetView}
onClose={() => {
setSelectedTriageRow(undefined)
setSelectedRow(undefined)
}}
dataGridContainerRef={dataGridContainerRef}
triageContainerRef={triageContainerRef}
explainLoadingQuery={explainLoadingQuery}
explainResults={explainResults}
/>
</div>
)
}