Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

feat(studio): resizable query/results split in the Explorer query editor (#49984)

Saxon Fletcherc365549ab895
diff --git a/apps/studio/components/interfaces/Explorer/QueryEditor/QueryResultError.tsx b/apps/studio/components/interfaces/Explorer/QueryEditor/QueryResultError.tsx
index c3a0863e695..0cfe3be9b24 100644
--- a/apps/studio/components/interfaces/Explorer/QueryEditor/QueryResultError.tsx
+++ b/apps/studio/components/interfaces/Explorer/QueryEditor/QueryResultError.tsx
@@ -84,7 +84,7 @@ export const QueryResultError = ({
)
return (
- <div className="w-full bg-table-header-light in-data-[theme*=dark]:bg-table-header-dark overflow-y-auto">
+ <div className="w-full overflow-y-auto">
<div className="flex flex-row justify-between items-start py-4 px-6 gap-x-4">
{isTimeout ? (
<div className="flex flex-col gap-y-1">
diff --git a/apps/studio/components/interfaces/Explorer/QueryEditor/QueryRunButton.tsx b/apps/studio/components/interfaces/Explorer/QueryEditor/QueryRunButton.tsx
index bac5df8a5a9..9a4fe033020 100644
--- a/apps/studio/components/interfaces/Explorer/QueryEditor/QueryRunButton.tsx
+++ b/apps/studio/components/interfaces/Explorer/QueryEditor/QueryRunButton.tsx
@@ -3,12 +3,12 @@ import {
Button,
DropdownMenu,
DropdownMenuContent,
+ DropdownMenuItem,
DropdownMenuTrigger,
KeyboardShortcut,
} from 'ui'
import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
-import { DropdownMenuItemTooltip } from '@/components/ui/DropdownMenuItemTooltip'
interface QueryRunButtonProps {
isExecuting: boolean
@@ -63,20 +63,9 @@ export const QueryRunButton = ({
/>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
- <DropdownMenuItemTooltip
- disabled={!hasSelection}
- onClick={onRunSelected}
- tooltip={{
- content: {
- side: 'left',
- text: !hasSelection
- ? 'Select SQL in the editor to run part of the query'
- : undefined,
- },
- }}
- >
- Run selected
- </DropdownMenuItemTooltip>
+ <DropdownMenuItem disabled={!hasSelection} onClick={onRunSelected}>
+ Run selected SQL
+ </DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
diff --git a/apps/studio/components/interfaces/Explorer/QueryEditor/index.tsx b/apps/studio/components/interfaces/Explorer/QueryEditor/index.tsx
index e8b3287bd09..baea5d34660 100644
--- a/apps/studio/components/interfaces/Explorer/QueryEditor/index.tsx
+++ b/apps/studio/components/interfaces/Explorer/QueryEditor/index.tsx
@@ -12,7 +12,7 @@ import {
useState,
type ReactNode,
} from 'react'
-import { Button, cn } from 'ui'
+import { Button, cn, ResizableHandle, ResizablePanel, ResizablePanelGroup } from 'ui'
import { resolveLogTimeRange } from '../../QuerySources/LogTimeRange.utils'
import {
@@ -131,7 +131,7 @@ type QueryEditorProps = {
className?: string
showQuery: boolean
onShowQueryChange: (showQuery: boolean) => void
- /** When true, toolbar and editor run actions are disabled. */
+ /** Disables editor run actions and hides the toolbar run button (e.g. while an external confirm footer owns the run). */
isRunDisabled?: boolean
onTitleChange: (title: string) => void
onSqlChange: (sql: string) => void
@@ -367,6 +367,7 @@ export const QueryEditor = forwardRef<QueryEditorHandle, QueryEditorProps>(funct
}
const Shell = variant === 'viewport' ? ExplorerQueryViewport : ExplorerQuery
+ const isResizableSplit = variant === 'viewport' && showQuery
const handlePrettify = async () => {
if (pendingProposalRef.current) return
@@ -391,6 +392,154 @@ export const QueryEditor = forwardRef<QueryEditorHandle, QueryEditorProps>(funct
return () => node.removeEventListener('keydown', handleEscapeKey)
}, [promptState?.isOpen])
+ const shouldCenterResults =
+ !result?.error && ((result?.rows ?? []).length === 0 || (view === 'chart' && !hasConfig))
+
+ const queryResults = (
+ <ExplorerQueryResults
+ className={cn(
+ variant === 'embedded' ? 'max-h-80' : 'h-full',
+ shouldCenterResults ? 'items-center justify-center' : 'overflow-x-auto'
+ )}
+ >
+ <QueryResultRenderer
+ view={view}
+ result={result}
+ chart={display?.chart}
+ sql={result?.sql}
+ source={result?.source}
+ onDebug={onDebug}
+ />
+ </ExplorerQueryResults>
+ )
+
+ const querySql = showQuery ? (
+ <>
+ <LegacyLogsRewriteBanner
+ isLogsSource={query._tag === 'logs'}
+ sql={sql}
+ readSql={() => sqlRef.current}
+ onProposal={({ original, modified }) =>
+ setPendingProposal({
+ original,
+ modified,
+ label: 'Review the ClickHouse SQL rewrite before accepting it',
+ })
+ }
+ hidden={pendingProposal !== null}
+ />
+ <ExplorerQueryEditor
+ className={cn('relative', isResizableSplit && 'h-full min-h-0 flex-1 border-b-0')}
+ >
+ <CodeEditor
+ id={`explorer-query-${id}`}
+ language="pgsql"
+ isReadOnly={isReadOnly}
+ value={sql}
+ placeholder={!promptState?.isOpen ? generatePlaceholder(os) : ''}
+ placeholderClassName="top-[13px]"
+ className={isResizableSplit ? undefined : 'h-44'}
+ actions={{
+ runQuery: {
+ enabled: !isRunDisabled,
+ callback: (rawSql: string) => handleRunQuery({ rawSql }),
+ },
+ }}
+ options={{
+ minimap: { enabled: false },
+ padding: { top: 8 },
+ }}
+ onInputChange={(value) => onSqlChange(value ?? '')}
+ onMount={(editor, monaco) => {
+ editor.onDidBlurEditorWidget(() => onSqlCommitRef.current?.(sqlRef.current))
+ editorInstanceRef.current = editor
+
+ const updateHasSelection = (selection: Selection | null | undefined) => {
+ const noSelection =
+ !selection ||
+ (selection.startLineNumber === selection.endLineNumber &&
+ selection.startColumn === selection.endColumn)
+ setHasSelection(!noSelection)
+ }
+
+ // A remount (e.g. toggling "Show query" off then on) creates a fresh
+ // editor with no listener history, so `hasSelection` must be read from
+ // this instance directly rather than left at whatever the previous
+ // editor instance last reported.
+ updateHasSelection(editor.getSelection())
+ editor.onDidChangeCursorSelection(({ selection }) => updateHasSelection(selection))
+
+ editor.addAction({
+ id: 'generate-sql',
+ label: 'Generate SQL',
+ keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyMod.Shift | monaco.KeyCode.KeyK],
+ run: () => {
+ if (pendingProposalRef.current) return
+ const selectionParts = getEditorSelectionParts(editor)
+ if (selectionParts) setPromptState({ isOpen: true, ...selectionParts })
+ },
+ })
+
+ editor.addAction({
+ id: 'prettify-query',
+ label: 'Prettify SQL',
+ keybindings: [monaco.KeyMod.Alt | monaco.KeyMod.Shift | monaco.KeyCode.KeyF],
+ contextMenuGroupId: 'operation',
+ run: () => {
+ handlePrettify()
+ },
+ })
+ }}
+ />
+
+ {promptState?.isOpen && editorInstanceRef.current && !pendingProposal && (
+ <ResizableAIWidget
+ editor={editorInstanceRef.current}
+ id={`explorer-ask-ai-${id}`}
+ value={promptInput}
+ onChange={setPromptInput}
+ onSubmit={handleGenerateSql}
+ onCancel={closePrompt}
+ isDiffVisible={false}
+ isLoading={isCompletionLoading}
+ startLineNumber={Math.max(0, promptState.startLineNumber)}
+ endLineNumber={promptState.endLineNumber}
+ />
+ )}
+
+ {pendingProposal && (
+ <div className="absolute inset-0 z-10 flex flex-col bg-studio">
+ <div className="flex items-center justify-between gap-2 border-b bg-surface-100 px-3 py-2">
+ <div>
+ <p className="text-xs text-foreground-light">{pendingProposal.label}</p>
+ {pendingProposal.prompt && (
+ <p className="text-xs text-foreground-lighter">
+ Prompt: {pendingProposal.prompt}
+ </p>
+ )}
+ </div>
+ <div className="flex items-center gap-2">
+ <Button variant="default" size="tiny" onClick={() => setPendingProposal(null)}>
+ Discard
+ </Button>
+ <Button variant="primary" size="tiny" onClick={acceptSqlProposal}>
+ Accept
+ </Button>
+ </div>
+ </div>
+ <div className="min-h-0 flex-1">
+ <DiffEditor
+ language="pgsql"
+ original={pendingProposal.original}
+ modified={pendingProposal.modified}
+ />
+ </div>
+ </div>
+ )}
+ </ExplorerQueryEditor>
+ </>
+ ) : null
+
return (
<>
<Shell className={cn(variant === 'embedded' && 'mx-auto max-w-6xl', className)}>
@@ -440,175 +589,39 @@ export const QueryEditor = forwardRef<QueryEditorHandle, QueryEditorProps>(funct
{toolbarActions}
- <QueryRunButton
- isExecuting={isExecuting}
- disabled={
- isBusy || pendingProposal !== null || isRunDisabled || sql.trim().length === 0
- }
- hasSelection={showQuery && hasSelection}
- onRun={() => handleRunQuery({ rawSql: sql })}
- onRunSelected={() => {
- const editorInstance = editorInstanceRef.current
- const rawSql = editorInstance ? getEditorValueOrSelection(editorInstance) : sql
- handleRunQuery({ rawSql })
- }}
- />
+ {!isRunDisabled && (
+ <QueryRunButton
+ isExecuting={isExecuting}
+ disabled={isBusy || pendingProposal !== null || sql.trim().length === 0}
+ hasSelection={showQuery && hasSelection}
+ onRun={() => handleRunQuery({ rawSql: sql })}
+ onRunSelected={() => {
+ const editorInstance = editorInstanceRef.current
+ const rawSql = editorInstance ? getEditorValueOrSelection(editorInstance) : sql
+ handleRunQuery({ rawSql })
+ }}
+ />
+ )}
</ExplorerToolbarActions>
</ExplorerToolbar>
- {showQuery && (
+ {isResizableSplit ? (
+ <ResizablePanelGroup orientation="vertical" className="relative h-0 min-h-0 flex-1">
+ <ResizablePanel defaultSize="40" maxSize="70">
+ <div className="flex h-full min-h-0 flex-col overflow-hidden">{querySql}</div>
+ </ResizablePanel>
+ <ResizableHandle withHandle />
+ <ResizablePanel defaultSize="60" maxSize="70">
+ <div className="flex h-full min-h-0 flex-col overflow-hidden">{queryResults}</div>
+ </ResizablePanel>
+ </ResizablePanelGroup>
+ ) : (
<>
- <LegacyLogsRewriteBanner
- isLogsSource={query._tag === 'logs'}
- sql={sql}
- readSql={() => sqlRef.current}
- onProposal={({ original, modified }) =>
- setPendingProposal({
- original,
- modified,
- label: 'Review the ClickHouse SQL rewrite before accepting it',
- })
- }
- hidden={pendingProposal !== null}
- />
- <ExplorerQueryEditor
- className={cn('relative', variant === 'viewport' ? 'h-[45%] min-h-48' : undefined)}
- >
- <CodeEditor
- id={`explorer-query-${id}`}
- language="pgsql"
- isReadOnly={isReadOnly}
- value={sql}
- placeholder={!promptState?.isOpen ? generatePlaceholder(os) : ''}
- placeholderClassName="top-[13px]"
- className={variant === 'embedded' ? 'h-44' : undefined}
- actions={{
- runQuery: {
- enabled: !isRunDisabled,
- callback: (rawSql: string) => handleRunQuery({ rawSql }),
- },
- }}
- options={{
- minimap: { enabled: false },
- padding: { top: 8 },
- }}
- onInputChange={(value) => onSqlChange(value ?? '')}
- onMount={(editor, monaco) => {
- editor.onDidBlurEditorWidget(() => onSqlCommitRef.current?.(sqlRef.current))
- editorInstanceRef.current = editor
-
- const updateHasSelection = (selection: Selection | null | undefined) => {
- const noSelection =
- !selection ||
- (selection.startLineNumber === selection.endLineNumber &&
- selection.startColumn === selection.endColumn)
- setHasSelection(!noSelection)
- }
-
- // A remount (e.g. toggling "Show query" off then on) creates a fresh
- // editor with no listener history, so `hasSelection` must be read from
- // this instance directly rather than left at whatever the previous
- // editor instance last reported.
- updateHasSelection(editor.getSelection())
- editor.onDidChangeCursorSelection(({ selection }) =>
- updateHasSelection(selection)
- )
-
- editor.addAction({
- id: 'generate-sql',
- label: 'Generate SQL',
- keybindings: [
- monaco.KeyMod.CtrlCmd | monaco.KeyMod.Shift | monaco.KeyCode.KeyK,
- ],
- run: () => {
- if (pendingProposalRef.current) return
- const selectionParts = getEditorSelectionParts(editor)
- if (selectionParts) setPromptState({ isOpen: true, ...selectionParts })
- },
- })
-
- editor.addAction({
- id: 'prettify-query',
- label: 'Prettify SQL',
- keybindings: [monaco.KeyMod.Alt | monaco.KeyMod.Shift | monaco.KeyCode.KeyF],
- contextMenuGroupId: 'operation',
- run: () => {
- handlePrettify()
- },
- })
- }}
- />
-
- {promptState?.isOpen && editorInstanceRef.current && !pendingProposal && (
- <ResizableAIWidget
- editor={editorInstanceRef.current}
- id={`explorer-ask-ai-${id}`}
- value={promptInput}
- onChange={setPromptInput}
- onSubmit={handleGenerateSql}
- onCancel={closePrompt}
- isDiffVisible={false}
- isLoading={isCompletionLoading}
- startLineNumber={Math.max(0, promptState.startLineNumber)}
- endLineNumber={promptState.endLineNumber}
- />
- )}
-
- {pendingProposal && (
- <div className="absolute inset-0 z-10 flex flex-col bg-studio">
- <div className="flex items-center justify-between gap-2 border-b bg-surface-100 px-3 py-2">
- <div>
- <p className="text-xs text-foreground-light">{pendingProposal.label}</p>
- {pendingProposal.prompt && (
- <p className="text-xs text-foreground-lighter">
- Prompt: {pendingProposal.prompt}
- </p>
- )}
- </div>
- <div className="flex items-center gap-2">
- <Button
- variant="default"
- size="tiny"
- onClick={() => setPendingProposal(null)}
- >
- Discard
- </Button>
- <Button variant="primary" size="tiny" onClick={acceptSqlProposal}>
- Accept
- </Button>
- </div>
- </div>
- <div className="min-h-0 flex-1">
- <DiffEditor
- language="pgsql"
- original={pendingProposal.original}
- modified={pendingProposal.modified}
- />
- </div>
- </div>
- )}
- </ExplorerQueryEditor>
+ {querySql}
+ {queryResults}
</>
)}
- <ExplorerQueryResults
- className={cn(
- variant === 'embedded' ? 'max-h-80' : '',
- (result?.rows ?? []).length === 0 || (view === 'chart' && !hasConfig)
- ? 'items-center justify-center'
- : 'overflow-x-auto'
- )}
- >
- <QueryResultRenderer
- view={view}
- result={result}
- chart={display?.chart}
- sql={result?.sql}
- source={result?.source}
- onDebug={onDebug}
- />
- </ExplorerQueryResults>
-
<ExplorerQueryFooter className="flex items-center gap-x-2">
<p>{(result?.rows ?? []).length.toLocaleString()} rows</p>
{rowLimit && (
diff --git a/apps/studio/components/interfaces/Explorer/__tests__/QueryTab.test.tsx b/apps/studio/components/interfaces/Explorer/__tests__/QueryTab.test.tsx
index e9c2dbf799f..cde619b1a7e 100644
--- a/apps/studio/components/interfaces/Explorer/__tests__/QueryTab.test.tsx
+++ b/apps/studio/components/interfaces/Explorer/__tests__/QueryTab.test.tsx
@@ -1,7 +1,7 @@
import { act, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { HttpResponse } from 'msw'
-import { useEffect, useRef } from 'react'
+import { useEffect, useRef, type ReactNode } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ExplorerQueryTab } from '../ExplorerQueryTab'
@@ -94,6 +94,20 @@ vi.mock('../QueryEditor/QuerySourceMenu', () => ({
),
}))
+// react-resizable-panels needs real layout to mount panel content, which jsdom can't provide.
+vi.mock('ui', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('ui')>()
+ const Passthrough = ({ children, ...props }: { children?: ReactNode }) => (
+ <div {...props}>{children}</div>
+ )
+ return {
+ ...actual,
+ ResizableHandle: (props: Record<string, unknown>) => <div {...props} />,
+ ResizablePanel: Passthrough,
+ ResizablePanelGroup: Passthrough,
+ }
+})
+
vi.mock('../QueryEditor/DisplaySettingsButton', () => ({
DisplaySettingsButton: ({
display,
@@ -456,7 +470,7 @@ describe('QueryTab execution', () => {
expect(executedQueries[0]).toContain('select 2')
})
- it('runs only the selected text from the Run selected menu item', async () => {
+ it('runs only the selected text from the Run selected SQL menu item', async () => {
createDraft({ _tag: 'database' }, 'select 1;\nselect 2;')
testContext.selectedText = 'select 2;'
@@ -481,14 +495,14 @@ describe('QueryTab execution', () => {
await waitFor(() => expect(runButton).toBeEnabled())
await userEvent.click(screen.getByRole('button', { name: 'More actions' }))
- await userEvent.click(await screen.findByRole('menuitem', { name: 'Run selected' }))
+ await userEvent.click(await screen.findByRole('menuitem', { name: 'Run selected SQL' }))
await waitFor(() => expect(executedQueries).toHaveLength(1))
expect(executedQueries[0]).toContain('select 2')
expect(executedQueries[0]).not.toContain('select 1')
})
- it('drops the stale "Run selected" state once the query panel is hidden and shown again', async () => {
+ it('drops the stale "Run selected SQL" state once the query panel is hidden and shown again', async () => {
createDraft({ _tag: 'database' }, 'select 1;\nselect 2;')
testContext.selectedText = 'select 2;'
@@ -507,7 +521,7 @@ describe('QueryTab execution', () => {
renderQueryTab()
await userEvent.click(await screen.findByRole('button', { name: 'More actions' }))
- expect(await screen.findByRole('menuitem', { name: 'Run selected' })).toBeEnabled()
+ expect(await screen.findByRole('menuitem', { name: 'Run selected SQL' })).toBeEnabled()
await userEvent.keyboard('{Escape}')
// Hiding the query panel unmounts CodeEditor entirely. Simulate the selection being
@@ -522,7 +536,7 @@ describe('QueryTab execution', () => {
await userEvent.click(showQueryButton as HTMLButtonElement)
await userEvent.click(screen.getByRole('button', { name: 'More actions' }))
- expect(await screen.findByRole('menuitem', { name: 'Run selected' })).toHaveAttribute(
+ expect(await screen.findByRole('menuitem', { name: 'Run selected SQL' })).toHaveAttribute(
'aria-disabled',
'true'
)
diff --git a/apps/studio/components/ui/AIAssistantPanel/AssistantQueryCell.tsx b/apps/studio/components/ui/AIAssistantPanel/AssistantQueryCell.tsx
index b8d3f4d30c0..9f4cbb9e7b0 100644
--- a/apps/studio/components/ui/AIAssistantPanel/AssistantQueryCell.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/AssistantQueryCell.tsx
@@ -143,13 +143,14 @@ export const AssistantQueryCell = ({
})
}
- const isConfirming = confirmState !== undefined
+ const isRunDisabled =
+ confirmState === 'approval-requested' || confirmState === 'approval-responded'
const outcomeMessages = QUERY_OUTCOME_MESSAGES[source._tag]
return (
<Confirm
fill
- className="h-96 w-full max-w-6xl mx-auto"
+ className="w-full max-w-6xl mx-auto"
state={confirmState}
message="Assistant wants to run this query"
cancelLabel="Skip"
@@ -165,6 +166,7 @@ export const AssistantQueryCell = ({
isReadOnly
id={id}
variant="viewport"
+ className="h-96"
title={title}
query={query}
result={result}
@@ -172,7 +174,7 @@ export const AssistantQueryCell = ({
onShowQueryChange={setShowQuery}
roleImpersonationState={roleImpersonationState}
display={display}
- isRunDisabled={isConfirming}
+ isRunDisabled={isRunDisabled}
onTitleChange={handleTitleChange}
onSqlChange={(sql) => setQuery((current) => setAssistantQuerySql(current, sql))}
onSourceChange={handleSourceChange}