Skip to content

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

Decouple editor panel (#37707)

Saxon Fletchera224598f1ec8
diff --git a/apps/studio/components/interfaces/Reports/ReportPadding.tsx b/apps/studio/components/interfaces/Reports/ReportPadding.tsx
index 37e30aaff1c..1c74cd7b321 100644
--- a/apps/studio/components/interfaces/Reports/ReportPadding.tsx
+++ b/apps/studio/components/interfaces/Reports/ReportPadding.tsx
@@ -1,7 +1,6 @@
import { PropsWithChildren } from 'react'
import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'
-import { useAppStateSnapshot } from 'state/app-state'
import { cn } from 'ui'
/**
@@ -9,13 +8,12 @@ import { cn } from 'ui'
*/
const ReportPadding = ({ children }: PropsWithChildren<{}>) => {
const snap = useAiAssistantStateSnapshot()
- const { editorPanel } = useAppStateSnapshot()
return (
<div
className={cn(
'flex flex-col gap-4 px-5 py-6 mx-auto 1xl:px-28 lg:px-16 2xl:px-32 w-full',
- snap.open || editorPanel.open ? 'xl:px-6' : 'xl:px-22'
+ snap.open ? 'xl:px-6' : 'xl:px-22'
)}
>
{children}
diff --git a/apps/studio/components/layouts/AppLayout/AssistantButton.tsx b/apps/studio/components/layouts/AppLayout/AssistantButton.tsx
index 8b9b80ffef2..93254be01c4 100644
--- a/apps/studio/components/layouts/AppLayout/AssistantButton.tsx
+++ b/apps/studio/components/layouts/AppLayout/AssistantButton.tsx
@@ -1,12 +1,10 @@
import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'
-import { useAppStateSnapshot } from 'state/app-state'
import { AiIconAnimation } from 'ui'
import { KeyboardShortcut } from 'ui'
export const AssistantButton = () => {
const snap = useAiAssistantStateSnapshot()
- const { setEditorPanel } = useAppStateSnapshot()
return (
<ButtonTooltip
@@ -16,7 +14,6 @@ export const AssistantButton = () => {
className="rounded-none w-[32px] h-[30px] flex items-center justify-center p-0 hover:bg-brand-400"
onClick={() => {
snap.toggleAssistant()
- setEditorPanel({ open: false })
}}
tooltip={{
content: {
diff --git a/apps/studio/components/layouts/AppLayout/InlineEditorButton.tsx b/apps/studio/components/layouts/AppLayout/InlineEditorButton.tsx
index a88a80a5bdb..d447221b08b 100644
--- a/apps/studio/components/layouts/AppLayout/InlineEditorButton.tsx
+++ b/apps/studio/components/layouts/AppLayout/InlineEditorButton.tsx
@@ -1,23 +1,15 @@
-import { SqlEditor } from 'icons'
-import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'
-import { useAppStateSnapshot } from 'state/app-state'
import { ButtonTooltip } from 'components/ui/ButtonTooltip'
+import { SqlEditor } from 'icons'
import { KeyboardShortcut } from 'ui'
-export const InlineEditorButton = () => {
- const { closeAssistant } = useAiAssistantStateSnapshot()
- const { setEditorPanel, editorPanel } = useAppStateSnapshot()
-
+export const InlineEditorButton = ({ onClick }: { onClick: () => void }) => {
return (
<ButtonTooltip
type="text"
size="tiny"
id="editor-trigger"
className="rounded-none w-[32px] h-[30px] flex items-center justify-center p-0 text-foreground-light hover:text-foreground"
- onClick={() => {
- closeAssistant()
- setEditorPanel({ open: !editorPanel.open })
- }}
+ onClick={onClick}
tooltip={{
content: {
text: (
diff --git a/apps/studio/components/layouts/ProjectLayout/LayoutHeader/LayoutHeader.tsx b/apps/studio/components/layouts/ProjectLayout/LayoutHeader/LayoutHeader.tsx
index 17ca647da39..b0d99ecc117 100644
--- a/apps/studio/components/layouts/ProjectLayout/LayoutHeader/LayoutHeader.tsx
+++ b/apps/studio/components/layouts/ProjectLayout/LayoutHeader/LayoutHeader.tsx
@@ -1,6 +1,6 @@
import { AnimatePresence, motion } from 'framer-motion'
import Link from 'next/link'
-import { ReactNode, useMemo } from 'react'
+import { ReactNode, useMemo, useState } from 'react'
import { useParams } from 'common'
import { useIsBranching2Enabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'
@@ -12,10 +12,12 @@ import { BranchDropdown } from 'components/layouts/AppLayout/BranchDropdown'
import { InlineEditorButton } from 'components/layouts/AppLayout/InlineEditorButton'
import { OrganizationDropdown } from 'components/layouts/AppLayout/OrganizationDropdown'
import { ProjectDropdown } from 'components/layouts/AppLayout/ProjectDropdown'
+import EditorPanel from 'components/ui/EditorPanel/EditorPanel'
import { getResourcesExceededLimitsOrg } from 'components/ui/OveragesBanner/OveragesBanner.utils'
import { useOrgUsageQuery } from 'data/usage/org-usage-query'
import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
+import { useHotKey } from 'hooks/ui/useHotKey'
import { IS_PLATFORM } from 'lib/constants'
import { useAppStateSnapshot } from 'state/app-state'
import { Badge, cn } from 'ui'
@@ -64,6 +66,15 @@ const LayoutHeader = ({
const { setMobileMenuOpen } = useAppStateSnapshot()
const gitlessBranching = useIsBranching2Enabled()
+ const [showEditorPanel, setShowEditorPanel] = useState(false)
+ useHotKey(
+ () => {
+ if (projectRef) setShowEditorPanel(!showEditorPanel)
+ },
+ 'e',
+ [showEditorPanel, projectRef]
+ )
+
// We only want to query the org usage and check for possible over-ages for plans without usage billing enabled (free or pro with spend cap)
const { data: orgUsage } = useOrgUsageQuery(
{ orgSlug: selectedOrganization?.slug },
@@ -82,74 +93,94 @@ const LayoutHeader = ({
const showOrgSelection = slug || (selectedOrganization && projectRef)
return (
- <header className={cn('flex h-12 items-center flex-shrink-0 border-b')}>
- {showProductMenu && (
- <div className="flex items-center justify-center border-r flex-0 md:hidden h-full aspect-square">
- <button
- title="Menu dropdown button"
- className={cn(
- 'group/view-toggle ml-4 flex justify-center flex-col border-none space-x-0 items-start gap-1 !bg-transparent rounded-md min-w-[30px] w-[30px] h-[30px]'
- )}
- onClick={() => setMobileMenuOpen(true)}
- >
- <div className="h-px inline-block left-0 w-4 transition-all ease-out bg-foreground-lighter group-hover/view-toggle:bg-foreground p-0 m-0" />
- <div className="h-px inline-block left-0 w-3 transition-all ease-out bg-foreground-lighter group-hover/view-toggle:bg-foreground p-0 m-0" />
- </button>
- </div>
- )}
- <div
- className={cn(
- 'flex items-center justify-between h-full pr-3 flex-1 overflow-x-auto gap-x-8 pl-4'
+ <>
+ <header className={cn('flex h-12 items-center flex-shrink-0 border-b')}>
+ {showProductMenu && (
+ <div className="flex items-center justify-center border-r flex-0 md:hidden h-full aspect-square">
+ <button
+ title="Menu dropdown button"
+ className={cn(
+ 'group/view-toggle ml-4 flex justify-center flex-col border-none space-x-0 items-start gap-1 !bg-transparent rounded-md min-w-[30px] w-[30px] h-[30px]'
+ )}
+ onClick={() => setMobileMenuOpen(true)}
+ >
+ <div className="h-px inline-block left-0 w-4 transition-all ease-out bg-foreground-lighter group-hover/view-toggle:bg-foreground p-0 m-0" />
+ <div className="h-px inline-block left-0 w-3 transition-all ease-out bg-foreground-lighter group-hover/view-toggle:bg-foreground p-0 m-0" />
+ </button>
+ </div>
)}
- >
- <div className="flex items-center text-sm">
- <HomeIcon />
- <div className="flex items-center md:pl-2">
- {showOrgSelection && IS_PLATFORM ? (
- <>
- <LayoutHeaderDivider className="hidden md:block" />
- <OrganizationDropdown />
- </>
- ) : null}
- <AnimatePresence>
- {projectRef && (
- <motion.div
- className="flex items-center"
- initial={{ opacity: 0, x: -20 }}
- animate={{ opacity: 1, x: 0 }}
- exit={{ opacity: 0, x: -20 }}
- transition={{
- duration: 0.15,
- ease: 'easeOut',
- }}
- >
- <LayoutHeaderDivider />
- <ProjectDropdown />
+ <div
+ className={cn(
+ 'flex items-center justify-between h-full pr-3 flex-1 overflow-x-auto gap-x-8 pl-4'
+ )}
+ >
+ <div className="flex items-center text-sm">
+ <HomeIcon />
+ <div className="flex items-center md:pl-2">
+ {showOrgSelection && IS_PLATFORM ? (
+ <>
+ <LayoutHeaderDivider className="hidden md:block" />
+ <OrganizationDropdown />
+ </>
+ ) : null}
+ <AnimatePresence>
+ {projectRef && (
+ <motion.div
+ className="flex items-center"
+ initial={{ opacity: 0, x: -20 }}
+ animate={{ opacity: 1, x: 0 }}
+ exit={{ opacity: 0, x: -20 }}
+ transition={{
+ duration: 0.15,
+ ease: 'easeOut',
+ }}
+ >
+ <LayoutHeaderDivider />
+ <ProjectDropdown />
- {exceedingLimits && (
- <div className="ml-2">
- <Link href={`/org/${selectedOrganization?.slug}/usage`}>
- <Badge variant="destructive" className="whitespace-nowrap">
- Exceeding usage limits
- </Badge>
- </Link>
- </div>
- )}
+ {exceedingLimits && (
+ <div className="ml-2">
+ <Link href={`/org/${selectedOrganization?.slug}/usage`}>
+ <Badge variant="destructive" className="whitespace-nowrap">
+ Exceeding usage limits
+ </Badge>
+ </Link>
+ </div>
+ )}
- {selectedProject && (
- <>
- <LayoutHeaderDivider />
- {IS_PLATFORM && <BranchDropdown />}
- </>
- )}
- </motion.div>
- )}
- </AnimatePresence>
+ {selectedProject && (
+ <>
+ <LayoutHeaderDivider />
+ {IS_PLATFORM && <BranchDropdown />}
+ </>
+ )}
+ </motion.div>
+ )}
+ </AnimatePresence>
+
+ <AnimatePresence>
+ {headerTitle && (
+ <motion.div
+ className="flex items-center"
+ initial={{ opacity: 0, x: -20 }}
+ animate={{ opacity: 1, x: 0 }}
+ exit={{ opacity: 0, x: -20 }}
+ transition={{
+ duration: 0.15,
+ ease: 'easeOut',
+ }}
+ >
+ <LayoutHeaderDivider />
+ <span className="text-foreground">{headerTitle}</span>
+ </motion.div>
+ )}
+ </AnimatePresence>
+ </div>
<AnimatePresence>
- {headerTitle && (
+ {projectRef && (
<motion.div
- className="flex items-center"
+ className="ml-3 items-center gap-x-2 flex"
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: -20 }}
@@ -158,71 +189,54 @@ const LayoutHeader = ({
ease: 'easeOut',
}}
>
- <LayoutHeaderDivider />
- <span className="text-foreground">{headerTitle}</span>
+ {IS_PLATFORM && gitlessBranching && <MergeRequestButton />}
+ <Connect />
</motion.div>
)}
</AnimatePresence>
+ <BreadcrumbsView defaultValue={breadcrumbs} />
</div>
+ <div className="flex items-center gap-x-2">
+ {customHeaderComponents && customHeaderComponents}
+ {IS_PLATFORM ? (
+ <>
+ <FeedbackDropdown />
- <AnimatePresence>
- {projectRef && (
- <motion.div
- className="ml-3 items-center gap-x-2 flex"
- initial={{ opacity: 0, x: -20 }}
- animate={{ opacity: 1, x: 0 }}
- exit={{ opacity: 0, x: -20 }}
- transition={{
- duration: 0.15,
- ease: 'easeOut',
- }}
- >
- {IS_PLATFORM && gitlessBranching && <MergeRequestButton />}
- <Connect />
- </motion.div>
+ <div className="overflow-hidden flex items-center rounded-full border">
+ <HelpPopover />
+ <NotificationsPopoverV2 />
+ <AnimatePresence initial={false}>
+ {!!projectRef && (
+ <>
+ <InlineEditorButton onClick={() => setShowEditorPanel(true)} />
+ <AssistantButton />
+ </>
+ )}
+ </AnimatePresence>
+ </div>
+ <UserDropdown />
+ </>
+ ) : (
+ <>
+ <LocalVersionPopover />
+ <div className="overflow-hidden flex items-center rounded-full border">
+ <AnimatePresence initial={false}>
+ {!!projectRef && (
+ <>
+ <InlineEditorButton onClick={() => setShowEditorPanel(true)} />
+ <AssistantButton />
+ </>
+ )}
+ </AnimatePresence>
+ </div>
+ <LocalDropdown />
+ </>
)}
- </AnimatePresence>
- <BreadcrumbsView defaultValue={breadcrumbs} />
- </div>
- <div className="flex items-center gap-x-2">
- {customHeaderComponents && customHeaderComponents}
- {IS_PLATFORM ? (
- <>
- <FeedbackDropdown />
-
- <div className="overflow-hidden flex items-center rounded-full border">
- <HelpPopover />
- <NotificationsPopoverV2 />
- <AnimatePresence initial={false}>
- {!!projectRef && (
- <>
- <InlineEditorButton />
- <AssistantButton />
- </>
- )}
- </AnimatePresence>
- </div>
- <UserDropdown />
- </>
- ) : (
- <>
- <LocalVersionPopover />
- <div className="overflow-hidden flex items-center rounded-full border">
- <AnimatePresence initial={false}>
- {!!projectRef && (
- <>
- <InlineEditorButton />
- <AssistantButton />
- </>
- )}
- </AnimatePresence>
- </div>
- <LocalDropdown />
- </>
- )}
+ </div>
</div>
- </div>
- </header>
+ </header>
+ <EditorPanel open={showEditorPanel} onClose={() => setShowEditorPanel(false)} />
+ </>
)
}
diff --git a/apps/studio/components/layouts/ProjectLayout/ProjectLayout.tsx b/apps/studio/components/layouts/ProjectLayout/ProjectLayout.tsx
index 831d3c0a021..fb9c5bcf9fa 100644
--- a/apps/studio/components/layouts/ProjectLayout/ProjectLayout.tsx
+++ b/apps/studio/components/layouts/ProjectLayout/ProjectLayout.tsx
@@ -7,12 +7,12 @@ import { useParams } from 'common'
import { CreateBranchModal } from 'components/interfaces/BranchManagement/CreateBranchModal'
import ProjectAPIDocs from 'components/interfaces/ProjectAPIDocs/ProjectAPIDocs'
import { AIAssistant } from 'components/ui/AIAssistantPanel/AIAssistant'
-import { EditorPanel } from 'components/ui/EditorPanel/EditorPanel'
import { Loading } from 'components/ui/Loading'
import { ResourceExhaustionWarningBanner } from 'components/ui/ResourceExhaustionWarningBanner/ResourceExhaustionWarningBanner'
import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
import { withAuth } from 'hooks/misc/withAuth'
+import { useHotKey } from 'hooks/ui/useHotKey'
import { PROJECT_STATUS } from 'lib/constants'
import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'
import { useAppStateSnapshot } from 'state/app-state'
@@ -91,16 +91,11 @@ const ProjectLayout = forwardRef<HTMLDivElement, PropsWithChildren<ProjectLayout
const { data: selectedOrganization } = useSelectedOrganizationQuery()
const { data: selectedProject } = useSelectedProjectQuery()
- const {
- editorPanel,
- mobileMenuOpen,
- showSidebar,
- setMobileMenuOpen,
- toggleEditorPanel,
- setEditorPanel,
- } = useAppStateSnapshot()
+ const { mobileMenuOpen, showSidebar, setMobileMenuOpen } = useAppStateSnapshot()
const aiSnap = useAiAssistantStateSnapshot()
+ useHotKey(() => aiSnap.toggleAssistant(), 'i', [aiSnap])
+
const editor = useEditorType()
const forceShowProductMenu = editor === undefined
const sideBarIsOpen = forceShowProductMenu || showSidebar
@@ -124,28 +119,6 @@ const ProjectLayout = forwardRef<HTMLDivElement, PropsWithChildren<ProjectLayout
setIsClient(true)
}, [])
- useEffect(() => {
- const handler = (e: KeyboardEvent) => {
- // Cmd+I: Open AI Assistant, close Editor Panel
- if (e.metaKey && e.key === 'i' && !e.altKey && !e.shiftKey) {
- setEditorPanel({ open: false })
- aiSnap.toggleAssistant()
- e.preventDefault()
- e.stopPropagation()
- }
- // Cmd+E: Toggle Editor Panel, always close AI Assistant
- if (e.metaKey && e.key === 'e' && !e.altKey && !e.shiftKey) {
- aiSnap.closeAssistant()
- toggleEditorPanel()
- e.preventDefault()
- e.stopPropagation()
- }
- }
- window.addEventListener('keydown', handler)
- return () => window.removeEventListener('keydown', handler)
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [setEditorPanel, aiSnap, editorPanel.open])
-
return (
<>
<Head>
@@ -238,7 +211,7 @@ const ProjectLayout = forwardRef<HTMLDivElement, PropsWithChildren<ProjectLayout
)}
</main>
</ResizablePanel>
- {isClient && (aiSnap.open || editorPanel.open) && (
+ {isClient && aiSnap.open && (
<>
<ResizableHandle withHandle />
<ResizablePanel
@@ -252,11 +225,7 @@ const ProjectLayout = forwardRef<HTMLDivElement, PropsWithChildren<ProjectLayout
'xl:relative xl:border-l-0'
)}
>
- {aiSnap.open ? (
- <AIAssistant className="w-full h-[100dvh] md:h-full max-h-[100dvh]" />
- ) : editorPanel.open ? (
- <EditorPanel />
- ) : null}
+ <AIAssistant className="w-full h-[100dvh] md:h-full max-h-[100dvh]" />
</ResizablePanel>
</>
)}
diff --git a/apps/studio/components/ui/AIEditor/index.tsx b/apps/studio/components/ui/AIEditor/index.tsx
index 6dc2a84ab3a..57ed87433a6 100644
--- a/apps/studio/components/ui/AIEditor/index.tsx
+++ b/apps/studio/components/ui/AIEditor/index.tsx
@@ -23,9 +23,11 @@ interface AIEditorProps {
}
initialPrompt?: string
readOnly?: boolean
+ autoFocus?: boolean
className?: string
options?: monacoEditor.IStandaloneEditorConstructionOptions
onChange?: (value: string) => void
+ onClose?: () => void
executeQuery?: () => void
}
@@ -41,9 +43,11 @@ const AIEditor = ({
aiMetadata,
initialPrompt,
readOnly = false,
+ autoFocus = false,
className = '',
options = {},
onChange,
+ onClose,
executeQuery,
}: AIEditorProps) => {
const os = detectOS()
@@ -149,6 +153,17 @@ const AIEditor = ({
})
}
+ if (!!onClose) {
+ editor.addAction({
+ id: 'close-editor',
+ label: 'Close editor',
+ keybindings: [monaco.KeyMod.CtrlCmd + monaco.KeyCode.KeyE],
+ contextMenuGroupId: 'operation',
+ contextMenuOrder: 0,
+ run: () => onClose(),
+ })
+ }
+
editor.addAction({
id: 'generate-ai',
label: 'Generate with AI',
@@ -176,6 +191,11 @@ const AIEditor = ({
})
},
})
+
+ if (autoFocus) {
+ if (editor.getValue().length === 1) editor.setPosition({ lineNumber: 1, column: 2 })
+ editor.focus()
+ }
}
const handlePrompt = async (
@@ -327,6 +347,7 @@ const AIEditor = ({
</div>
) : (
<div className="w-full h-full relative">
+ {/* [Joshen] Refactor: Use CodeEditor.tsx instead, reduce duplicate declaration of Editor */}
<Editor
theme="supabase"
language={language}
diff --git a/apps/studio/components/ui/DataTable/DataTableResetButton.tsx b/apps/studio/components/ui/DataTable/DataTableResetButton.tsx
index 3e373ff2ee5..efcdff50e9b 100644
--- a/apps/studio/components/ui/DataTable/DataTableResetButton.tsx
+++ b/apps/studio/components/ui/DataTable/DataTableResetButton.tsx
@@ -7,7 +7,7 @@ import { useDataTable } from './providers/DataTableProvider'
export function DataTableResetButton() {
const { table } = useDataTable()
- useHotKey(table.resetColumnFilters, 'Escape')
+ useHotKey(() => table.resetColumnFilters(), 'Escape')
return (
<Tooltip>
diff --git a/apps/studio/components/ui/EditorPanel/EditorPanel.tsx b/apps/studio/components/ui/EditorPanel/EditorPanel.tsx
index 62d593fbab3..ae19f3ca6db 100644
--- a/apps/studio/components/ui/EditorPanel/EditorPanel.tsx
+++ b/apps/studio/components/ui/EditorPanel/EditorPanel.tsx
@@ -1,6 +1,6 @@
-import { debounce } from 'lodash'
import { Book, Save, X } from 'lucide-react'
-import { useCallback, useEffect, useState } from 'react'
+import { useEffect, useState } from 'react'
+import { useForm } from 'react-hook-form'
import { toast } from 'sonner'
import { useParams } from 'common'
@@ -17,7 +17,6 @@ import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
import { BASE_PATH } from 'lib/constants'
import { uuidv4 } from 'lib/helpers'
import { useProfile } from 'lib/profile'
-import { useAppStateSnapshot } from 'state/app-state'
import { useSqlEditorV2StateSnapshot } from 'state/sql-editor-v2'
import {
Button,
@@ -29,12 +28,21 @@ import {
CommandInput_Shadcn_,
CommandItem_Shadcn_,
CommandList_Shadcn_,
+ Form_Shadcn_,
+ FormField_Shadcn_,
HoverCard_Shadcn_,
HoverCardContent_Shadcn_,
HoverCardTrigger_Shadcn_,
+ Input_Shadcn_ as Input,
+ KeyboardShortcut,
Popover_Shadcn_,
PopoverContent_Shadcn_,
PopoverTrigger_Shadcn_,
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetHeader,
+ SheetTitle,
SQL_ICON,
} from 'ui'
import { Admonition } from 'ui-patterns'
@@ -44,14 +52,44 @@ import { ButtonTooltip } from '../ButtonTooltip'
import { InlineLink } from '../InlineLink'
import SqlWarningAdmonition from '../SqlWarningAdmonition'
+type Template = {
+ name: string
+ description: string
+ content: string
+}
+
interface EditorPanelProps {
+ open: boolean
+ onClose: () => void
+ initialValue?: string
+ label?: string
+ saveLabel?: string
+ saveValue?: string
+ onSave?: (value: string, saveValue: string) => void
+ onRunSuccess?: (value: any[]) => void
+ onRunError?: (value: any) => void
+ functionName?: string
+ templates?: Template[]
+ initialPrompt?: string
onChange?: (value: string) => void
}
-export const EditorPanel = ({ onChange }: EditorPanelProps) => {
+export const EditorPanel = ({
+ open,
+ onClose,
+ initialValue = '',
+ label = '',
+ saveLabel = 'Save',
+ saveValue = '',
+ onSave,
+ onRunSuccess,
+ onRunError,
+ templates = [],
+ initialPrompt = '',
+ onChange,
+}: EditorPanelProps) => {
const { ref } = useParams()
const { data: project } = useSelectedProjectQuery()
- const { editorPanel, setEditorPanel } = useAppStateSnapshot()
const { profile } = useProfile()
const snapV2 = useSqlEditorV2StateSnapshot()
const { mutateAsync: generateSqlTitle } = useSqlTitleGenerateMutation()
@@ -61,26 +99,38 @@ export const EditorPanel = ({ onChange }: EditorPanelProps) => {
const [error, setError] = useState<QueryResponseError>()
const [results, setResults] = useState<undefined | any[]>(undefined)
const [showWarning, setShowWarning] = useState<'hasWriteOperation' | 'hasUnknownFunctions'>()
- const [currentValue, setCurrentValue] = useState(editorPanel.initialValue || '')
- const [savedCode, setSavedCode] = useState<string>('')
- const [isPreviewingTemplate, setIsPreviewingTemplate] = useState(false)
+ const [currentValue, setCurrentValue] = useState(initialValue)
const [showResults, setShowResults] = useState(true)
const [isTemplatesOpen, setIsTemplatesOpen] = useState(false)
+ const saveForm = useForm({
+ defaultValues: {
+ saveValue: saveValue || '',
+ },
+ })
+
const errorHeader = error?.formattedError?.split('\n')?.filter((x: string) => x.length > 0)?.[0]
const errorContent =
- error?.formattedError
- ?.split('\n')
- ?.filter((x: string) => x.length > 0)
- ?.slice(1) ?? []
+ 'formattedError' in (error || {})
+ ? error?.formattedError
+ ?.split('\n')
+ ?.filter((x: string) => x.length > 0)
+ ?.slice(1) ?? []
+ : [error?.message ?? '']
const { mutate: executeSql, isLoading: isExecuting } = useExecuteSqlMutation({
onSuccess: async (res) => {
setResults(res.result)
+ if (onRunSuccess) {
+ onRunSuccess(res.result)
+ }
},
onError: (error) => {
setError(error)
setResults([])
+ if (onRunError) {
+ onRunError(error)
+ }
},
})
@@ -98,11 +148,6 @@ export const EditorPanel = ({ onChange }: EditorPanelProps) => {
return
}
}
-
- if (editorPanel.onSave) {
- editorPanel.onSave(currentValue)
- }
-
executeSql({
sql: suffixWithLimit(currentValue, 100),
projectRef: project?.ref,
@@ -124,250 +169,285 @@ export const EditorPanel = ({ onChange }: EditorPanelProps) => {
setIsTemplatesOpen(false)
}
- // Create a debounced version of the revert code function
- const debouncedRevertCode = useCallback(
- debounce(() => {
- setIsPreviewingTemplate(false)
- handleChange(savedCode)
- }, 300),
- [savedCode]
- )
-
- // Cleanup debounce on unmount
- useEffect(() => {
- return () => {
- debouncedRevertCode.cancel()
- }
- }, [debouncedRevertCode])
-
useEffect(() => {
- if (editorPanel.initialValue !== undefined && editorPanel.initialValue !== currentValue) {
- setCurrentValue(editorPanel.initialValue)
+ if (initialValue !== undefined && initialValue !== currentValue) {
+ setCurrentValue(initialValue)
+ setResults(undefined)
+ setError(undefined)
+ setShowWarning(undefined)
}
- }, [editorPanel.initialValue])
+ }, [initialValue])
useEffect(() => {
- if (editorPanel.initialValue !== currentValue) {
- setEditorPanel({
- initialValue: currentValue,
- })
- }
- }, [currentValue, setEditorPanel])
+ saveForm.reset({
+ saveValue: saveValue || '',
+ })
+ }, [saveValue, saveForm])
return (
- <div className="flex flex-col h-full bg-surface-100">
- <div className="border-b flex shrink-0 items-center gap-x-3 px-4 h-[46px]">
- <span className="text-sm flex-1">SQL Editor</span>
- <div className="flex gap-2 items-center">
- <Popover_Shadcn_ open={isTemplatesOpen} onOpenChange={setIsTemplatesOpen}>
- <PopoverTrigger_Shadcn_ asChild>
- <Button
- size="tiny"
- type="default"
- role="combobox"
- aria-expanded={isTemplatesOpen}
- icon={<Book size={14} />}
- >
- Templates
- </Button>
- </PopoverTrigger_Shadcn_>
- <PopoverContent_Shadcn_ align="end" className="w-[300px] p-0">
- <Command_Shadcn_>
- <CommandInput_Shadcn_ placeholder="Search templates..." />
- <CommandList_Shadcn_>
- <CommandEmpty_Shadcn_>No templates found.</CommandEmpty_Shadcn_>
- <CommandGroup_Shadcn_>
- {editorPanel.templates?.map((template) => (
- <HoverCard_Shadcn_ key={template.name}>
- <HoverCardTrigger_Shadcn_ asChild>
- <CommandItem_Shadcn_
- value={template.name}
- onSelect={() => onSelectTemplate(template.content)}
- className="cursor-pointer"
- >
- <div className="flex items-center gap-3">
- <SQL_ICON
- size={16}
- className={cn(
- 'w-5 h-5 flex-0 mr-2 transition-colors fill-foreground-muted'
- )}
+ <Sheet open={open} onOpenChange={(open) => !open && onClose()}>
+ <SheetContent
+ showClose={false}
+ className="w-full sm:max-w-3xl flex flex-col h-full p-0 space-y-0 gap-0"
+ >
+ <SheetHeader className="flex shrink-0 items-center gap-x-3">
+ <div className="flex-1">
+ <SheetTitle className="text-sm">SQL Editor</SheetTitle>
+ {label && <SheetDescription className="text-sm">{label}</SheetDescription>}
+ </div>
+ <div className="flex gap-2 items-center">
+ {templates.length > 0 && (
+ <Popover_Shadcn_ open={isTemplatesOpen} onOpenChange={setIsTemplatesOpen}>
+ <PopoverTrigger_Shadcn_ asChild>
+ <Button
+ size="tiny"
+ type="default"
+ role="combobox"
+ aria-expanded={isTemplatesOpen}
+ icon={<Book size={14} />}
+ >
+ Templates
+ </Button>
+ </PopoverTrigger_Shadcn_>
+ <PopoverContent_Shadcn_ align="end" className="w-[300px] p-0">
+ <Command_Shadcn_>
+ <CommandInput_Shadcn_ placeholder="Search templates..." />
+ <CommandList_Shadcn_>
+ <CommandEmpty_Shadcn_>No templates found.</CommandEmpty_Shadcn_>
+ <CommandGroup_Shadcn_>
+ {templates.map((template) => (
+ <HoverCard_Shadcn_ key={template.name}>
+ <HoverCardTrigger_Shadcn_ asChild>
+ <CommandItem_Shadcn_
+ value={template.name}
+ onSelect={() => onSelectTemplate(template.content)}
+ className="cursor-pointer"
+ >
+ <div className="flex items-center gap-3">
+ <SQL_ICON
+ size={16}
+ className={cn(
+ 'w-5 h-5 flex-0 mr-2 transition-colors fill-foreground-muted'
+ )}
+ />
+ <div className="flex-1">
+ <h4 className="text-foreground flex-1">{template.name}</h4>
+ <p className="text-xs text-foreground-light">
+ {template.description}
+ </p>
+ </div>
+ </div>
+ </CommandItem_Shadcn_>
+ </HoverCardTrigger_Shadcn_>
+ <HoverCardContent_Shadcn_ side="left" className="w-[500px] p-0">
+ <CodeBlock
+ language="sql"
+ className="language-sql border-none"
+ hideLineNumbers
+ value={template.content}
/>
- <div className="flex-1">
- <h4 className="text-foreground flex-1">{template.name}</h4>
- <p className="text-xs text-foreground-light">
- {template.description}
- </p>
- </div>
- </div>
- </CommandItem_Shadcn_>
- </HoverCardTrigger_Shadcn_>
- <HoverCardContent_Shadcn_ side="left" className="w-[500px] p-0">
- <CodeBlock
- language="sql"
- className="language-sql border-none"
- hideLineNumbers
- value={template.content}
- />
- </HoverCardContent_Shadcn_>
- </HoverCard_Shadcn_>
- ))}
- </CommandGroup_Shadcn_>
- </CommandList_Shadcn_>
- </Command_Shadcn_>
- </PopoverContent_Shadcn_>
- </Popover_Shadcn_>
- <ButtonTooltip
- tooltip={{
- content: {
- side: 'bottom',
- text: 'Save as snippet',
- },
- }}
- size="tiny"
- type="default"
- className="w-7 h-7"
- loading={isSaving}
- icon={<Save size={16} />}
- onClick={async () => {
- if (!ref) return console.error('Project ref is required')
- if (!project) return console.error('Project is required')
- if (!profile) return console.error('Profile is required')
-
- try {
- setIsSaving(true)
- const { title: name } = await generateSqlTitle({
- sql: currentValue,
- })
- const snippet = createSqlSnippetSkeletonV2({
- id: uuidv4(),
- name,
- sql: currentValue,
- owner_id: profile.id,
- project_id: project.id,
- })
- snapV2.addSnippet({ projectRef: ref, snippet })
- snapV2.addNeedsSaving(snippet.id)
- toast.success(
- <div>
- Saved snippet! View it{' '}
- <InlineLink href={`/project/${ref}/sql/${snippet.id}`}>here</InlineLink>
- </div>
- )
- } catch (error: any) {
- toast.error(`Failed to create new query: ${error.message}`)
- } finally {
- setIsSaving(false)
- }
- }}
- />
+ </HoverCardContent_Shadcn_>
+ </HoverCard_Shadcn_>
+ ))}
+ </CommandGroup_Shadcn_>
+ </CommandList_Shadcn_>
+ </Command_Shadcn_>
+ </PopoverContent_Shadcn_>
+ </Popover_Shadcn_>
+ )}
+ <ButtonTooltip
+ tooltip={{
+ content: {
+ side: 'bottom',
+ text: 'Save as snippet',
+ },
+ }}
+ size="tiny"
+ type="default"
+ className="w-7 h-7"
+ loading={isSaving}
+ icon={<Save size={16} />}
+ onClick={async () => {
+ if (!ref) return console.error('Project ref is required')
+ if (!project) return console.error('Project is required')
+ if (!profile) return console.error('Profile is required')
- <Button
- size="tiny"
- type="default"
- className="w-7 h-7"
- onClick={() => setEditorPanel({ open: false })}
- icon={<X size={16} />}
- />
- </div>
- </div>
+ try {
+ setIsSaving(true)
+ const { title: name } = await generateSqlTitle({
+ sql: currentValue,
+ })
+ const snippet = createSqlSnippetSkeletonV2({
+ id: uuidv4(),
+ name,
+ sql: currentValue,
+ owner_id: profile.id,
+ project_id: project.id,
+ })
+ snapV2.addSnippet({ projectRef: ref, snippet })
+ snapV2.addNeedsSaving(snippet.id)
+ toast.success(
+ <div>
+ Saved snippet! View it{' '}
+ <InlineLink href={`/project/${ref}/sql/${snippet.id}`}>here</InlineLink>
+ </div>
+ )
+ } catch (error: any) {
+ toast.error(`Failed to create new query: ${error.message}`)
+ } finally {
+ setIsSaving(false)
+ }
+ }}
+ />
- <div className="flex-1 overflow-hidden flex flex-col h-full">
- <div className="flex-1 min-h-0 relative">
- <AIEditor
- language="pgsql"
- value={currentValue}
- onChange={handleChange}
- aiEndpoint={`${BASE_PATH}/api/ai/sql/complete-v2`}
- aiMetadata={{
- projectRef: project?.ref,
- connectionString: project?.connectionString,
- includeSchemaMetadata,
- }}
- initialPrompt={editorPanel.initialPrompt}
- options={{
- tabSize: 2,
- fontSize: 13,
- minimap: { enabled: false },
- wordWrap: 'on',
- lineNumbers: 'on',
- folding: false,
- padding: { top: 4 },
- lineNumbersMinChars: 3,
- }}
- executeQuery={onExecuteSql}
- />
- </div>
+ <ButtonTooltip
+ size="tiny"
+ type="default"
+ className="w-7 h-7"
+ onClick={onClose}
+ icon={<X size={16} />}
+ tooltip={{
+ content: {
+ side: 'bottom',
+ text: (
+ <div className="flex items-center gap-4">
+ <span>Close Editor</span>
+ <KeyboardShortcut keys={['Meta', 'e']} />
+ </div>
+ ),
+ },
+ }}
+ />
+ </div>
+ </SheetHeader>
- {error !== undefined && (
- <div className="shrink-0">
- <Admonition
- type="warning"
- className="m-0 rounded-none border-x-0 border-b-0 [&>div>div>pre]:text-sm [&>div]:flex [&>div]:flex-col [&>div]:gap-y-2"
- title={errorHeader || 'Error running SQL query'}
- description={
- <div>
- {errorContent.length > 0 ? (
- errorContent.map((errorText: string, i: number) => (
- <pre key={`err-${i}`} className="font-mono text-xs whitespace-pre-wrap">
- {errorText}
- </pre>
- ))
- ) : (
- <p className="font-mono text-xs">{error.error}</p>
- )}
- </div>
- }
+ <div className="flex-1 overflow-hidden flex flex-col h-full">
+ <div className="flex-1 min-h-0 relative">
+ <AIEditor
+ autoFocus
+ language="pgsql"
+ value={currentValue}
+ onChange={handleChange}
+ aiEndpoint={`${BASE_PATH}/api/ai/sql/complete-v2`}
+ aiMetadata={{
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ includeSchemaMetadata,
+ }}
+ initialPrompt={initialPrompt}
+ options={{
+ tabSize: 2,
+ fontSize: 13,
+ minimap: { enabled: false },
+ wordWrap: 'on',
+ lineNumbers: 'on',
+ folding: false,
+ padding: { top: 16 },
+ lineNumbersMinChars: 3,
+ }}
+ executeQuery={onExecuteSql}
+ onClose={() => onClose()}
/>
</div>
- )}
- {showWarning && (
- <SqlWarningAdmonition
- className="border-t"
- warningType={showWarning}
- onCancel={() => setShowWarning(undefined)}
- onConfirm={() => {
- setShowWarning(undefined)
- onExecuteSql(true)
- }}
- />
- )}
+ {error !== undefined && (
+ <div className="shrink-0">
+ <Admonition
+ type="warning"
+ className="m-0 rounded-none border-x-0 border-b-0 [&>div>div>pre]:text-sm [&>div]:flex [&>div]:flex-col [&>div]:gap-y-2"
+ title={errorHeader || 'Error running SQL query'}
+ description={
+ <div>
+ {errorContent.length > 0 ? (
+ errorContent.map((errorText: string, i: number) => (
+ <pre key={`err-${i}`} className="font-mono text-xs whitespace-pre-wrap">
+ {errorText}
+ </pre>
+ ))
+ ) : (
+ <p className="font-mono text-xs">{error.error}</p>
+ )}
+ </div>
+ }
+ />
+ </div>
+ )}
+
+ {showWarning && (
+ <SqlWarningAdmonition
+ className="border-t"
+ warningType={showWarning}
+ onCancel={() => setShowWarning(undefined)}
+ onConfirm={() => {
+ setShowWarning(undefined)
+ onExecuteSql(true)
+ }}
+ />
+ )}
+
+ {results !== undefined && results.length > 0 && (
+ <div className={`max-h-72 shrink-0 flex flex-col ${showResults && 'h-full'}`}>
+ {showResults && (
+ <div className="border-t flex-1 overflow-auto">
+ <Results rows={results} />
+ </div>
+ )}
+ <p className="text-xs text-foreground-light border-t py-2 px-5 flex items-center justify-between">
+ <span className="font-mono">
+ {results.length} rows{results.length >= 100 && ` (Limited to only 100 rows)`}
+ </span>
+ <Button
+ size="tiny"
+ type="default"
+ className="ml-2"
+ onClick={() => setShowResults((prev) => !prev)}
+ >
+ {showResults ? 'Hide Results' : 'Show Results'}
+ </Button>
+ </p>
+ </div>
+ )}
+ {results !== undefined && results.length === 0 && !error && (
+ <div className="shrink-0">
+ <p className="text-xs text-foreground-light font-mono py-2 px-5">
+ Success. No rows returned.
+ </p>
+ </div>
+ )}
- {results !== undefined && results.length > 0 && (
- <div className={`max-h-72 shrink-0 flex flex-col ${showResults && 'h-full'}`}>
- {showResults && (
- <div className="border-t flex-1 overflow-auto">
- <Results rows={results} />
- </div>
+ <div className="flex items-center gap-2 justify-end px-5 py-4 w-full border-t shrink-0">
+ {onSave && (
+ <Form_Shadcn_ {...saveForm}>
+ <form
+ onSubmit={saveForm.handleSubmit((values) => {
+ onSave(currentValue, values.saveValue)
+ })}
+ className="flex items-center gap-2"
+ >
+ {saveValue && (
+ <FormField_Shadcn_
+ control={saveForm.control}
+ name="saveValue"
+ render={({ field }) => (
+ <Input size="tiny" placeholder="Enter save value..." {...field} />
+ )}
+ />
+ )}
+ <Button size="tiny" type="default" htmlType="submit">
+ {saveLabel}
+ </Button>
+ </form>
+ </Form_Shadcn_>
)}
- <p className="text-xs text-foreground-light border-t py-2 px-5 flex items-center justify-between">
- <span className="font-mono">
- {results.length} rows{results.length >= 100 && ` (Limited to only 100 rows)`}
- </span>
- <Button
- size="tiny"
- type="default"
- className="ml-2"
- onClick={() => setShowResults((prev) => !prev)}
- >
- {showResults ? 'Hide Results' : 'Show Results'}
- </Button>
- </p>
- </div>
- )}
- {results !== undefined && results.length === 0 && (
- <div className="shrink-0">
- <p className="text-xs text-foreground-light font-mono py-2 px-5">
- Success. No rows returned.
- </p>
+ <SqlRunButton
+ isDisabled={isExecuting}
+ isExecuting={isExecuting}
+ onClick={onExecuteSql}
+ />
</div>
- )}
-
- <div className="bg-surface-100 flex items-center gap-2 justify-end px-5 py-4 w-full border-t shrink-0">
- <SqlRunButton isDisabled={isExecuting} isExecuting={isExecuting} onClick={onExecuteSql} />
</div>
- </div>
- </div>
+ </SheetContent>
+ </Sheet>
)
}
diff --git a/apps/studio/components/ui/QueryBlock/EditQueryButton.tsx b/apps/studio/components/ui/QueryBlock/EditQueryButton.tsx
index 8559432226d..60585ed6662 100644
--- a/apps/studio/components/ui/QueryBlock/EditQueryButton.tsx
+++ b/apps/studio/components/ui/QueryBlock/EditQueryButton.tsx
@@ -10,7 +10,6 @@ import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization
import Link from 'next/link'
import { ComponentProps } from 'react'
import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'
-import { useAppStateSnapshot } from 'state/app-state'
import { useSqlEditorV2StateSnapshot } from 'state/sql-editor-v2'
import {
cn,
@@ -42,7 +41,6 @@ export const EditQueryButton = ({
const { newQuery } = useNewQuery()
const sqlEditorSnap = useSqlEditorV2StateSnapshot()
- const { setEditorPanel } = useAppStateSnapshot()
const snap = useAiAssistantStateSnapshot()
const isInSQLEditor = router.pathname.includes('/sql')
@@ -78,10 +76,9 @@ export const EditQueryButton = ({
icon={<Edit size={14} strokeWidth={1.5} />}
onClick={() => {
if (isInlineEditorEnabled) {
- setEditorPanel({
- open: true,
- initialValue: sql,
- })
+ // This component needs to be updated to work with local EditorPanel state
+ // For now, fall back to creating a new query
+ if (sql) newQuery(sql, title)
snap.closeAssistant()
} else {
if (sql) newQuery(sql, title)
diff --git a/apps/studio/hooks/ui/useHotKey.ts b/apps/studio/hooks/ui/useHotKey.ts
index d0c381b9beb..4d1093ea10e 100644
--- a/apps/studio/hooks/ui/useHotKey.ts
+++ b/apps/studio/hooks/ui/useHotKey.ts
@@ -1,11 +1,14 @@
import { useEffect } from 'react'
-export function useHotKey(callback: () => void, key: string): void {
+export function useHotKey(
+ callback: (e: KeyboardEvent) => void,
+ key: string,
+ dependencies: any[] = []
+): void {
useEffect(() => {
function handler(e: KeyboardEvent) {
- if (e.key === key && (e.metaKey || e.ctrlKey)) {
- // e.preventDefault();
- callback()
+ if ((e.metaKey || e.ctrlKey) && e.key === key && !e.altKey && !e.shiftKey) {
+ callback(e)
}
}
@@ -13,5 +16,5 @@ export function useHotKey(callback: () => void, key: string): void {
return () => {
window.removeEventListener('keydown', handler)
}
- }, [key])
+ }, [key, ...dependencies])
}
diff --git a/apps/studio/pages/project/[ref]/auth/policies.tsx b/apps/studio/pages/project/[ref]/auth/policies.tsx
index 0e6ba60d9ac..fe8f6313386 100644
--- a/apps/studio/pages/project/[ref]/auth/policies.tsx
+++ b/apps/studio/pages/project/[ref]/auth/policies.tsx
@@ -12,6 +12,7 @@ import AuthLayout from 'components/layouts/AuthLayout/AuthLayout'
import DefaultLayout from 'components/layouts/DefaultLayout'
import AlertError from 'components/ui/AlertError'
import { DocsButton } from 'components/ui/DocsButton'
+import { EditorPanel } from 'components/ui/EditorPanel/EditorPanel'
import NoPermission from 'components/ui/NoPermission'
import SchemaSelector from 'components/ui/SchemaSelector'
import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'
@@ -21,7 +22,6 @@ import { useCheckPermissions, usePermissionsLoaded } from 'hooks/misc/useCheckPe
import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
import { useUrlState } from 'hooks/ui/useUrlState'
import { useIsProtectedSchema } from 'hooks/useProtectedSchemas'
-import { useAppStateSnapshot } from 'state/app-state'
import type { NextPageWithLayout } from 'types'
import { Input } from 'ui'
@@ -67,13 +67,15 @@ const AuthPoliciesPage: NextPageWithLayout = () => {
}>()
const { schema = 'public', search: searchString = '' } = params
const { data: project } = useSelectedProjectQuery()
- const { setEditorPanel } = useAppStateSnapshot()
const isInlineEditorEnabled = useIsInlineEditorEnabled()
const [selectedTable, setSelectedTable] = useState<string>()
const [showPolicyAiEditor, setShowPolicyAiEditor] = useState(false)
const [selectedPolicyToEdit, setSelectedPolicyToEdit] = useState<PostgresPolicy>()
+ // Local editor panel state
+ const [editorPanelOpen, setEditorPanelOpen] = useState(false)
+
const { isSchemaLocked } = useIsProtectedSchema({ schema: schema, excludedSchemas: ['realtime'] })
const { data: policies } = useDatabasePoliciesQuery({
@@ -142,43 +144,20 @@ const AuthPoliciesPage: NextPageWithLayout = () => {
hasTables={tables.length > 0}
isLocked={isSchemaLocked}
onSelectCreatePolicy={(table: string) => {
+ setSelectedTable(table)
+ setSelectedPolicyToEdit(undefined)
if (isInlineEditorEnabled) {
- setEditorPanel({
- open: true,
- initialValue: `create policy "replace_with_policy_name"
- on ${schema}.${table}
- for select
- to authenticated
- using (
- true -- Write your policy condition here
-);`,
- label: `Create new RLS policy on "${table}"`,
- saveLabel: 'Create policy',
- initialPrompt: `Create and name a entirely new RLS policy for the "${table}" table in the ${schema} schema. The policy should...`,
- })
+ setEditorPanelOpen(true)
} else {
- setSelectedTable(table)
setShowPolicyAiEditor(true)
}
}}
onSelectEditPolicy={(policy) => {
+ setSelectedPolicyToEdit(policy)
+ setSelectedTable(undefined)
if (isInlineEditorEnabled) {
- const sql = generatePolicyUpdateSQL(policy)
- const templates = getGeneralPolicyTemplates(policy.schema, policy.table)
- setEditorPanel({
- open: true,
- initialValue: sql,
- label: `Edit policy "${policy.name}"`,
- saveLabel: 'Update policy',
- templates: templates.map((template) => ({
- name: template.templateName,
- description: template.description,
- content: template.statement,
- })),
- initialPrompt: `Update the policy with name "${policy.name}" in the ${policy.schema} schema on the ${policy.table} table. It should...`,
- })
+ setEditorPanelOpen(true)
} else {
- setSelectedPolicyToEdit(policy)
setShowPolicyAiEditor(true)
}
}}
@@ -198,6 +177,59 @@ const AuthPoliciesPage: NextPageWithLayout = () => {
}}
authContext="database"
/>
+
+ <EditorPanel
+ open={editorPanelOpen}
+ onClose={() => {
+ setEditorPanelOpen(false)
+ setSelectedPolicyToEdit(undefined)
+ setSelectedTable(undefined)
+ }}
+ onRunSuccess={() => {
+ setEditorPanelOpen(false)
+ setSelectedPolicyToEdit(undefined)
+ setSelectedTable(undefined)
+ }}
+ initialValue={
+ selectedPolicyToEdit
+ ? generatePolicyUpdateSQL(selectedPolicyToEdit)
+ : selectedTable
+ ? `create policy "replace_with_policy_name"
+ on ${schema}.${selectedTable}
+ for select
+ to authenticated
+ using (
+ true -- Write your policy condition here
+);`
+ : ''
+ }
+ label={
+ selectedPolicyToEdit
+ ? 'RLS policies are just SQL statements that you can alter'
+ : selectedTable
+ ? `Create new RLS policy on "${selectedTable}"`
+ : ''
+ }
+ initialPrompt={
+ selectedPolicyToEdit
+ ? `Update the policy with name "${selectedPolicyToEdit.name}" in the ${selectedPolicyToEdit.schema} schema on the ${selectedPolicyToEdit.table} table. It should...`
+ : selectedTable
+ ? `Create and name a entirely new RLS policy for the "${selectedTable}" table in the ${schema} schema. The policy should...`
+ : ''
+ }
+ templates={
+ selectedPolicyToEdit
+ ? getGeneralPolicyTemplates(
+ selectedPolicyToEdit.schema,
+ selectedPolicyToEdit.table
+ ).map((template) => ({
+ name: template.templateName,
+ description: template.description,
+ content: template.statement,
+ }))
+ : []
+ }
+ />
</div>
)
}
diff --git a/apps/studio/pages/project/[ref]/database/functions.tsx b/apps/studio/pages/project/[ref]/database/functions.tsx
index 0fba9273945..c4653c0b56b 100644
--- a/apps/studio/pages/project/[ref]/database/functions.tsx
+++ b/apps/studio/pages/project/[ref]/database/functions.tsx
@@ -7,39 +7,32 @@ import FunctionsList from 'components/interfaces/Database/Functions/FunctionsLis
import DatabaseLayout from 'components/layouts/DatabaseLayout/DatabaseLayout'
import DefaultLayout from 'components/layouts/DefaultLayout'
import { ScaffoldContainer, ScaffoldSection } from 'components/layouts/Scaffold'
+import { EditorPanel } from 'components/ui/EditorPanel/EditorPanel'
import { FormHeader } from 'components/ui/Forms/FormHeader'
import NoPermission from 'components/ui/NoPermission'
import { DatabaseFunction } from 'data/database-functions/database-functions-query'
import { useCheckPermissions, usePermissionsLoaded } from 'hooks/misc/useCheckPermissions'
-import { useAppStateSnapshot } from 'state/app-state'
import type { NextPageWithLayout } from 'types'
const DatabaseFunctionsPage: NextPageWithLayout = () => {
const [selectedFunction, setSelectedFunction] = useState<DatabaseFunction | undefined>()
const [showCreateFunctionForm, setShowCreateFunctionForm] = useState(false)
const [showDeleteFunctionForm, setShowDeleteFunctionForm] = useState(false)
- const { setEditorPanel } = useAppStateSnapshot()
const isInlineEditorEnabled = useIsInlineEditorEnabled()
+ // Local editor panel state
+ const [editorPanelOpen, setEditorPanelOpen] = useState(false)
+ const [selectedFunctionForEditor, setSelectedFunctionForEditor] = useState<
+ DatabaseFunction | undefined
+ >()
+
const canReadFunctions = useCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_READ, 'functions')
const isPermissionsLoaded = usePermissionsLoaded()
const createFunction = () => {
if (isInlineEditorEnabled) {
- setEditorPanel({
- open: true,
- initialValue: `create function function_name()
-returns void
-language plpgsql
-as $$
-begin
- -- Write your function logic here
-end;
-$$;`,
- label: 'Create new database function',
- saveLabel: 'Create function',
- initialPrompt: 'Create a new database function that...',
- })
+ setSelectedFunctionForEditor(undefined)
+ setEditorPanelOpen(true)
} else {
setSelectedFunction(undefined)
setShowCreateFunctionForm(true)
@@ -48,13 +41,8 @@ $$;`,
const editFunction = (fn: DatabaseFunction) => {
if (isInlineEditorEnabled) {
- setEditorPanel({
- open: true,
- initialValue: fn.complete_statement,
- label: `Edit function "${fn.name}"`,
- saveLabel: 'Update function',
- initialPrompt: `Update the database function "${fn.name}" to...`,
- })
+ setSelectedFunctionForEditor(fn)
+ setEditorPanelOpen(true)
} else {
setSelectedFunction(fn)
setShowCreateFunctionForm(true)
@@ -97,6 +85,40 @@ $$;`,
visible={showDeleteFunctionForm}
setVisible={setShowDeleteFunctionForm}
/>
+
+ <EditorPanel
+ open={editorPanelOpen}
+ onRunSuccess={() => {
+ setEditorPanelOpen(false)
+ setSelectedFunctionForEditor(undefined)
+ }}
+ onClose={() => {
+ setEditorPanelOpen(false)
+ setSelectedFunctionForEditor(undefined)
+ }}
+ initialValue={
+ selectedFunctionForEditor
+ ? selectedFunctionForEditor.complete_statement
+ : `create function function_name()
+returns void
+language plpgsql
+as $$
+begin
+ -- Write your function logic here
+end;
+$$;`
+ }
+ label={
+ selectedFunctionForEditor
+ ? `Edit function "${selectedFunctionForEditor.name}"`
+ : 'Create new database function'
+ }
+ initialPrompt={
+ selectedFunctionForEditor
+ ? `Update the database function "${selectedFunctionForEditor.name}" to...`
+ : 'Create a new database function that...'
+ }
+ />
</>
)
}
diff --git a/apps/studio/pages/project/[ref]/database/triggers.tsx b/apps/studio/pages/project/[ref]/database/triggers.tsx
index 890b49919cd..587f409b39d 100644
--- a/apps/studio/pages/project/[ref]/database/triggers.tsx
+++ b/apps/studio/pages/project/[ref]/database/triggers.tsx
@@ -10,35 +10,30 @@ import TriggersList from 'components/interfaces/Database/Triggers/TriggersList/T
import DatabaseLayout from 'components/layouts/DatabaseLayout/DatabaseLayout'
import DefaultLayout from 'components/layouts/DefaultLayout'
import { ScaffoldContainer, ScaffoldSection } from 'components/layouts/Scaffold'
+import { EditorPanel } from 'components/ui/EditorPanel/EditorPanel'
import { FormHeader } from 'components/ui/Forms/FormHeader'
import NoPermission from 'components/ui/NoPermission'
import { useCheckPermissions, usePermissionsLoaded } from 'hooks/misc/useCheckPermissions'
-import { useAppStateSnapshot } from 'state/app-state'
import type { NextPageWithLayout } from 'types'
const TriggersPage: NextPageWithLayout = () => {
- const { setEditorPanel } = useAppStateSnapshot()
const isInlineEditorEnabled = useIsInlineEditorEnabled()
const [selectedTrigger, setSelectedTrigger] = useState<PostgresTrigger>()
const [showCreateTriggerForm, setShowCreateTriggerForm] = useState<boolean>(false)
const [showDeleteTriggerForm, setShowDeleteTriggerForm] = useState<boolean>(false)
+ // Local editor panel state
+ const [editorPanelOpen, setEditorPanelOpen] = useState(false)
+ const [selectedTriggerForEditor, setSelectedTriggerForEditor] = useState<PostgresTrigger>()
+
const canReadTriggers = useCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_READ, 'triggers')
const isPermissionsLoaded = usePermissionsLoaded()
const createTrigger = () => {
if (isInlineEditorEnabled) {
- setEditorPanel({
- open: true,
- initialValue: `create trigger trigger_name
-after insert or update or delete on table_name
-for each row
-execute function function_name();`,
- label: 'Create new database trigger',
- saveLabel: 'Create trigger',
- initialPrompt: 'Create a new database trigger that...',
- })
+ setSelectedTriggerForEditor(undefined)
+ setEditorPanelOpen(true)
} else {
setSelectedTrigger(undefined)
setShowCreateTriggerForm(true)
@@ -47,14 +42,8 @@ execute function function_name();`,
const editTrigger = (trigger: PostgresTrigger) => {
if (isInlineEditorEnabled) {
- const sql = generateTriggerCreateSQL(trigger)
- setEditorPanel({
- open: true,
- initialValue: sql,
- label: `Edit trigger "${trigger.name}"`,
- saveLabel: 'Update trigger',
- initialPrompt: `Update the database trigger "${trigger.name}" to...`,
- })
+ setSelectedTriggerForEditor(trigger)
+ setEditorPanelOpen(true)
} else {
setSelectedTrigger(trigger)
setShowCreateTriggerForm(true)
@@ -98,6 +87,36 @@ execute function function_name();`,
visible={showDeleteTriggerForm}
setVisible={setShowDeleteTriggerForm}
/>
+
+ <EditorPanel
+ open={editorPanelOpen}
+ onRunSuccess={() => {
+ setEditorPanelOpen(false)
+ setSelectedTriggerForEditor(undefined)
+ }}
+ onClose={() => {
+ setEditorPanelOpen(false)
+ setSelectedTriggerForEditor(undefined)
+ }}
+ initialValue={
+ selectedTriggerForEditor
+ ? generateTriggerCreateSQL(selectedTriggerForEditor)
+ : `create trigger trigger_name
+after insert or update or delete on table_name
+for each row
+execute function function_name();`
+ }
+ label={
+ selectedTriggerForEditor
+ ? `Edit trigger "${selectedTriggerForEditor.name}"`
+ : 'Create new database trigger'
+ }
+ initialPrompt={
+ selectedTriggerForEditor
+ ? `Update the database trigger "${selectedTriggerForEditor.name}" to...`
+ : 'Create a new database trigger that...'
+ }
+ />
</>
)
}
diff --git a/apps/studio/pages/project/[ref]/reports/api-overview.tsx b/apps/studio/pages/project/[ref]/reports/api-overview.tsx
index 6db01dc456b..db5c13970d7 100644
--- a/apps/studio/pages/project/[ref]/reports/api-overview.tsx
+++ b/apps/studio/pages/project/[ref]/reports/api-overview.tsx
@@ -1,7 +1,9 @@
import ReportFilterBar from 'components/interfaces/Reports/ReportFilterBar'
import ReportHeader from 'components/interfaces/Reports/ReportHeader'
import ReportPadding from 'components/interfaces/Reports/ReportPadding'
+import ReportStickyNav from 'components/interfaces/Reports/ReportStickyNav'
import ReportWidget from 'components/interfaces/Reports/ReportWidget'
+import { REPORT_DATERANGE_HELPER_LABELS } from 'components/interfaces/Reports/Reports.constants'
import {
ErrorCountsChartRenderer,
NetworkTrafficRenderer,
@@ -10,16 +12,12 @@ import {
TotalRequestsChartRenderer,
} from 'components/interfaces/Reports/renderers/ApiRenderers'
import { DatePickerValue } from 'components/interfaces/Settings/Logs/Logs.DatePickers'
+import UpgradePrompt from 'components/interfaces/Settings/Logs/UpgradePrompt'
import DefaultLayout from 'components/layouts/DefaultLayout'
import ReportsLayout from 'components/layouts/ReportsLayout/ReportsLayout'
-import ReportStickyNav from 'components/interfaces/Reports/ReportStickyNav'
-import { REPORT_DATERANGE_HELPER_LABELS } from 'components/interfaces/Reports/Reports.constants'
-import { useState } from 'react'
-
import { useApiReport } from 'data/reports/api-report-query'
import { useReportDateRange } from 'hooks/misc/useReportDateRange'
import { NextPageWithLayout } from 'types'
-import UpgradePrompt from 'components/interfaces/Settings/Logs/UpgradePrompt'
export const ApiReport: NextPageWithLayout = () => {
const report = useApiReport()
diff --git a/apps/studio/state/app-state.ts b/apps/studio/state/app-state.ts
index 9303cc4ed12..133c53edd2e 100644
--- a/apps/studio/state/app-state.ts
+++ b/apps/studio/state/app-state.ts
@@ -1,80 +1,18 @@
-import { proxy, snapshot, subscribe, useSnapshot } from 'valtio'
+import { proxy, snapshot, useSnapshot } from 'valtio'
import { LOCAL_STORAGE_KEYS as COMMON_LOCAL_STORAGE_KEYS, LOCAL_STORAGE_KEYS } from 'common'
-import { SQL_TEMPLATES } from 'components/interfaces/SQLEditor/SQLEditor.queries'
-
-export type Template = {
- name: string
- description: string
- content: string
-}
-
-type EditorPanelType = {
- open: boolean
- initialValue?: string
- label?: string
- saveLabel?: string
- onSave?: (value: string) => void
- functionName?: string
- templates?: Template[]
- initialPrompt?: string
-}
-
type DashboardHistoryType = {
sql?: string
editor?: string
}
-const INITIAL_EDITOR_PANEL: EditorPanelType = {
- open: false,
- initialValue: '',
- label: '',
- saveLabel: '',
- initialPrompt: '',
- templates: SQL_TEMPLATES.filter((template) => template.type === 'template').map((template) => ({
- name: template.title,
- description: template.description,
- content: template.sql,
- })),
-}
-
const EMPTY_DASHBOARD_HISTORY: DashboardHistoryType = {
sql: undefined,
editor: undefined,
}
const getInitialState = () => {
- if (typeof window === 'undefined') {
- return {
- editorPanel: INITIAL_EDITOR_PANEL,
- dashboardHistory: EMPTY_DASHBOARD_HISTORY,
- activeDocsSection: ['introduction'],
- docsLanguage: 'js',
- showProjectApiDocs: false,
- showCreateBranchModal: false,
- showAiSettingsModal: false,
- showConnectDialog: false,
- ongoingQueriesPanelOpen: false,
- mobileMenuOpen: false,
- showSidebar: true,
- lastRouteBeforeVisitingAccountPage: '',
- }
- }
-
- const storedEditor = localStorage.getItem(LOCAL_STORAGE_KEYS.EDITOR_PANEL_STATE)
-
- let parsedEditorPanel = INITIAL_EDITOR_PANEL
-
- try {
- if (storedEditor) {
- parsedEditorPanel = JSON.parse(storedEditor)
- }
- } catch {
- // Ignore parsing errors
- }
-
return {
- editorPanel: parsedEditorPanel,
dashboardHistory: EMPTY_DASHBOARD_HISTORY,
activeDocsSection: ['introduction'],
docsLanguage: 'js',
@@ -85,6 +23,7 @@ const getInitialState = () => {
ongoingQueriesPanelOpen: false,
mobileMenuOpen: false,
showSidebar: true,
+ showEditorPanel: false,
lastRouteBeforeVisitingAccountPage: '',
}
}
@@ -148,26 +87,6 @@ export const appState = proxy({
appState.ongoingQueriesPanelOpen = value
},
- setEditorPanel: (value: Partial<EditorPanelType>) => {
- // Reset templates to initial if initialValue is empty
- if (value.initialValue === '') {
- value.templates = INITIAL_EDITOR_PANEL.templates
- }
-
- if (!value.open) {
- value.initialPrompt = INITIAL_EDITOR_PANEL.initialPrompt
- }
-
- appState.editorPanel = {
- ...appState.editorPanel,
- ...value,
- }
- },
-
- toggleEditorPanel: (value?: boolean) => {
- appState.editorPanel.open = value ?? !appState.editorPanel.open
- },
-
mobileMenuOpen: false,
setMobileMenuOpen: (value: boolean) => {
appState.mobileMenuOpen = value
@@ -179,16 +98,6 @@ export const appState = proxy({
},
})
-// Set up localStorage subscriptions
-if (typeof window !== 'undefined') {
- subscribe(appState, () => {
- localStorage.setItem(
- LOCAL_STORAGE_KEYS.EDITOR_PANEL_STATE,
- JSON.stringify(appState.editorPanel)
- )
- })
-}
-
export const getAppStateSnapshot = () => snapshot(appState)
export const useAppStateSnapshot = (options?: Parameters<typeof useSnapshot>[1]) =>