The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
chore(studio): refocus editor after Run button tap (#43476)
Danny Whiteed46a5ab3f65
diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsxindex e403547c221..718463124b4 100644--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx@@ -118,6 +118,7 @@ export const SQLEditor = () => {const monacoRef = useRef<Monaco | null>(null)const diffEditorRef = useRef<IStandaloneDiffEditor | null>(null)const scrollTopRef = useRef<number>(0)+ const shouldRefocusAfterRunRef = useRef(false)const [hasSelection, setHasSelection] = useState<boolean>(false)const [lineHighlights, setLineHighlights] = useState<string[]>([])@@ -128,6 +129,23 @@ export const SQLEditor = () => {const [showWidget, setShowWidget] = useState(false)const [activeUtilityTab, setActiveUtilityTab] = useState<string>('results')+ const refocusEditor = useCallback(() => {+ requestAnimationFrame(() => {+ setTimeout(() => editorRef.current?.focus(), 0)+ })+ }, [])++ const clearPendingRunRefocus = useCallback(() => {+ shouldRefocusAfterRunRef.current = false+ }, [])++ const refocusEditorAfterRunIfNeeded = useCallback(() => {+ if (!shouldRefocusAfterRunRef.current) return++ shouldRefocusAfterRunRef.current = false+ refocusEditor()+ }, [refocusEditor])+// generate a new snippet title and an id to be used for new snippets. The dependency on urlId is to avoid a bug which// shows up when clicking on the SQL Editor while being in the SQL editor on a random snippet.const [generatedNewSnippetName, generatedId] = useMemo(() => {@@ -173,6 +191,7 @@ export const SQLEditor = () => {// revalidate lint queryqueryClient.invalidateQueries({ queryKey: lintKeys.lint(ref) })+ refocusEditorAfterRunIfNeeded()},onError(error: any, vars) {if (id) {@@ -209,6 +228,8 @@ export const SQLEditor = () => {snapV2.addResultError(id, error, vars.autoLimit)}++ refocusEditorAfterRunIfNeeded()},})@@ -273,87 +294,95 @@ export const SQLEditor = () => {const executeQuery = useCallback(async (force: boolean = false) => {- if (isDiffOpen) return+ if (isDiffOpen) {+ clearPendingRunRefocus()+ return+ }// use the latest stateconst state = getSqlEditorV2StateSnapshot()const snippet = state.snippets[id]- if (editorRef.current !== null && !isExecuting && project !== undefined) {- const editor = editorRef.current- const selection = editor.getSelection()- const selectedValue = selection ? editor.getModel()?.getValueInRange(selection) : undefined-- const sql = snippet- ? (selectedValue || editorRef.current?.getValue()) ?? snippet.snippet.content?.sql- : selectedValue || editorRef.current?.getValue()+ if (editorRef.current === null || isExecuting || project === undefined) {+ clearPendingRunRefocus()+ return+ }- let queryHasIssues = false+ const editor = editorRef.current+ const selection = editor.getSelection()+ const selectedValue = selection ? editor.getModel()?.getValueInRange(selection) : undefined- const destructiveOperations = checkDestructiveQuery(sql)- if (!force && destructiveOperations) {- setShowPotentialIssuesModal(true)- setQueryHasDestructiveOperations(true)- queryHasIssues = true- }+ const sql = snippet+ ? (selectedValue || editorRef.current?.getValue()) ?? snippet.snippet.content?.sql+ : selectedValue || editorRef.current?.getValue()- const updateWithoutWhereClause = isUpdateWithoutWhere(sql)- if (!force && updateWithoutWhereClause) {- setShowPotentialIssuesModal(true)- setQueryHasUpdateWithoutWhere(true)- queryHasIssues = true- }+ let queryHasIssues = false- if (queryHasIssues) {- return- }+ const destructiveOperations = checkDestructiveQuery(sql)+ if (!force && destructiveOperations) {+ setShowPotentialIssuesModal(true)+ setQueryHasDestructiveOperations(true)+ queryHasIssues = true+ }- if (- !isHipaaProjectDisallowed &&- snippet?.snippet.name.startsWith(untitledSnippetTitle) &&- IS_PLATFORM- ) {- // Intentionally don't await title gen (lazy)- setAiTitle(id, sql)- }+ const updateWithoutWhereClause = isUpdateWithoutWhere(sql)+ if (!force && updateWithoutWhereClause) {+ setShowPotentialIssuesModal(true)+ setQueryHasUpdateWithoutWhere(true)+ queryHasIssues = true+ }- if (lineHighlights.length > 0) {- editor?.deltaDecorations(lineHighlights, [])- setLineHighlights([])- }+ if (queryHasIssues) {+ return+ }- const impersonatedRoleState = getImpersonatedRoleState()- const connectionString = databases?.find(- (db) => db.identifier === databaseSelectorState.selectedDatabaseId- )?.connectionString- if (!isValidConnString(connectionString)) {- return toast.error('Unable to run query: Connection string is missing')- }+ if (+ !isHipaaProjectDisallowed &&+ snippet?.snippet.name.startsWith(untitledSnippetTitle) &&+ IS_PLATFORM+ ) {+ // Intentionally don't await title gen (lazy)+ setAiTitle(id, sql)+ }- const { appendAutoLimit } = checkIfAppendLimitRequired(sql, limit)- const formattedSql = suffixWithLimit(sql, limit)-- execute({- projectRef: project.ref,- connectionString: connectionString,- sql: wrapWithRoleImpersonation(formattedSql, impersonatedRoleState),- autoLimit: appendAutoLimit ? limit : undefined,- isRoleImpersonationEnabled: isRoleImpersonationEnabled(impersonatedRoleState.role),- isStatementTimeoutDisabled: true,- contextualInvalidation: true,- handleError: (error) => {- throw error- },- })+ if (lineHighlights.length > 0) {+ editor?.deltaDecorations(lineHighlights, [])+ setLineHighlights([])+ }- sendEvent({- action: 'sql_editor_query_run_button_clicked',- groups: { project: ref ?? 'Unknown', organization: org?.slug ?? 'Unknown' },- })+ const impersonatedRoleState = getImpersonatedRoleState()+ const connectionString = databases?.find(+ (db) => db.identifier === databaseSelectorState.selectedDatabaseId+ )?.connectionString+ if (!isValidConnString(connectionString)) {+ clearPendingRunRefocus()+ return toast.error('Unable to run query: Connection string is missing')}++ const { appendAutoLimit } = checkIfAppendLimitRequired(sql, limit)+ const formattedSql = suffixWithLimit(sql, limit)++ execute({+ projectRef: project.ref,+ connectionString: connectionString,+ sql: wrapWithRoleImpersonation(formattedSql, impersonatedRoleState),+ autoLimit: appendAutoLimit ? limit : undefined,+ isRoleImpersonationEnabled: isRoleImpersonationEnabled(impersonatedRoleState.role),+ isStatementTimeoutDisabled: true,+ contextualInvalidation: true,+ handleError: (error) => {+ throw error+ },+ })++ sendEvent({+ action: 'sql_editor_query_run_button_clicked',+ groups: { project: ref ?? 'Unknown', organization: org?.slug ?? 'Unknown' },+ })},// eslint-disable-next-line react-hooks/exhaustive-deps[+ clearPendingRunRefocus,isDiffOpen,id,isExecuting,@@ -368,6 +397,12 @@ export const SQLEditor = () => {])+ const executeQueryFromButton = useCallback(() => {+ shouldRefocusAfterRunRef.current = true+ refocusEditor()+ void executeQuery()+ }, [executeQuery, refocusEditor])+const executeExplainQuery = useCallback(async () => {if (isDiffOpen) return@@ -770,14 +805,19 @@ export const SQLEditor = () => {hasDestructiveOperations={queryHasDestructiveOperations}hasUpdateWithoutWhere={queryHasUpdateWithoutWhere}onCancel={() => {+ clearPendingRunRefocus()setShowPotentialIssuesModal(false)setQueryHasDestructiveOperations(false)setQueryHasUpdateWithoutWhere(false)- setTimeout(() => editorRef.current?.focus(), 100)+ refocusEditor()}}onConfirm={() => {+ shouldRefocusAfterRunRef.current = truesetShowPotentialIssuesModal(false)- executeQuery(true)+ setQueryHasDestructiveOperations(false)+ setQueryHasUpdateWithoutWhere(false)+ refocusEditor()+ void executeQuery(true)}}/>@@ -911,7 +951,7 @@ export const SQLEditor = () => {isDisabled={isDiffOpen}hasSelection={hasSelection}prettifyQuery={prettifyQuery}- executeQuery={executeQuery}+ executeQuery={executeQueryFromButton}executeExplainQuery={executeExplainQuery}onDebug={onDebug}buildDebugPrompt={buildDebugPrompt}diff --git a/apps/studio/components/ui/EditorPanel/EditorPanel.tsx b/apps/studio/components/ui/EditorPanel/EditorPanel.tsxindex a9a4ce4548a..28b6651c45e 100644--- a/apps/studio/components/ui/EditorPanel/EditorPanel.tsx+++ b/apps/studio/components/ui/EditorPanel/EditorPanel.tsx@@ -32,6 +32,7 @@ import {PlusIcon,X,} from 'lucide-react'+import type { editor as MonacoEditor } from 'monaco-editor'import { useRouter } from 'next/router'import { useEffect, useRef, useState } from 'react'import { editorPanelState, useEditorPanelStateSnapshot } from 'state/editor-panel-state'@@ -89,6 +90,8 @@ export const EditorPanel = () => {const [isEditingTitle, setIsEditingTitle] = useState(false)const [titleInput, setTitleInput] = useState('')const titleInputRef = useRef<HTMLInputElement>(null)+ const editorRef = useRef<MonacoEditor.IStandaloneCodeEditor | null>(null)+ const shouldRefocusAfterRunRef = useRef(false)const [monaco, setMonaco] = useState<Monaco | null>(null)useAddDefinitions('', monaco)@@ -127,6 +130,23 @@ export const EditorPanel = () => {const saveStatusTimerRef = useRef<ReturnType<typeof setTimeout>>()const originalSnippetRef = useRef<{ sql: string; name: string } | null>(null)+ const refocusEditor = () => {+ requestAnimationFrame(() => {+ setTimeout(() => editorRef.current?.focus(), 0)+ })+ }++ const clearPendingRunRefocus = () => {+ shouldRefocusAfterRunRef.current = false+ }++ const refocusEditorAfterRunIfNeeded = () => {+ if (!shouldRefocusAfterRunRef.current) return++ shouldRefocusAfterRunRef.current = false+ refocusEditor()+ }+const showSaveSuccess = () => {setSaveStatus('success')clearTimeout(saveStatusTimerRef.current)@@ -184,10 +204,12 @@ export const EditorPanel = () => {onSuccess: async (res) => {setResults(res.result)setError(undefined)+ refocusEditorAfterRunIfNeeded()},onError: (mutationError) => {setError(mutationError)setResults([])+ refocusEditorAfterRunIfNeeded()},})@@ -196,7 +218,10 @@ export const EditorPanel = () => {setShowWarning(undefined)setResults(undefined)- if (currentValue.length === 0) return+ if (currentValue.length === 0) {+ clearPendingRunRefocus()+ return+ }if (!skipValidation) {const isReadOnlySelectSQL = isReadOnlySelect(currentValue)@@ -232,7 +257,14 @@ export const EditorPanel = () => {setIsTemplatesOpen(false)}+ const onExecuteSqlFromButton = () => {+ shouldRefocusAfterRunRef.current = true+ onExecuteSql()+ refocusEditor()+ }+const handleClosePanel = () => {+ clearPendingRunRefocus()closeSidebar(SIDEBAR_KEYS.EDITOR_PANEL)setTemplates([])setError(undefined)@@ -458,7 +490,10 @@ export const EditorPanel = () => {language="pgsql"value={currentValue}onChange={handleChange}- onMount={(_, m) => setMonaco(m)}+ onMount={(editor, m) => {+ editorRef.current = editor+ setMonaco(m)+ }}aiEndpoint={`${BASE_PATH}/api/ai/code/complete`}aiMetadata={{projectRef: project?.ref,@@ -510,10 +545,16 @@ export const EditorPanel = () => {<SqlWarningAdmonitionclassName="border-t"warningType={showWarning}- onCancel={() => setShowWarning(undefined)}+ onCancel={() => {+ clearPendingRunRefocus()+ setShowWarning(undefined)+ refocusEditor()+ }}onConfirm={() => {+ shouldRefocusAfterRunRef.current = truesetShowWarning(undefined)onExecuteSql(true)+ refocusEditor()}}/>)}@@ -615,7 +656,11 @@ export const EditorPanel = () => {>{activeSnippet ? 'Update snippet' : 'Save as snippet'}</Button>- <SqlRunButton isDisabled={isExecuting} isExecuting={isExecuting} onClick={onExecuteSql} />+ <SqlRunButton+ isDisabled={isExecuting}+ isExecuting={isExecuting}+ onClick={onExecuteSqlFromButton}+ /></div></div><SaveSnippetDialog