Skip to content

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

Support persisting scroll position for SQL editor tabs (#35094)

Joshen Lim7969f157aa33
diff --git a/apps/studio/components/interfaces/SQLEditor/MonacoEditor.tsx b/apps/studio/components/interfaces/SQLEditor/MonacoEditor.tsx
index c9a5a04cf66..538a75b6c2a 100644
--- a/apps/studio/components/interfaces/SQLEditor/MonacoEditor.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/MonacoEditor.tsx
@@ -10,12 +10,12 @@ import { LOCAL_STORAGE_KEYS } from 'lib/constants'
import { useProfile } from 'lib/profile'
import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'
import { useSqlEditorV2StateSnapshot } from 'state/sql-editor-v2'
+import { makeActiveTabPermanent } from 'state/tabs'
import { cn } from 'ui'
import { Admonition } from 'ui-patterns'
import { untitledSnippetTitle } from './SQLEditor.constants'
import type { IStandaloneCodeEditor } from './SQLEditor.types'
import { createSqlSnippetSkeletonV2 } from './SQLEditor.utils'
-import { makeActiveTabPermanent } from 'state/tabs'
export type MonacoEditorProps = {
id: string
@@ -25,6 +25,7 @@ export type MonacoEditorProps = {
autoFocus?: boolean
executeQuery: () => void
onHasSelection: (value: boolean) => void
+ onMount?: (editor: IStandaloneCodeEditor) => void
onPrompt?: (value: {
selection: string
beforeSelection: string
@@ -43,6 +44,7 @@ const MonacoEditor = ({
executeQuery,
onHasSelection,
onPrompt,
+ onMount,
}: MonacoEditorProps) => {
const router = useRouter()
const { profile } = useProfile()
@@ -143,6 +145,8 @@ const MonacoEditor = ({
if (editor.getValue().length === 1) editor.setPosition({ lineNumber: 1, column: 2 })
editor.focus()
}
+
+ onMount?.(editor)
}
const debouncedSetSql = debounce((id, value) => snapV2.setSql(id, value), 1000)
diff --git a/apps/studio/components/interfaces/SQLEditor/RenameQueryModal.tsx b/apps/studio/components/interfaces/SQLEditor/RenameQueryModal.tsx
index 5956e1e1034..591f8a63c04 100644
--- a/apps/studio/components/interfaces/SQLEditor/RenameQueryModal.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/RenameQueryModal.tsx
@@ -13,7 +13,7 @@ import type { SqlSnippet } from 'data/content/sql-snippets-query'
import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
import { useSqlEditorV2StateSnapshot } from 'state/sql-editor-v2'
-import { createTabId, renameTab } from 'state/tabs'
+import { createTabId, updateTab } from 'state/tabs'
import { AiIconAnimation, Button, Form, Input, Modal } from 'ui'
import { useIsSQLEditorTabsEnabled } from '../App/FeaturePreview/FeaturePreviewContext'
import { subscriptionHasHipaaAddon } from '../Billing/Subscription/Subscription.utils'
@@ -111,7 +111,7 @@ const RenameQueryModal = ({
snapV2.renameSnippet({ id, name: nameInput, description: descriptionInput })
if (isSQLEditorTabsEnabled && ref) {
const tabId = createTabId('sql', { id })
- renameTab(ref, tabId, nameInput)
+ updateTab(ref, tabId, { label: nameInput })
}
toast.success('Successfully renamed snippet!')
if (onComplete) onComplete()
diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
index 8dc8ee9ef81..e518e86627f 100644
--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
@@ -36,6 +36,7 @@ import {
useGetImpersonatedRoleState,
} from 'state/role-impersonation-state'
import { getSqlEditorV2StateSnapshot, useSqlEditorV2StateSnapshot } from 'state/sql-editor-v2'
+import { createTabId, getTabsStore, updateTab } from 'state/tabs'
import {
Button,
DropdownMenu,
@@ -51,6 +52,7 @@ import {
TooltipTrigger,
cn,
} from 'ui'
+import { useSnapshot } from 'valtio'
import { subscriptionHasHipaaAddon } from '../Billing/Subscription/Subscription.utils'
import { useSqlEditorDiff, useSqlEditorPrompt } from './hooks'
import { RunQueryWarningModal } from './RunQueryWarningModal'
@@ -81,11 +83,14 @@ export const SQLEditor = () => {
const os = detectOS()
const router = useRouter()
const { ref, id: urlId } = useParams()
- const org = useSelectedOrganization()
+
const { profile } = useProfile()
- const queryClient = useQueryClient()
const project = useSelectedProject()
- const organization = useSelectedOrganization()
+ const org = useSelectedOrganization()
+
+ const queryClient = useQueryClient()
+ const store = getTabsStore(ref)
+ const tabs = useSnapshot(store)
const aiSnap = useAiAssistantStateSnapshot()
const snapV2 = useSqlEditorV2StateSnapshot()
const getImpersonatedRoleState = useGetImpersonatedRoleState()
@@ -111,6 +116,8 @@ export const SQLEditor = () => {
const editorRef = useRef<IStandaloneCodeEditor | null>(null)
const monacoRef = useRef<Monaco | null>(null)
const diffEditorRef = useRef<IStandaloneDiffEditor | null>(null)
+ const scrollTopRef = useRef<number>(0)
+
const [hasSelection, setHasSelection] = useState<boolean>(false)
const [lineHighlights, setLineHighlights] = useState<string[]>([])
const [isDiffEditorMounted, setIsDiffEditorMounted] = useState(false)
@@ -136,7 +143,7 @@ export const SQLEditor = () => {
useAddDefinitions(id, monacoRef.current)
/** React query data fetching */
- const { data: subscription } = useOrgSubscriptionQuery({ orgSlug: organization?.slug })
+ const { data: subscription } = useOrgSubscriptionQuery({ orgSlug: org?.slug })
const hasHipaaAddon = subscriptionHasHipaaAddon(subscription)
const { data: databases, isSuccess: isSuccessReadReplicas } = useReadReplicasQuery({
@@ -362,6 +369,19 @@ export const SQLEditor = () => {
[profile?.id, project?.id, ref, router, snapV2]
)
+ const onMount = (editor: IStandaloneCodeEditor) => {
+ const tabId = createTabId('sql', { id })
+ const tabData = tabs.tabsMap[tabId]
+
+ // [Joshen] Tiny timeout to give a bit of time for the content to load before scrolling
+ setTimeout(() => {
+ if (tabData?.metadata?.scrollTop) {
+ editor.setScrollTop(tabData.metadata.scrollTop)
+ }
+ }, 20)
+ editor.onDidScrollChange((e) => (scrollTopRef.current = e.scrollTop))
+ }
+
const onDebug = useCallback(async () => {
try {
const snippet = snapV2.snippets[id]
@@ -511,6 +531,12 @@ export const SQLEditor = () => {
closeDiff()
setPromptState((prev) => ({ ...prev, isOpen: false }))
}
+ return () => {
+ if (ref) {
+ const tabId = createTabId('sql', { id })
+ updateTab(ref, tabId, { scrollTop: scrollTopRef.current })
+ }
+ }
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [closeDiff, id])
@@ -718,6 +744,7 @@ export const SQLEditor = () => {
monacoRef={monacoRef}
executeQuery={executeQuery}
onHasSelection={setHasSelection}
+ onMount={onMount}
onPrompt={({
selection,
beforeSelection,
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
index 38661ec6a5c..27d6664959e 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
@@ -25,7 +25,7 @@ import { getTables } from 'data/tables/tables-query'
import { useUrlState } from 'hooks/ui/useUrlState'
import { useGetImpersonatedRoleState } from 'state/role-impersonation-state'
import { useTableEditorStateSnapshot } from 'state/table-editor'
-import { createTabId, renameTab } from 'state/tabs'
+import { createTabId, updateTab } from 'state/tabs'
import type { Dictionary } from 'types'
import { SonnerProgress } from 'ui'
import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
@@ -489,7 +489,7 @@ const SidePanelEditor = ({
if (isTableEditorTabsEnabled && ref && payload.name) {
// [Joshen] Only table entities can be updated via the dashboard
const tabId = createTabId(ENTITY_TYPE.TABLE, { id: selectedTable.id })
- renameTab(ref, tabId, payload.name)
+ updateTab(ref, tabId, { label: payload.name })
}
toast.success(`Successfully updated ${table.name}!`, { id: toastId })
}
diff --git a/apps/studio/state/tabs.ts b/apps/studio/state/tabs.ts
index 7b3b50755f0..cae1ed4fa49 100644
--- a/apps/studio/state/tabs.ts
+++ b/apps/studio/state/tabs.ts
@@ -27,6 +27,7 @@ export interface Tab {
name?: string // Optional name of the entity represented by the tab
tableId?: number // Optional ID of the table associated with the tab
sqlId?: string // Optional ID of the SQL query associated with the tab
+ scrollTop?: number // Optional scroll top of the tab (Currently just for SQL query)
}
isPreview?: boolean // Optional flag indicating if the tab is in preview mode
createdAt?: Date // Optional timestamp for when the tab was created
@@ -143,7 +144,6 @@ export const addTab = (ref: string | undefined, tab: Tab) => {
// this is used for removing tabs from the localstorage state
// for handling a manual tab removal with a close action, use handleTabClose()
export const removeTab = (ref: string | undefined, id: string) => {
- console.log('removeTab')
const store = getTabsStore(ref)
const idx = store.openTabs.indexOf(id)
store.openTabs = store.openTabs.filter((tabId) => tabId !== id)
@@ -165,10 +165,20 @@ export const removeTabs = (ref: string | undefined, ids: string[]) => {
ids.forEach((id) => removeTab(ref, id))
}
-export const renameTab = (ref: string, id: string, name: string) => {
+export const updateTab = (
+ ref: string,
+ id: string,
+ updates: { label?: string; scrollTop?: number }
+) => {
const store = getTabsStore(ref)
+
if (!!store.tabsMap[id]) {
- store.tabsMap[id].label = name
+ if ('label' in updates) {
+ store.tabsMap[id].label = updates.label
+ }
+ if ('scrollTop' in updates && store.tabsMap[id].metadata) {
+ store.tabsMap[id].metadata.scrollTop = updates.scrollTop
+ }
}
}