Skip to content

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

feat(inline sql editor): snippet management in editor panel (#43011)

Jordi Enric233c2d4a4c23
diff --git a/apps/studio/components/interfaces/HomeNew/SnippetDropdown.tsx b/apps/studio/components/interfaces/HomeNew/SnippetDropdown.tsx
index b43172a0a84..7ab0d5d70c1 100644
--- a/apps/studio/components/interfaces/HomeNew/SnippetDropdown.tsx
+++ b/apps/studio/components/interfaces/HomeNew/SnippetDropdown.tsx
@@ -1,13 +1,13 @@
-import { useDebounce, useIntersectionObserver } from '@uidotdev/usehooks'
-import { Plus } from 'lucide-react'
-import Link from 'next/link'
-import { useRouter } from 'next/router'
-import { ReactNode, useEffect, useMemo, useRef, useState } from 'react'
-
import { keepPreviousData } from '@tanstack/react-query'
+import { useDebounce, useIntersectionObserver } from '@uidotdev/usehooks'
+import { SIDEBAR_KEYS } from 'components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'
import { useContentInfiniteQuery } from 'data/content/content-infinite-query'
import type { Content } from 'data/content/content-query'
import { SNIPPET_PAGE_LIMIT } from 'data/content/sql-folders-query'
+import { Plus } from 'lucide-react'
+import { ReactNode, useEffect, useMemo, useRef, useState } from 'react'
+import { editorPanelState } from 'state/editor-panel-state'
+import { useSidebarManagerSnapshot } from 'state/sidebar-manager-state'
import {
Command_Shadcn_,
CommandGroup_Shadcn_,
@@ -42,7 +42,7 @@ export const SnippetDropdown = ({
autoFocus = false,
onSelect,
}: SnippetDropdownProps) => {
- const router = useRouter()
+ const { openSidebar } = useSidebarManagerSnapshot()
const scrollRootRef = useRef<HTMLDivElement | null>(null)
const [open, setOpen] = useState(false)
@@ -133,20 +133,14 @@ export const SnippetDropdown = ({
className="cursor-pointer w-full"
onSelect={() => {
setOpen(false)
- router.push(`/project/${projectRef}/sql/new`)
+ editorPanelState.openAsNew()
+ openSidebar(SIDEBAR_KEYS.EDITOR_PANEL)
}}
- onClick={() => setOpen(false)}
>
- <Link
- href={`/project/${projectRef}/sql/new`}
- onClick={() => {
- setOpen(false)
- }}
- className="w-full flex items-center gap-2"
- >
+ <div className="w-full flex items-center gap-2">
<Plus size={14} strokeWidth={1.5} />
- <p>Create a report block with SQL</p>
- </Link>
+ <p>Create snippet</p>
+ </div>
</CommandItem_Shadcn_>
</CommandGroup_Shadcn_>
</CommandList_Shadcn_>
diff --git a/apps/studio/components/ui/AIEditor/index.tsx b/apps/studio/components/ui/AIEditor/index.tsx
index 6335e6d11ad..c3d6fbdbd71 100644
--- a/apps/studio/components/ui/AIEditor/index.tsx
+++ b/apps/studio/components/ui/AIEditor/index.tsx
@@ -1,14 +1,14 @@
import Editor, { Monaco, OnMount } from '@monaco-editor/react'
+import { SIDEBAR_KEYS } from 'components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'
+import { constructHeaders } from 'data/fetchers'
import { AnimatePresence, motion } from 'framer-motion'
+import { detectOS } from 'lib/helpers'
import { Command } from 'lucide-react'
import type { editor as monacoEditor } from 'monaco-editor'
import { useCallback, useEffect, useRef, useState } from 'react'
import { toast } from 'sonner'
-
-import { SIDEBAR_KEYS } from 'components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'
-import { constructHeaders } from 'data/fetchers'
-import { detectOS } from 'lib/helpers'
import { useSidebarManagerSnapshot } from 'state/sidebar-manager-state'
+
import { DiffEditor } from '../DiffEditor'
import ResizableAIWidget from './ResizableAIWidget'
@@ -33,6 +33,7 @@ interface AIEditorProps {
closeShortcutEnabled?: boolean
openAIAssistantShortcutEnabled?: boolean
executeQuery?: () => void
+ onMount?: (editor: monacoEditor.IStandaloneCodeEditor, monaco: Monaco) => void
}
// [Joshen] This has overlap with components/interfaces/SQLEditor/MonacoEditor
@@ -55,6 +56,7 @@ export const AIEditor = ({
closeShortcutEnabled = true,
openAIAssistantShortcutEnabled = true,
executeQuery,
+ onMount,
}: AIEditorProps) => {
const os = detectOS()
const { toggleSidebar } = useSidebarManagerSnapshot()
@@ -179,6 +181,7 @@ export const AIEditor = ({
) => {
editorRef.current = editor
monacoRef.current = monaco
+ onMount?.(editor, monaco)
// Set prompt state to open if promptInput exists
if (promptInput) {
const model = editor.getModel()
diff --git a/apps/studio/components/ui/EditorPanel/EditorPanel.tsx b/apps/studio/components/ui/EditorPanel/EditorPanel.tsx
index 7f660ea02c1..a9a4ce4548a 100644
--- a/apps/studio/components/ui/EditorPanel/EditorPanel.tsx
+++ b/apps/studio/components/ui/EditorPanel/EditorPanel.tsx
@@ -1,3 +1,6 @@
+import type { Monaco } from '@monaco-editor/react'
+import { useQueryClient } from '@tanstack/react-query'
+import { useDebounce } from '@uidotdev/usehooks'
import { LOCAL_STORAGE_KEYS, useParams } from 'common'
import { isExplainQuery } from 'components/interfaces/ExplainVisualizer/ExplainVisualizer.utils'
import { generateSnippetTitle } from 'components/interfaces/SQLEditor/SQLEditor.constants'
@@ -5,19 +8,33 @@ import {
createSqlSnippetSkeletonV2,
suffixWithLimit,
} from 'components/interfaces/SQLEditor/SQLEditor.utils'
+import { useAddDefinitions } from 'components/interfaces/SQLEditor/useAddDefinitions'
import Results from 'components/interfaces/SQLEditor/UtilityPanel/Results'
import { SqlRunButton } from 'components/interfaces/SQLEditor/UtilityPanel/RunButton'
import { SIDEBAR_KEYS } from 'components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'
+import { useContentIdQuery } from 'data/content/content-id-query'
+import { useContentQuery, type Content } from 'data/content/content-query'
+import { useContentUpsertMutation } from 'data/content/content-upsert-mutation'
+import { contentKeys } from 'data/content/keys'
import { useExecuteSqlMutation } from 'data/sql/execute-sql-mutation'
import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'
import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
import { BASE_PATH } from 'lib/constants'
import { useProfile } from 'lib/profile'
-import { Book, Maximize2, X } from 'lucide-react'
+import {
+ AlertCircle,
+ Book,
+ CheckCircle2,
+ FolderOpen,
+ Loader2,
+ Maximize2,
+ PlusIcon,
+ X,
+} from 'lucide-react'
import { useRouter } from 'next/router'
-import { useId, useState } from 'react'
-import { useEditorPanelStateSnapshot } from 'state/editor-panel-state'
+import { useEffect, useRef, useState } from 'react'
+import { editorPanelState, useEditorPanelStateSnapshot } from 'state/editor-panel-state'
import { useSidebarManagerSnapshot } from 'state/sidebar-manager-state'
import { useSqlEditorV2StateSnapshot } from 'state/sql-editor-v2'
import {
@@ -45,6 +62,8 @@ import { containsUnknownFunction, isReadOnlySelect } from '../AIAssistantPanel/A
import { AIEditor } from '../AIEditor'
import { ButtonTooltip } from '../ButtonTooltip'
import { SqlWarningAdmonition } from '../SqlWarningAdmonition'
+import { formatSqlError } from './EditorPanel.utils'
+import { SaveSnippetDialog } from './SaveSnippetDialog'
export const EditorPanel = () => {
const {
@@ -58,12 +77,33 @@ export const EditorPanel = () => {
setTemplates,
setResults,
setError,
+ activeSnippetId,
+ pendingReset,
} = useEditorPanelStateSnapshot()
const { profile } = useProfile()
const { closeSidebar } = useSidebarManagerSnapshot()
const sqlEditorSnap = useSqlEditorV2StateSnapshot()
+ const queryClient = useQueryClient()
+
+ const [activeSnippet, setActiveSnippet] = useState<Extract<Content, { type: 'sql' }> | null>(null)
+ const [isEditingTitle, setIsEditingTitle] = useState(false)
+ const [titleInput, setTitleInput] = useState('')
+ const titleInputRef = useRef<HTMLInputElement>(null)
+ const [monaco, setMonaco] = useState<Monaco | null>(null)
+
+ useAddDefinitions('', monaco)
- const label = 'SQL Editor'
+ const label = activeSnippet?.name ?? 'SQL Editor'
+
+ const commitRename = () => {
+ const newName = titleInput.trim()
+ if (!newName || !activeSnippet) {
+ setIsEditingTitle(false)
+ return
+ }
+ setActiveSnippet({ ...activeSnippet, name: newName })
+ setIsEditingTitle(false)
+ }
const [isInlineEditorHotkeyEnabled] = useLocalStorageQuery<boolean>(
LOCAL_STORAGE_KEYS.HOTKEY_SIDEBAR(SIDEBAR_KEYS.EDITOR_PANEL),
true
@@ -82,17 +122,63 @@ export const EditorPanel = () => {
const [showWarning, setShowWarning] = useState<'hasWriteOperation' | 'hasUnknownFunctions'>()
const [showResults, setShowResults] = useState(true)
+ const [isSaveDialogOpen, setIsSaveDialogOpen] = useState(false)
+ const [saveStatus, setSaveStatus] = useState<'idle' | 'success' | 'error'>('idle')
+ const saveStatusTimerRef = useRef<ReturnType<typeof setTimeout>>()
+ const originalSnippetRef = useRef<{ sql: string; name: string } | null>(null)
+
+ const showSaveSuccess = () => {
+ setSaveStatus('success')
+ clearTimeout(saveStatusTimerRef.current)
+ saveStatusTimerRef.current = setTimeout(() => setSaveStatus('idle'), 2000)
+ }
const [isTemplatesOpen, setIsTemplatesOpen] = useState(false)
- const templatesListboxId = useId()
+ const [isSnippetsOpen, setIsSnippetsOpen] = useState(false)
+ const [snippetSearch, setSnippetSearch] = useState('')
+ const debouncedSnippetSearch = useDebounce(snippetSearch, 300)
+
+ const { data: snippetsData, isLoading: isLoadingSnippets } = useContentQuery(
+ { projectRef: ref, type: 'sql', name: debouncedSnippetSearch || undefined },
+ { enabled: isSnippetsOpen }
+ )
- const errorHeader = error?.formattedError?.split('\n')?.filter((x: string) => x.length > 0)?.[0]
- const errorContent =
- 'formattedError' in (error || {})
- ? error?.formattedError
- ?.split('\n')
- ?.filter((x: string) => x.length > 0)
- ?.slice(1) ?? []
- : [error?.message ?? '']
+ const { data: snippetById } = useContentIdQuery(
+ { projectRef: ref, id: activeSnippetId ?? undefined },
+ { enabled: !!activeSnippetId }
+ )
+
+ useEffect(() => {
+ if (!pendingReset) return
+ setActiveSnippet(null)
+ setIsEditingTitle(false)
+ originalSnippetRef.current = null
+ editorPanelState.pendingReset = false
+ }, [pendingReset, setActiveSnippet, setIsEditingTitle])
+
+ useEffect(() => {
+ if (!snippetById || !activeSnippetId) return
+ const sqlSnippet = snippetById as unknown as Extract<Content, { type: 'sql' }>
+ const sql = sqlSnippet.content.sql ?? ''
+ setValue(sql)
+ setActiveSnippet(sqlSnippet)
+ originalSnippetRef.current = { sql, name: sqlSnippet.name }
+ editorPanelState.setActiveSnippetId(null)
+ }, [snippetById, activeSnippetId, setValue, setActiveSnippet])
+
+ const { header: errorHeader, lines: errorContent } = error
+ ? formatSqlError(error)
+ : { header: undefined, lines: [] as string[] }
+
+ const { mutate: upsertContent, isPending: isUpserting } = useContentUpsertMutation({
+ onSuccess: (_, vars) => {
+ if (vars.payload.id && ref) {
+ queryClient.invalidateQueries({ queryKey: contentKeys.resource(ref, vars.payload.id) })
+ }
+ originalSnippetRef.current = { sql: currentValue, name: vars.payload.name }
+ showSaveSuccess()
+ },
+ onError: () => setSaveStatus('error'),
+ })
const { mutate: executeSql, isPending: isExecuting } = useExecuteSqlMutation({
onSuccess: async (res) => {
@@ -152,13 +238,102 @@ export const EditorPanel = () => {
setError(undefined)
setShowWarning(undefined)
setShowResults(true)
+ setActiveSnippet(null)
+ setIsEditingTitle(false)
+ editorPanelState.setActiveSnippetId(null)
}
return (
<div className="flex h-full flex-col bg-background">
<div className="border-b border-b-muted flex items-center justify-between gap-x-4 pl-4 pr-3 h-[var(--header-height)]">
- <div className="text-xs">{label}</div>
- <div className="flex items-center">
+ {isEditingTitle ? (
+ <input
+ ref={titleInputRef}
+ value={titleInput}
+ onChange={(e) => setTitleInput(e.target.value)}
+ onBlur={commitRename}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') commitRename()
+ if (e.key === 'Escape') setIsEditingTitle(false)
+ }}
+ className="text-xs bg-transparent border-b border-foreground-lighter outline-none w-48 py-0.5"
+ autoFocus
+ />
+ ) : (
+ <div
+ className={cn('text-xs', activeSnippet && 'cursor-pointer hover:text-foreground')}
+ onClick={() => {
+ if (!activeSnippet) return
+ setTitleInput(activeSnippet.name)
+ setIsEditingTitle(true)
+ }}
+ >
+ {label}
+ </div>
+ )}
+ <div className="flex items-center gap-2">
+ {activeSnippet && (
+ <ButtonTooltip
+ size="tiny"
+ type="text"
+ className="w-7 h-7 p-0"
+ icon={<PlusIcon size={14} />}
+ tooltip={{ content: { side: 'bottom', text: 'New snippet' } }}
+ onClick={() => editorPanelState.openAsNew()}
+ />
+ )}
+ <Popover_Shadcn_ open={isSnippetsOpen} onOpenChange={setIsSnippetsOpen}>
+ <PopoverTrigger_Shadcn_ asChild>
+ <ButtonTooltip
+ size="tiny"
+ type="text"
+ role="combobox"
+ aria-expanded={isSnippetsOpen}
+ className="w-7 h-7 p-0"
+ icon={<FolderOpen size={14} />}
+ tooltip={{
+ content: {
+ side: 'bottom',
+ text: 'Open snippet',
+ },
+ }}
+ ></ButtonTooltip>
+ </PopoverTrigger_Shadcn_>
+ <PopoverContent_Shadcn_ align="end" className="w-[300px] p-0">
+ <Command_Shadcn_ shouldFilter={false}>
+ <CommandInput_Shadcn_
+ placeholder="Search snippets..."
+ value={snippetSearch}
+ onValueChange={setSnippetSearch}
+ />
+ <CommandList_Shadcn_>
+ {isLoadingSnippets ? (
+ <div className="py-6 text-center text-sm text-foreground-light">
+ Loading snippets...
+ </div>
+ ) : (
+ <CommandEmpty_Shadcn_>No snippets found.</CommandEmpty_Shadcn_>
+ )}
+ <CommandGroup_Shadcn_>
+ {(snippetsData?.content ?? []).map((snippet) => (
+ <CommandItem_Shadcn_
+ key={snippet.id}
+ value={snippet.id}
+ className="cursor-pointer"
+ onSelect={() => {
+ if (snippet.id) editorPanelState.setActiveSnippetId(snippet.id)
+ setIsSnippetsOpen(false)
+ setSnippetSearch('')
+ }}
+ >
+ {snippet.name}
+ </CommandItem_Shadcn_>
+ ))}
+ </CommandGroup_Shadcn_>
+ </CommandList_Shadcn_>
+ </Command_Shadcn_>
+ </PopoverContent_Shadcn_>
+ </Popover_Shadcn_>
{templates.length > 0 && (
<Popover_Shadcn_ open={isTemplatesOpen} onOpenChange={setIsTemplatesOpen}>
<PopoverTrigger_Shadcn_ asChild>
@@ -168,13 +343,12 @@ export const EditorPanel = () => {
role="combobox"
className="mr-2"
aria-expanded={isTemplatesOpen}
- aria-controls={templatesListboxId}
icon={<Book size={14} />}
>
Templates
</Button>
</PopoverTrigger_Shadcn_>
- <PopoverContent_Shadcn_ id={templatesListboxId} align="end" className="w-[300px] p-0">
+ <PopoverContent_Shadcn_ align="end" className="w-[300px] p-0">
<Command_Shadcn_>
<CommandInput_Shadcn_ placeholder="Search templates..." />
<CommandList_Shadcn_>
@@ -284,6 +458,7 @@ export const EditorPanel = () => {
language="pgsql"
value={currentValue}
onChange={handleChange}
+ onMount={(_, m) => setMonaco(m)}
aiEndpoint={`${BASE_PATH}/api/ai/code/complete`}
aiMetadata={{
projectRef: project?.ref,
@@ -379,10 +554,89 @@ export const EditorPanel = () => {
</div>
)}
- <div className="flex items-center gap-2 justify-end px-5 py-4 w-full border-t shrink-0">
+ <div className="relative shrink-0 flex items-center gap-2 justify-end px-5 py-4 w-full border-t">
+ {(isUpserting || saveStatus !== 'idle') && (
+ <div
+ className={cn(
+ 'absolute left-0 flex items-center gap-2 px-5 py-3 text-xs',
+ saveStatus === 'success' && 'text-brand-600',
+ saveStatus === 'error' && 'text-warning',
+ saveStatus === 'idle' && 'text-foreground-light'
+ )}
+ >
+ {isUpserting && <Loader2 size={13} className="animate-spin" />}
+ {saveStatus === 'success' && <CheckCircle2 size={13} />}
+ {saveStatus === 'error' && <AlertCircle size={13} />}
+ <span>
+ {isUpserting
+ ? 'Saving...'
+ : saveStatus === 'success'
+ ? 'Snippet updated'
+ : 'Failed to save snippet'}
+ </span>
+ </div>
+ )}
+ <Button
+ type="default"
+ size="tiny"
+ disabled={
+ !currentValue ||
+ isExecuting ||
+ isUpserting ||
+ (!!activeSnippet &&
+ currentValue === originalSnippetRef.current?.sql &&
+ activeSnippet.name === originalSnippetRef.current?.name)
+ }
+ onClick={() => {
+ if (!ref || !profile || !project) return
+
+ if (activeSnippet) {
+ setSaveStatus('idle')
+ upsertContent({
+ projectRef: ref,
+ payload: {
+ id: activeSnippet.id,
+ type: 'sql',
+ name: activeSnippet.name,
+ description: activeSnippet.description ?? '',
+ visibility: activeSnippet.visibility ?? 'user',
+ project_id: project.id,
+ owner_id: profile.id,
+ content: {
+ ...activeSnippet.content,
+ sql: currentValue,
+ },
+ },
+ })
+ } else {
+ setIsSaveDialogOpen(true)
+ }
+ }}
+ >
+ {activeSnippet ? 'Update snippet' : 'Save as snippet'}
+ </Button>
<SqlRunButton isDisabled={isExecuting} isExecuting={isExecuting} onClick={onExecuteSql} />
</div>
</div>
+ <SaveSnippetDialog
+ open={isSaveDialogOpen}
+ sql={currentValue}
+ onOpenChange={setIsSaveDialogOpen}
+ onSave={(name) => {
+ if (!ref || !profile || !project) return
+ const snippet = createSqlSnippetSkeletonV2({
+ name,
+ sql: currentValue,
+ owner_id: profile.id,
+ project_id: project.id,
+ })
+ sqlEditorSnap.addSnippet({ projectRef: ref, snippet })
+ sqlEditorSnap.addNeedsSaving(snippet.id)
+ setActiveSnippet(snippet as unknown as Extract<Content, { type: 'sql' }>)
+ originalSnippetRef.current = { sql: currentValue, name }
+ showSaveSuccess()
+ }}
+ />
</div>
)
}
diff --git a/apps/studio/components/ui/EditorPanel/EditorPanel.utils.ts b/apps/studio/components/ui/EditorPanel/EditorPanel.utils.ts
new file mode 100644
index 00000000000..3a6ffa836c7
--- /dev/null
+++ b/apps/studio/components/ui/EditorPanel/EditorPanel.utils.ts
@@ -0,0 +1,9 @@
+import type { SqlError } from 'state/editor-panel-state'
+
+export function formatSqlError(error: SqlError): { header: string | undefined; lines: string[] } {
+ if (error.formattedError) {
+ const lines = error.formattedError.split('\n').filter((l) => l.length > 0)
+ return { header: lines[0], lines: lines.slice(1) }
+ }
+ return { header: undefined, lines: [error.message ?? ''] }
+}
diff --git a/apps/studio/components/ui/EditorPanel/SaveSnippetDialog.tsx b/apps/studio/components/ui/EditorPanel/SaveSnippetDialog.tsx
new file mode 100644
index 00000000000..4412fbf4604
--- /dev/null
+++ b/apps/studio/components/ui/EditorPanel/SaveSnippetDialog.tsx
@@ -0,0 +1,123 @@
+import { useParams } from 'common'
+import { subscriptionHasHipaaAddon } from 'components/interfaces/Billing/Subscription/Subscription.utils'
+import { generateSnippetTitle } from 'components/interfaces/SQLEditor/SQLEditor.constants'
+import { ButtonTooltip } from 'components/ui/ButtonTooltip'
+import { useCheckOpenAIKeyQuery } from 'data/ai/check-api-key-query'
+import { useSqlTitleGenerateMutation } from 'data/ai/sql-title-mutation'
+import { useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
+import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
+import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
+import { useEffect, useState } from 'react'
+import { toast } from 'sonner'
+import {
+ AiIconAnimation,
+ Button,
+ Dialog,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogSection,
+ DialogSectionSeparator,
+ DialogTitle,
+ Input_Shadcn_,
+ Label_Shadcn_,
+} from 'ui'
+
+interface SaveSnippetDialogProps {
+ open: boolean
+ sql: string
+ onOpenChange: (open: boolean) => void
+ onSave: (name: string) => void
+}
+
+export const SaveSnippetDialog = ({ open, sql, onOpenChange, onSave }: SaveSnippetDialogProps) => {
+ const { ref } = useParams()
+ const { data: organization } = useSelectedOrganizationQuery()
+ const { data: subscription } = useOrgSubscriptionQuery(
+ { orgSlug: organization?.slug },
+ { enabled: open }
+ )
+ const { data: projectSettings } = useProjectSettingsV2Query({ projectRef: ref })
+ const { data: check } = useCheckOpenAIKeyQuery()
+
+ const [name, setName] = useState(generateSnippetTitle())
+
+ const isApiKeySet = !!check?.hasKey
+ const hasHipaaAddon = subscriptionHasHipaaAddon(subscription) && projectSettings?.is_sensitive
+
+ const { mutate: generateTitle, isPending: isGenerating } = useSqlTitleGenerateMutation({
+ onSuccess: ({ title }) => setName(title),
+ onError: (error) => toast.error(`Failed to generate title: ${error.message}`),
+ })
+
+ // Reset the name each time the dialog opens
+ useEffect(() => {
+ if (open) setName(generateSnippetTitle())
+ }, [open])
+
+ const handleSave = () => {
+ const trimmed = name.trim()
+ if (!trimmed) return
+ onSave(trimmed)
+ onOpenChange(false)
+ }
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent size="small">
+ <DialogHeader>
+ <DialogTitle>Save snippet</DialogTitle>
+ </DialogHeader>
+ <DialogSectionSeparator />
+ <DialogSection className="flex flex-col gap-y-4 py-5">
+ <div className="flex flex-col gap-y-2">
+ <Label_Shadcn_ htmlFor="snippet-name">Name</Label_Shadcn_>
+ <Input_Shadcn_
+ id="snippet-name"
+ autoFocus
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') handleSave()
+ }}
+ />
+ </div>
+ {!hasHipaaAddon && (
+ <div className="flex justify-end">
+ <ButtonTooltip
+ type="default"
+ size="tiny"
+ disabled={isGenerating || !isApiKeySet}
+ onClick={() => generateTitle({ sql })}
+ tooltip={{
+ content: {
+ side: 'bottom',
+ text: isApiKeySet
+ ? undefined
+ : 'Add your "OPENAI_API_KEY" to your environment variables to use this feature.',
+ },
+ }}
+ >
+ <div className="flex items-center gap-1">
+ <div className="scale-75">
+ <AiIconAnimation loading={isGenerating} />
+ </div>
+ <span>Generate with AI</span>
+ </div>
+ </ButtonTooltip>
+ </div>
+ )}
+ </DialogSection>
+ <DialogSectionSeparator />
+ <DialogFooter className="px-5 py-4">
+ <Button type="default" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button disabled={!name.trim()} onClick={handleSave}>
+ Save snippet
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/apps/studio/components/ui/QueryBlock/EditQueryButton.tsx b/apps/studio/components/ui/QueryBlock/EditQueryButton.tsx
index 5e514a60979..2664e35f972 100644
--- a/apps/studio/components/ui/QueryBlock/EditQueryButton.tsx
+++ b/apps/studio/components/ui/QueryBlock/EditQueryButton.tsx
@@ -1,15 +1,14 @@
-import { Edit } from 'lucide-react'
-import Link from 'next/link'
-import { useRouter } from 'next/router'
-import { ComponentProps } from 'react'
-
import { useParams } from 'common'
import { useIsInlineEditorEnabled } from 'components/interfaces/Account/Preferences/InlineEditorSettings'
-import { DiffType } from 'components/interfaces/SQLEditor/SQLEditor.types'
import useNewQuery from 'components/interfaces/SQLEditor/hooks'
+import { DiffType } from 'components/interfaces/SQLEditor/SQLEditor.types'
import { SIDEBAR_KEYS } from 'components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'
import { useSendEventMutation } from 'data/telemetry/send-event-mutation'
import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
+import { Edit } from 'lucide-react'
+import { useRouter } from 'next/router'
+import { ComponentProps } from 'react'
+import { editorPanelState } from 'state/editor-panel-state'
import { useSidebarManagerSnapshot } from 'state/sidebar-manager-state'
import { useSqlEditorV2StateSnapshot } from 'state/sql-editor-v2'
import {
@@ -20,6 +19,7 @@ import {
DropdownMenuTrigger,
TooltipContent,
} from 'ui'
+
import { ButtonTooltip } from '../ButtonTooltip'
interface EditQueryButtonProps {
@@ -42,7 +42,7 @@ export const EditQueryButton = ({
const { newQuery } = useNewQuery()
const sqlEditorSnap = useSqlEditorV2StateSnapshot()
- const { closeSidebar } = useSidebarManagerSnapshot()
+ const { closeSidebar, openSidebar } = useSidebarManagerSnapshot()
const isInSQLEditor = router.pathname.includes('/sql')
const isInNewSnippet = router.pathname.endsWith('/sql')
@@ -57,15 +57,16 @@ export const EditQueryButton = ({
if (id !== undefined) {
return (
<ButtonTooltip
- asChild
type={type}
size="tiny"
className={cn('w-7 h-7', className)}
icon={<Edit size={14} strokeWidth={1.5} />}
tooltip={tooltip}
- >
- <Link href={`/project/${ref}/sql/${id}`} />
- </ButtonTooltip>
+ onClick={() => {
+ editorPanelState.setActiveSnippetId(id)
+ openSidebar(SIDEBAR_KEYS.EDITOR_PANEL)
+ }}
+ />
)
}
diff --git a/apps/studio/state/editor-panel-state.tsx b/apps/studio/state/editor-panel-state.tsx
index 167e33ef3b5..bff9268b6e8 100644
--- a/apps/studio/state/editor-panel-state.tsx
+++ b/apps/studio/state/editor-panel-state.tsx
@@ -6,13 +6,21 @@ type Template = {
content: string
}
+export type SqlError = {
+ error?: string
+ formattedError?: string
+ message?: string
+}
+
type EditorPanelState = {
value: string
templates: Template[]
- results: any[] | undefined
- error: any
+ results: Record<string, unknown>[] | undefined
+ error: SqlError | undefined
initialPrompt: string
onChange: ((value: string) => void) | undefined
+ activeSnippetId: string | null
+ pendingReset: boolean
}
const initialState: EditorPanelState = {
@@ -22,6 +30,8 @@ const initialState: EditorPanelState = {
error: undefined,
initialPrompt: '',
onChange: undefined,
+ activeSnippetId: null,
+ pendingReset: false,
}
export const editorPanelState = proxy({
@@ -35,15 +45,24 @@ export const editorPanelState = proxy({
setTemplates(templates: Template[]) {
editorPanelState.templates = templates
},
- setResults(results: any[] | undefined) {
+ setResults(results: Record<string, unknown>[] | undefined) {
editorPanelState.results = results
},
- setError(error: any) {
+ setError(error: SqlError | undefined) {
editorPanelState.error = error
},
setInitialPrompt(initialPrompt: string) {
editorPanelState.initialPrompt = initialPrompt
},
+ setActiveSnippetId(id: string | null) {
+ editorPanelState.activeSnippetId = id
+ },
+ openAsNew() {
+ editorPanelState.value = ''
+ editorPanelState.results = undefined
+ editorPanelState.error = undefined
+ editorPanelState.pendingReset = true
+ },
reset() {
Object.assign(editorPanelState, initialState)
},