Skip to content

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

refactor(studio): extract useSnippetEditor from MonacoEditor (#47500)

Charis7c1ea30e43cf
diff --git a/apps/studio/components/interfaces/SQLEditor/MonacoEditor.tsx b/apps/studio/components/interfaces/SQLEditor/MonacoEditor.tsx
index 7166f686087..07f140c3bbc 100644
--- a/apps/studio/components/interfaces/SQLEditor/MonacoEditor.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/MonacoEditor.tsx
@@ -1,28 +1,20 @@
import { Monaco, OnMount } from '@monaco-editor/react'
-import { useDebounce } from '@uidotdev/usehooks'
-import { LOCAL_STORAGE_KEYS, useParams } from 'common'
+import { LOCAL_STORAGE_KEYS } from 'common'
import { noop } from 'lodash'
-import { useRouter } from 'next/router'
-import { RefObject, useEffect, useRef, useState } from 'react'
+import { RefObject, useRef } from 'react'
import { Admonition } from 'ui-patterns/admonition'
import type { IStandaloneCodeEditor } from './SQLEditor.types'
-import { createSqlSnippetSkeletonV2 } from './SQLEditor.utils'
+import { useSnippetEditor } from './useSnippetEditor'
import { SIDEBAR_KEYS } from '@/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'
import { getEditorSelectionParts } from '@/components/ui/AIEditor/utils'
import { CodeEditor } from '@/components/ui/CodeEditor/CodeEditor'
import { useLocalStorageQuery } from '@/hooks/misc/useLocalStorage'
-import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
-import { useProfile } from '@/lib/profile'
import { useAiAssistantStateSnapshot } from '@/state/ai-assistant-state'
import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
import { useIsShortcutEnabled } from '@/state/shortcuts/useIsShortcutEnabled'
import { useSidebarManagerSnapshot } from '@/state/sidebar-manager-state'
-import { useSqlEditorV2StateSnapshot } from '@/state/sql-editor-v2'
-import { wasNeverPersisted } from '@/state/sql-editor/sql-editor-lifecycle'
-import { canEditSnippet } from '@/state/sql-editor/sql-editor-rules'
import { useSqlEditorSaveCoordinator } from '@/state/sql-editor/sql-editor-save-coordinator'
-import { useTabsStateSnapshot } from '@/state/tabs'
export type MonacoEditorProps = {
id: string
@@ -63,13 +55,6 @@ export const MonacoEditor = ({
onPrompt,
onMount,
}: MonacoEditorProps) => {
- const router = useRouter()
- const { profile } = useProfile()
- const { ref, content } = useParams()
- const { data: project } = useSelectedProjectQuery()
-
- const snapV2 = useSqlEditorV2StateSnapshot()
- const tabsSnap = useTabsStateSnapshot()
const aiSnap = useAiAssistantStateSnapshot()
const { openSidebar, toggleSidebar } = useSidebarManagerSnapshot()
@@ -78,11 +63,14 @@ export const MonacoEditor = ({
true
)
- const [value, setValue] = useState('')
- const debouncedValue = useDebounce(value, 1000)
+ const { snippet, disableEdit, handleEditorChange } = useSnippetEditor({ id, snippetName })
- const snippet = snapV2.snippets[id]
- const disableEdit = !!snippet && !canEditSnippet(snippet.snippet, profile?.id)
+ // The Monaco save action is registered once on mount, but `snippet` starts
+ // undefined for a new/deep-linked snippet and is only created on first edit.
+ // Read it through a ref so Cmd/Ctrl+S sees the latest value, not the stale
+ // mount-time closure.
+ const snippetRef = useRef(snippet)
+ snippetRef.current = snippet
const executeExplainQueryRef = useRef(executeExplainQuery)
executeExplainQueryRef.current = executeExplainQuery
@@ -147,7 +135,8 @@ export const MonacoEditor = ({
contextMenuGroupId: 'operation',
contextMenuOrder: 0,
run: () => {
- if (snippet) requestSaveRef.current(snippet.snippet.id)
+ const currentSnippet = snippetRef.current
+ if (currentSnippet) requestSaveRef.current(currentSnippet.snippet.id)
},
})
@@ -215,46 +204,6 @@ export const MonacoEditor = ({
onMount?.(editor)
}
- function handleEditorChange(value: string | undefined) {
- tabsSnap.makeActiveTabPermanent()
- if (id && value) {
- if (!snippet && ref && profile !== undefined && project !== undefined) {
- const snippet = createSqlSnippetSkeletonV2({
- idOverride: id,
- name: snippetName,
- sql: value,
- owner_id: profile?.id,
- project_id: project?.id,
- })
- snapV2.addSnippet({ projectRef: ref, snippet })
- // When the editor was seeded from a `content` deep-link, replace rather
- // than push. The caller navigated to `/sql/new?content=...` (a long,
- // one-shot URL); replacing collapses it out of history so Back returns to
- // the originating page instead of a wasted step that re-seeds the snippet.
- if (router.query.content !== undefined) {
- router.replace(`/project/${ref}/sql/${snippet.id}`, undefined, { shallow: true })
- } else {
- router.push(`/project/${ref}/sql/${snippet.id}`, undefined, { shallow: true })
- }
- }
- setValue(value)
- }
- }
-
- useEffect(() => {
- if (debouncedValue.length > 0 && snippet) {
- const shouldInvalidate = wasNeverPersisted(snippet.snippet.status)
- snapV2.setSql({ id, sql: value, shouldInvalidate })
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [debouncedValue])
-
- // if an SQL query is passed by the content parameter, set the editor value to its content. This
- // is usually used for sending the user to SQL editor from other pages with SQL.
- useEffect(() => {
- if (content && content.length > 0) handleEditorChange(content)
- }, [])
-
return (
<>
{disableEdit && (
diff --git a/apps/studio/components/interfaces/SQLEditor/useSnippetEditor.ts b/apps/studio/components/interfaces/SQLEditor/useSnippetEditor.ts
new file mode 100644
index 00000000000..adf60851085
--- /dev/null
+++ b/apps/studio/components/interfaces/SQLEditor/useSnippetEditor.ts
@@ -0,0 +1,81 @@
+import { useParams } from 'common'
+import { useRouter } from 'next/router'
+import { useEffect, useEffectEvent } from 'react'
+
+import { createSqlSnippetSkeletonV2 } from './SQLEditor.utils'
+import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
+import { useProfile } from '@/lib/profile'
+import { useSqlEditorV2StateSnapshot } from '@/state/sql-editor-v2'
+import { wasNeverPersisted } from '@/state/sql-editor/sql-editor-lifecycle'
+import { canEditSnippet } from '@/state/sql-editor/sql-editor-rules'
+import { useTabsStateSnapshot } from '@/state/tabs'
+
+/**
+ * Owns the editing lifecycle of a single SQL snippet: creating the snippet in
+ * the store on first edit (and routing to its URL), writing changes back to the
+ * store via `setSql`, and seeding the editor from a `?content=` deep link.
+ *
+ * Edits are written to the store synchronously on every change; debouncing the
+ * actual persistence is the save mechanism's job (see `createSaveMechanism`), so
+ * the store — and therefore the snippet's dirty status — always reflects the
+ * latest edit immediately.
+ *
+ * Extracted from `MonacoEditor` so that component stays a thin editor shell.
+ */
+export function useSnippetEditor({ id, snippetName }: { id: string; snippetName: string }) {
+ const router = useRouter()
+ const { profile } = useProfile()
+ const { ref, content } = useParams()
+ const { data: project } = useSelectedProjectQuery()
+
+ const snapV2 = useSqlEditorV2StateSnapshot()
+ const tabsSnap = useTabsStateSnapshot()
+
+ const snippet = snapV2.snippets[id]
+ const disableEdit = !!snippet && !canEditSnippet(snippet.snippet, profile?.id)
+
+ function handleEditorChange(value: string | undefined) {
+ tabsSnap.makeActiveTabPermanent()
+ if (!id || !value) return
+
+ if (!snippet && ref && profile !== undefined && project !== undefined) {
+ const newSnippet = createSqlSnippetSkeletonV2({
+ idOverride: id,
+ name: snippetName,
+ sql: value,
+ owner_id: profile?.id,
+ project_id: project?.id,
+ })
+ snapV2.addSnippet({ projectRef: ref, snippet: newSnippet })
+ // When the editor was seeded from a `content` deep-link, replace rather
+ // than push. The caller navigated to `/sql/new?content=...` (a long,
+ // one-shot URL); replacing collapses it out of history so Back returns to
+ // the originating page instead of a wasted step that re-seeds the snippet.
+ if (router.query.content !== undefined) {
+ router.replace(`/project/${ref}/sql/${newSnippet.id}`, undefined, { shallow: true })
+ } else {
+ router.push(`/project/${ref}/sql/${newSnippet.id}`, undefined, { shallow: true })
+ }
+ }
+
+ // A snippet that has never been persisted needs the snippet/folder lists
+ // invalidated so it shows up in the sidebar. If `snippet` was undefined at
+ // render we just created one above (status 'new'), which always qualifies.
+ const shouldInvalidate = snippet ? wasNeverPersisted(snippet.snippet.status) : true
+ snapV2.setSql({ id, sql: value, shouldInvalidate })
+ }
+
+ // if an SQL query is passed by the content parameter, set the editor value to its content. This
+ // is usually used for sending the user to SQL editor from other pages with SQL.
+ const seedFromContentParam = useEffectEvent(() => {
+ if (content && content.length > 0) handleEditorChange(content)
+ })
+ useEffect(() => {
+ seedFromContentParam()
+ // The useEffectEvent return is stable and must not be a dependency; this
+ // disable can go once our eslint version understands useEffectEvent.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [])
+
+ return { snippet, disableEdit, handleEditorChange }
+}
diff --git a/apps/studio/state/sql-editor/sql-editor-lifecycle.test.ts b/apps/studio/state/sql-editor/sql-editor-lifecycle.test.ts
index 45419f50b7b..6e6def1faf8 100644
--- a/apps/studio/state/sql-editor/sql-editor-lifecycle.test.ts
+++ b/apps/studio/state/sql-editor/sql-editor-lifecycle.test.ts
@@ -8,6 +8,7 @@ import {
isNewFolder,
isSaveFailed,
isSaving,
+ statusOnEdit,
statusOnSaveError,
statusOnSaveStart,
statusOnSaveSuccess,
@@ -108,6 +109,24 @@ describe('statusOnSaveError', () => {
})
})
+describe('statusOnEdit', () => {
+ it('marks a persisted, clean snippet as unsaved', () => {
+ expect(statusOnEdit('saved')).toBe('unsaved')
+ })
+
+ it('leaves every already-dirty or in-flight status unchanged', () => {
+ for (const status of [...NEVER_PERSISTED, 'unsaved', 'saving', 'save_failed'] as const) {
+ expect(statusOnEdit(status)).toBe(status)
+ }
+ })
+
+ it('keeps hasUnsavedChanges true after an edit', () => {
+ for (const status of [...NEVER_PERSISTED, ...PERSISTED] as const) {
+ expect(hasUnsavedChanges(statusOnEdit(status))).toBe(true)
+ }
+ })
+})
+
describe('lifecycle round trips', () => {
it('new snippet: first save succeeds then a re-save succeeds', () => {
let status: SnippetStatus = 'new'
diff --git a/apps/studio/state/sql-editor/sql-editor-lifecycle.ts b/apps/studio/state/sql-editor/sql-editor-lifecycle.ts
index cc3013aae78..190231b1fb7 100644
--- a/apps/studio/state/sql-editor/sql-editor-lifecycle.ts
+++ b/apps/studio/state/sql-editor/sql-editor-lifecycle.ts
@@ -48,6 +48,18 @@ export function statusOnSaveError(status: SnippetStatus | undefined): SnippetSta
return wasNeverPersisted(status) ? 'new_save_failed' : 'save_failed'
}
+/**
+ * Transition when the snippet is edited locally. A persisted-and-clean snippet
+ * becomes 'unsaved' so its dirty state is durable immediately (rather than only
+ * once the debounced save begins). Every other status is already dirty or
+ * in-flight — the never-persisted family, a save in progress, or a failed
+ * save — and is left unchanged so the persistence and progress axes are
+ * preserved.
+ */
+export function statusOnEdit(status: SnippetStatus): SnippetStatus {
+ return status === 'saved' ? 'unsaved' : status
+}
+
/**
* The lifecycle of a folder in the SQL editor nav, as a single set of
* mutually-exclusive states. Like SnippetStatus, this collapses two orthogonal
diff --git a/apps/studio/state/sql-editor/sql-editor-state.ts b/apps/studio/state/sql-editor/sql-editor-state.ts
index 56c527876a0..52e79e2252d 100644
--- a/apps/studio/state/sql-editor/sql-editor-state.ts
+++ b/apps/studio/state/sql-editor/sql-editor-state.ts
@@ -4,7 +4,7 @@ import { toast } from 'sonner'
import { proxy, snapshot, useSnapshot } from 'valtio'
import { devtools, proxyMap } from 'valtio/utils'
-import { folderStatusOnSaveStart, isNewFolder } from './sql-editor-lifecycle'
+import { folderStatusOnSaveStart, isNewFolder, statusOnEdit } from './sql-editor-lifecycle'
import { sqlEditorSessionState } from './sql-editor-session-state'
import type { StateSnippet, StateSnippetFolder } from './types'
import type { SnippetWithContent } from '@/data/content/sql-folders-query'
@@ -110,6 +110,10 @@ export const sqlEditorState = proxy({
let snippet = sqlEditorState.snippets[id]?.snippet
if (snippet?.content) {
snippet.content.unchecked_sql = untrustedSql(sql)
+ // Mark dirty immediately so `status` (not the transient needsSaving queue)
+ // is the durable source of truth for unsaved changes, even before the
+ // debounced save begins.
+ snippet.status = statusOnEdit(snippet.status)
sqlEditorState.needsSaving.set(id, shouldInvalidate)
}
},