Files
Alaister YoungandAlaister Young 01d4d4d430 [FE-5113] refactor(studio): replace next/dynamic shim with React.lazy (#54022)
## Problem

Now that Studio runs on TanStack Start, `apps/studio` still routes 13
`next/dynamic` imports through a local compatibility shim
(`apps/studio/compat/next/dynamic.tsx` aliased in
`apps/studio/vite.config.ts`). Keeping the shim adds unnecessary
indirection during the Next.js teardown (FE-5113).

## Solution

Replaces every `next/dynamic` import in `apps/studio` with `React.lazy`
+ `Suspense` (or static imports where already inside a lazy chunk), then
deletes `compat/next/dynamic.tsx` and its Vite alias.

None of the previously `ssr: false` call sites need `ClientOnly`: Studio
runs TanStack Start with `spa: { enabled: true }` and only prerenders
the signed-out auth routes (`/sign-in`, `/sign-up`, `/sign-in-sso`,
`/forgot-password`), `__root.tsx` gates `<Outlet />` behind
`canRenderPage`, and `StudioCommandMenu` is already gated by
`useCommandMenuInitiated()` (which starts `false` per render).

**Removed:**

- `apps/studio/compat/next/dynamic.tsx` and the `'next/dynamic'` entry
in `nextShims` in `apps/studio/vite.config.ts`

**Changed:**

- Migrated all `next/dynamic` call sites to `React.lazy` + `Suspense`:
- `StudioCommandMenu`, `ContextSearchResults`,
`Marketplace/OverviewTab`, `QueryDetail` (`SqlMonacoBlock`),
`SQLEditorEditorPanel` (`MonacoEditor`, `DiffEditor`),
`SupportAssistantSuccessCard`, `LayoutSidebarProvider`,
`MessageMarkdown` (`Streamdown`), and
`SupportAssistantSuccessCardContent` (`Streamdown`)
- `ConnectStepsSection`: hoisted the lazy component cache out of
`useMemo` to module scope (also clears its
`react/no-unstable-nested-components` warning)
- `Integrations.constants.tsx` and `useAvailableIntegrations.tsx`:
hoisted all lazy integration tab/page definitions (including
`GraphiQLTab`) to module scope so `navigate()` returns stable component
references, added `Suspense` boundaries with `<Loading />` at both
render points (`MarketplaceDetail` and the integration child route), and
keyed integration tab/creation sheet instances (`integration.id` in
`MarketplaceDetail` and `wrapperMeta.name` in `WrappersTab`) so state
cannot leak when switching between wrappers or OAuth integrations;
preserves `umdAmdShortCircuit`, `ssrStubGraphiql`, and
`graphiqlViteWorkers` in `vite.config.ts`
- Replaced `dynamic()` calls for `AiIconAnimation`, `Badge`, and 4
`icons` in `CreateCommands.tsx` with static imports (already inside the
lazy `CommandMenu` chunk)
- Removed the stale `next/dynamic` mention from the
`lib/chunk-load-error.ts` doc comment (`React.lazy` chunk failures
continue bubbling to the root `ErrorBoundary` reload handler)

**Added:**

- Reference-stability tests for `INTEGRATIONS.navigate` in
`Integrations.constants.test.ts` (running in Vitest's Node environment)

## Review instructions

1. Open the SQL Editor and Query Performance query detail panel, and
confirm the Monaco editor and diff view load cleanly.
2. Open the GraphQL integration's GraphiQL tab, and confirm the loading
skeleton displays while the chunk loads and GraphiQL mounts with working
autocomplete/workers.
3. Open a Wrapper integration's Wrappers tab, open the create sheet,
then navigate via history to a different wrapper's create sheet and
confirm the form resets to the new wrapper's defaults.
4. Open the Command Menu (`Cmd+K`), navigate to context search (for
example, Search Database Tables) and Create commands, and confirm icons,
badges, and search results load without flicker.
5. Open the Connect sheet and switch between frameworks/steps,
confirming step content loads with the skeleton fallback.
6. Toggle sidebars (AI Assistant, Inline SQL Editor, Advisor, Help) and
verify markdown streaming in AI Assistant.
7. Confirm CI passes `pnpm --filter studio run build` (including
prerendering and chunk-cycle checks), typecheck, lint ratchet, and
Studio tests.

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-11-26 08:46:55 +00:00

253 lines
9.5 KiB
TypeScript

import { ChevronsUpDownIcon, LightbulbIcon } from 'lucide-react'
import { lazy, Suspense, useEffect, useState } from 'react'
import { Alert, AlertDescription, AlertTitle, Button, cn, FloatingPlate } from 'ui'
import { QueryPanelContainer, QueryPanelSection } from './QueryPanel'
import { buildQueryExplanationPrompt } from './QueryPerformance.ai'
import { QUERY_PERFORMANCE_COLUMNS } from './QueryPerformance.constants'
import { QueryPerformanceRow } from './QueryPerformance.types'
import { formatDuration } from './QueryPerformance.utils'
import { SIDEBAR_KEYS } from '@/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'
import { AiAssistantDropdown } from '@/components/ui/AiAssistantDropdown'
import { formatSql } from '@/lib/formatSql'
import { useTrack } from '@/lib/telemetry/track'
import { useAiAssistantStateSnapshot } from '@/state/ai-assistant-state'
import { useSidebarManagerSnapshot } from '@/state/sidebar-manager-state'
interface QueryDetailProps {
selectedRow?: QueryPerformanceRow
onClickViewSuggestion: () => void
onClose?: () => void
}
// Load SqlMonacoBlock (monaco editor) client-side only (does not behave well server-side)
const SqlMonacoBlock = lazy(() =>
import('./SqlMonacoBlock').then(({ SqlMonacoBlock }) => ({ default: SqlMonacoBlock }))
)
export const QueryDetail = ({ selectedRow, onClickViewSuggestion, onClose }: QueryDetailProps) => {
// [Joshen] TODO implement this logic once the linter rules are in
const isLinterWarning = false
const report = QUERY_PERFORMANCE_COLUMNS
const [query, setQuery] = useState(selectedRow?.['query'])
const { openSidebar } = useSidebarManagerSnapshot()
const aiSnap = useAiAssistantStateSnapshot()
const track = useTrack()
useEffect(() => {
if (selectedRow !== undefined) {
const formattedQuery = formatSql(selectedRow['query'])
setQuery(formattedQuery)
}
}, [selectedRow])
const [isExpanded, setIsExpanded] = useState(false)
const handleExplainQuery = () => {
if (!selectedRow?.query) return
const { query, prompt } = buildQueryExplanationPrompt(selectedRow)
openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)
aiSnap.newChat({
sqlSnippets: [
{
label: 'Query',
content: query,
},
],
initialMessage: prompt,
})
track('query_performance_explain_with_ai_button_clicked')
// Close the query detail panel since we need to see the AI assistant panel
onClose?.()
}
const buildPromptForCopy = () => {
if (!selectedRow?.query) return ''
const { query, prompt } = buildQueryExplanationPrompt(selectedRow)
return `${prompt}\n\nSQL Query:\n\`\`\`sql\n${query}\n\`\`\``
}
return (
<QueryPanelContainer>
<QueryPanelSection className="pt-2 border-b relative">
<div className="flex items-center justify-between mb-4">
<h4>Query pattern</h4>
<AiAssistantDropdown
label="Explain with AI"
buildPrompt={buildPromptForCopy}
onOpenAssistant={handleExplainQuery}
telemetrySource="query_performance"
size="tiny"
variant="default"
/>
</div>
<div
id="query-detail-sql-panel"
className={cn(
'overflow-hidden pb-0 z-0 relative transition-all duration-300',
isExpanded ? 'h-[348px]' : 'h-[120px]'
)}
>
<Suspense fallback={null}>
<SqlMonacoBlock
value={query}
wrapperClassName={cn('bg-surface-100', !isExpanded && 'pointer-events-none')}
/>
</Suspense>
{isLinterWarning && (
<Alert
variant="default"
className="mt-2 border-brand-400 bg-alternative [&>svg]:p-0.5 [&>svg]:bg-transparent [&>svg]:text-primary"
>
<LightbulbIcon />
<AlertTitle>Suggested optimization: Add an index</AlertTitle>
<AlertDescription>
Adding an index will help this query execute faster
</AlertDescription>
<AlertDescription>
<Button variant="primary" className="mt-3" onClick={() => onClickViewSuggestion()}>
View suggestion
</Button>
</AlertDescription>
</Alert>
)}
</div>
<div
className={cn(
'absolute left-0 bottom-0 w-full bg-linear-to-t from-black/30 to-transparent h-24 transition-opacity duration-300',
isExpanded && 'opacity-0 pointer-events-none'
)}
/>
<div className="absolute bottom-[-13px] left-0 right-0 w-full flex items-center justify-center z-10">
<FloatingPlate rounded="full">
<Button
type="button"
className="rounded-full"
icon={<ChevronsUpDownIcon />}
aria-expanded={isExpanded}
aria-controls="query-detail-sql-panel"
onClick={() => setIsExpanded(!isExpanded)}
>
{isExpanded ? 'Collapse' : 'Expand'}
</Button>
</FloatingPlate>
</div>
</QueryPanelSection>
<QueryPanelSection className="pb-3 pt-6">
<h4 className="mb-4">Metadata</h4>
<ul className="flex flex-col gap-y-3 divide-y divide-dashed">
{report
.filter((x) => x.id !== 'query')
.map((x) => {
const rawValue = selectedRow?.[x.id]
const isTime = x.name.includes('time')
const formattedValue = isTime
? typeof rawValue === 'number' && !isNaN(rawValue) && isFinite(rawValue)
? `${Math.round(rawValue).toLocaleString()}ms`
: 'n/a'
: rawValue != null
? String(rawValue)
: 'n/a'
if (x.id === 'prop_total_time') {
const percentage = selectedRow?.prop_total_time || 0
const totalTime = selectedRow?.total_time || 0
return (
<li key={x.id} className="flex justify-between pb-3 text-sm">
<p className="text-foreground-light">{x.name}</p>
{percentage && totalTime ? (
<p className="flex items-center gap-x-1.5">
<span
className={cn(
'tabular-nums',
percentage.toFixed(1) === '0.0' && 'text-foreground-lighter'
)}
>
{percentage.toFixed(1)}%
</span>{' '}
<span className="text-muted">/</span>{' '}
<span
className={cn(
'tabular-nums',
formatDuration(totalTime) === '0.00s' && 'text-foreground-lighter'
)}
>
{formatDuration(totalTime)}
</span>
</p>
) : (
<p className="text-muted">&ndash;</p>
)}
</li>
)
}
if (x.id == 'rows_read') {
return (
<li key={x.id} className="flex justify-between pb-3 text-sm">
<p className="text-foreground-light">{x.name}</p>
{typeof rawValue === 'number' && !isNaN(rawValue) && isFinite(rawValue) ? (
<p
className={cn('tabular-nums', rawValue === 0 && 'text-foreground-lighter')}
>
{rawValue.toLocaleString()}
</p>
) : (
<p className="text-muted">&ndash;</p>
)}
</li>
)
}
const cacheHitRateToNumber = (value: number | string) => {
if (typeof value === 'number') return value
return parseFloat(value.toString().replace('%', '')) || 0
}
if (x.id === 'cache_hit_rate') {
return (
<li key={x.id} className="flex justify-between pb-3 text-sm">
<p className="text-foreground-light">{x.name}</p>
{typeof rawValue === 'string' || typeof rawValue === 'number' ? (
<p
className={cn(
cacheHitRateToNumber(rawValue).toFixed(2) === '0.00' &&
'text-foreground-lighter'
)}
>
{cacheHitRateToNumber(rawValue).toLocaleString(undefined, {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
})}
%
</p>
) : (
<p className="text-muted">&ndash;</p>
)}
</li>
)
}
return (
<li key={x.id} className="flex justify-between pb-3 text-sm">
<p className="text-foreground-light">{x.name}</p>
<p className={cn('tabular-nums', x.id === 'rolname' && 'font-mono')}>
{formattedValue}
</p>
</li>
)
})}
</ul>
</QueryPanelSection>
</QueryPanelContainer>
)
}