Skip to content

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

Joshen/fe 3651 deprecate monacoeditor from grid folder to use codeeditor (#47179)

Joshen Limf2e20eac344e
diff --git a/apps/studio/components/grid/components/common/MonacoEditor.tsx b/apps/studio/components/grid/components/common/MonacoEditor.tsx
deleted file mode 100644
index d5e8c0dc827..00000000000
--- a/apps/studio/components/grid/components/common/MonacoEditor.tsx
+++ /dev/null
@@ -1,75 +0,0 @@
-import Editor from '@monaco-editor/react'
-
-type MonacoEditorProps = {
- width?: string | number | undefined
- height?: string | number | undefined
- value?: string | undefined
- language?: string | undefined
- readOnly?: boolean
- onChange: (value: string | undefined) => void
- onMount?: (editor: any) => void
-}
-
-export const MonacoEditor = ({
- width,
- height,
- value,
- language,
- readOnly = false,
- onChange,
- onMount,
-}: MonacoEditorProps) => {
- function handleEditorOnMount(editor: any) {
- // add margin above first line
- editor.changeViewZones((accessor: any) => {
- accessor.addZone({
- afterLineNumber: 0,
- heightInPx: 4,
- domNode: document.createElement('div'),
- })
- })
-
- // move cursor to the end of document
- const model = editor.getModel()
- const position = model.getPositionAt(value?.length)
- editor.setPosition(position)
-
- // auto focus on mount
- setTimeout(() => {
- editor?.focus()
- }, 0)
-
- if (onMount) onMount(editor)
- }
-
- return (
- <Editor
- width={width}
- height={height || '200px'}
- theme="supabase"
- wrapperProps={{
- className: 'grid-monaco-editor-container',
- }}
- className="grid-monaco-editor"
- defaultLanguage={language || 'plaintext'}
- defaultValue={value}
- onChange={onChange}
- onMount={handleEditorOnMount}
- options={{
- readOnly,
- tabSize: 2,
- fontSize: 13,
- minimap: {
- enabled: false,
- },
- glyphMargin: false,
- folding: false,
- lineNumbers: 'off',
- lineNumbersMinChars: 0,
- scrollBeyondLastLine: false,
- wordWrap: 'on',
- unusualLineTerminators: 'off',
- }}
- />
- )
-}
diff --git a/apps/studio/components/grid/components/editor/JsonEditor.tsx b/apps/studio/components/grid/components/editor/JsonEditor.tsx
index 1c9012cfadb..21c6224df7a 100644
--- a/apps/studio/components/grid/components/editor/JsonEditor.tsx
+++ b/apps/studio/components/grid/components/editor/JsonEditor.tsx
@@ -13,11 +13,11 @@ import {
} from 'ui'
import { BlockKeys } from '../common/BlockKeys'
-import { MonacoEditor } from '../common/MonacoEditor'
import { NullValue } from '../common/NullValue'
import { TruncatedWarningOverlay } from './TruncatedWarningOverlay'
import { useIsQueueOperationsEnabled } from '@/components/interfaces/Account/Preferences/useDashboardSettings'
import { isValueTruncated } from '@/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/RowEditor.utils'
+import { CodeEditor } from '@/components/ui/CodeEditor/CodeEditor'
import { useTableEditorQuery } from '@/data/table-editor/table-editor-query'
import { isTableLike } from '@/data/table-editor/table-editor-types'
import { useGetCellValueMutation } from '@/data/table-rows/get-cell-value-mutation'
@@ -174,16 +174,24 @@ export const JsonEditor = <TRow, TSummaryRow = unknown>({
<PopoverContent side="bottom" align="start" sideOffset={-35} className="rounded-none p-0">
{isTruncated && !isSuccess ? (
<div className="flex items-center justify-center flex-col relative">
- <MonacoEditor readOnly onChange={() => {}} value={value ?? ''} language="markdown" />
+ <CodeEditor
+ isReadOnly
+ hideLineNumbers
+ language="plaintext"
+ value={value ?? ''}
+ className="h-[200px]"
+ />
<TruncatedWarningOverlay isLoading={isPending} loadFullValue={loadFullValue} />
</div>
) : (
<BlockKeys value={value} onEscape={cancelChanges} onEnter={saveChanges}>
- <MonacoEditor
- value={value ?? ''}
+ <CodeEditor
+ hideLineNumbers
+ isReadOnly={!isEditable}
language="json"
- readOnly={!isEditable}
- onChange={onChange}
+ value={value ?? ''}
+ onInputChange={onChange}
+ className="h-[200px] border-b"
/>
<div className="flex items-start justify-between p-2 bg-surface-200 gap-x-2">
{isEditable && (
diff --git a/apps/studio/components/grid/components/editor/TextEditor.tsx b/apps/studio/components/grid/components/editor/TextEditor.tsx
index 59f37c33a1b..a3931a74654 100644
--- a/apps/studio/components/grid/components/editor/TextEditor.tsx
+++ b/apps/studio/components/grid/components/editor/TextEditor.tsx
@@ -17,11 +17,11 @@ import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
import { BlockKeys } from '../common/BlockKeys'
import { EmptyValue } from '../common/EmptyValue'
-import { MonacoEditor } from '../common/MonacoEditor'
import { NullValue } from '../common/NullValue'
import { TruncatedWarningOverlay } from './TruncatedWarningOverlay'
import { useTableRowOperations } from '@/components/grid/hooks/useTableRowOperations'
import { isValueTruncated } from '@/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/RowEditor.utils'
+import { CodeEditor } from '@/components/ui/CodeEditor/CodeEditor'
import { useTableEditorQuery } from '@/data/table-editor/table-editor-query'
import { isTableLike } from '@/data/table-editor/table-editor-types'
import { useGetCellValueMutation } from '@/data/table-rows/get-cell-value-mutation'
@@ -129,7 +129,13 @@ export const TextEditor = <TRow, TSummaryRow = unknown>({
<PopoverContent className="rounded-none p-0" side="bottom" align="start" sideOffset={-35}>
{isTruncated && !isSuccess ? (
<div className="flex items-center justify-center flex-col relative">
- <MonacoEditor readOnly onChange={() => {}} value={value ?? ''} language="markdown" />
+ <CodeEditor
+ hideLineNumbers
+ isReadOnly
+ language="plaintext"
+ value={value ?? ''}
+ className="h-[200px]"
+ />
<TruncatedWarningOverlay isLoading={isPending} loadFullValue={loadFullValue} />
</div>
) : (
@@ -139,7 +145,15 @@ export const TextEditor = <TRow, TSummaryRow = unknown>({
onEnter={saveChanges}
ignoreOutsideClicks={isConfirmNextModalOpen}
>
- <MonacoEditor value={value ?? ''} readOnly={!isEditable} onChange={onChange} />
+ <CodeEditor
+ hideLineNumbers
+ isReadOnly={!isEditable}
+ language="plaintext"
+ value={value ?? ''}
+ onInputChange={onChange}
+ className="h-[200px] border-b"
+ />
+
{isEditable && (
<div className="flex items-start justify-between p-2 bg-surface-200 space-x-2">
<div className="space-y-1">
diff --git a/apps/studio/components/interfaces/Auth/Hooks/CreateHookSheet.tsx b/apps/studio/components/interfaces/Auth/Hooks/CreateHookSheet.tsx
index 24055a99f51..c1dbe06022e 100644
--- a/apps/studio/components/interfaces/Auth/Hooks/CreateHookSheet.tsx
+++ b/apps/studio/components/interfaces/Auth/Hooks/CreateHookSheet.tsx
@@ -35,10 +35,10 @@ import { Hook, HOOK_DEFINITION_TITLE, HOOKS_DEFINITIONS } from './hooks.constant
import { extractMethod, getRevokePermissionStatements, isValidHook } from './hooks.utils'
import { convertArgumentTypes } from '@/components/interfaces/Database/Functions/Functions.utils'
import { DiscardChangesConfirmationDialog } from '@/components/ui-patterns/Dialogs/DiscardChangesConfirmationDialog'
-import CodeEditor from '@/components/ui/CodeEditor/CodeEditor'
+import { CodeEditor } from '@/components/ui/CodeEditor/CodeEditor'
import { DocsButton } from '@/components/ui/DocsButton'
import FunctionSelector from '@/components/ui/FunctionSelector'
-import SchemaSelector from '@/components/ui/SchemaSelector'
+import { SchemaSelector } from '@/components/ui/SchemaSelector'
import { AuthConfigResponse } from '@/data/auth/auth-config-query'
import { useAuthHooksUpdateMutation } from '@/data/auth/auth-hooks-update-mutation'
import { executeSql } from '@/data/sql/execute-sql-mutation'
diff --git a/apps/studio/components/interfaces/Auth/Hooks/HooksListing.tsx b/apps/studio/components/interfaces/Auth/Hooks/HooksListing.tsx
index 8f0ad3fa09a..a40b77793d1 100644
--- a/apps/studio/components/interfaces/Auth/Hooks/HooksListing.tsx
+++ b/apps/studio/components/interfaces/Auth/Hooks/HooksListing.tsx
@@ -20,8 +20,8 @@ import { CreateHookSheet } from './CreateHookSheet'
import { HookCard } from './HookCard'
import { Hook, HOOKS_DEFINITIONS } from './hooks.constants'
import { extractMethod, getRevokePermissionStatements, isValidHook } from './hooks.utils'
-import AlertError from '@/components/ui/AlertError'
-import CodeEditor from '@/components/ui/CodeEditor/CodeEditor'
+import { AlertError } from '@/components/ui/AlertError'
+import { CodeEditor } from '@/components/ui/CodeEditor/CodeEditor'
import { useAuthConfigQuery } from '@/data/auth/auth-config-query'
import { useAuthHooksUpdateMutation } from '@/data/auth/auth-hooks-update-mutation'
import { executeSql } from '@/data/sql/execute-sql-mutation'
diff --git a/apps/studio/components/interfaces/Auth/RLSTester/InferredSQLViewer.tsx b/apps/studio/components/interfaces/Auth/RLSTester/InferredSQLViewer.tsx
index 7174f586891..ecdaf4b6b80 100644
--- a/apps/studio/components/interfaces/Auth/RLSTester/InferredSQLViewer.tsx
+++ b/apps/studio/components/interfaces/Auth/RLSTester/InferredSQLViewer.tsx
@@ -2,7 +2,7 @@ import { UntrustedSqlFragment } from '@supabase/pg-meta'
import { Loader2 } from 'lucide-react'
import { Badge, Tooltip, TooltipContent, TooltipTrigger } from 'ui'
-import CodeEditor from '@/components/ui/CodeEditor/CodeEditor'
+import { CodeEditor } from '@/components/ui/CodeEditor/CodeEditor'
export const InferredSQLViewer = ({
sql,
diff --git a/apps/studio/components/interfaces/Database/Functions/CreateFunction/FunctionEditor.tsx b/apps/studio/components/interfaces/Database/Functions/CreateFunction/FunctionEditor.tsx
index b76fbeff29b..5543dc30f6a 100644
--- a/apps/studio/components/interfaces/Database/Functions/CreateFunction/FunctionEditor.tsx
+++ b/apps/studio/components/interfaces/Database/Functions/CreateFunction/FunctionEditor.tsx
@@ -1,7 +1,7 @@
import { Maximize2, Minimize2 } from 'lucide-react'
import { Button, cn, FormControl, Tooltip, TooltipContent, TooltipTrigger } from 'ui'
-import CodeEditor from '@/components/ui/CodeEditor/CodeEditor'
+import { CodeEditor } from '@/components/ui/CodeEditor/CodeEditor'
export const FunctionEditor = ({
field,
diff --git a/apps/studio/components/interfaces/Database/Indexes/CreateIndexSidePanel.tsx b/apps/studio/components/interfaces/Database/Indexes/CreateIndexSidePanel.tsx
index eb5214dd40b..42f7570cccc 100644
--- a/apps/studio/components/interfaces/Database/Indexes/CreateIndexSidePanel.tsx
+++ b/apps/studio/components/interfaces/Database/Indexes/CreateIndexSidePanel.tsx
@@ -46,7 +46,7 @@ import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'
import * as z from 'zod'
import { INDEX_TYPES } from './Indexes.constants'
-import CodeEditor from '@/components/ui/CodeEditor/CodeEditor'
+import { CodeEditor } from '@/components/ui/CodeEditor/CodeEditor'
import { DocsButton } from '@/components/ui/DocsButton'
import { useDatabaseIndexCreateMutation } from '@/data/database-indexes/index-create-mutation'
import { useSchemasQuery } from '@/data/database/schemas-query'
diff --git a/apps/studio/components/interfaces/Database/Indexes/Indexes.tsx b/apps/studio/components/interfaces/Database/Indexes/Indexes.tsx
index 878f27a57c7..f0c15d7c805 100644
--- a/apps/studio/components/interfaces/Database/Indexes/Indexes.tsx
+++ b/apps/studio/components/interfaces/Database/Indexes/Indexes.tsx
@@ -22,7 +22,7 @@ import { GenericSkeletonLoader, ShimmeringLoader } from 'ui-patterns/ShimmeringL
import { ProtectedSchemaWarning } from '../ProtectedSchemaWarning'
import { CreateIndexSidePanel } from './CreateIndexSidePanel'
import AlertError from '@/components/ui/AlertError'
-import CodeEditor from '@/components/ui/CodeEditor/CodeEditor'
+import { CodeEditor } from '@/components/ui/CodeEditor/CodeEditor'
import SchemaSelector from '@/components/ui/SchemaSelector'
import { Shortcut } from '@/components/ui/Shortcut'
import { useDatabaseIndexDeleteMutation } from '@/data/database-indexes/index-delete-mutation'
diff --git a/apps/studio/components/interfaces/Database/Migrations/Migrations.tsx b/apps/studio/components/interfaces/Database/Migrations/Migrations.tsx
index cc4bfc24aa4..df17cf08a7e 100644
--- a/apps/studio/components/interfaces/Database/Migrations/Migrations.tsx
+++ b/apps/studio/components/interfaces/Database/Migrations/Migrations.tsx
@@ -22,7 +22,7 @@ import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'
import { MigrationsEmptyState } from './MigrationsEmptyState'
import { SupportLink } from '@/components/interfaces/Support/SupportLink'
-import CodeEditor from '@/components/ui/CodeEditor/CodeEditor'
+import { CodeEditor } from '@/components/ui/CodeEditor/CodeEditor'
import { InlineLink } from '@/components/ui/InlineLink'
import { DatabaseMigration, useMigrationsQuery } from '@/data/database/migrations-query'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
diff --git a/apps/studio/components/interfaces/Integrations/CronJobs/SqlSnippetSection.tsx b/apps/studio/components/interfaces/Integrations/CronJobs/SqlSnippetSection.tsx
index a932220cfb6..39fb3efebd8 100644
--- a/apps/studio/components/interfaces/Integrations/CronJobs/SqlSnippetSection.tsx
+++ b/apps/studio/components/interfaces/Integrations/CronJobs/SqlSnippetSection.tsx
@@ -3,7 +3,7 @@ import { FormField, SheetSection } from 'ui'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
import { CreateCronJobForm } from './CreateCronJobSheet/CreateCronJobSheet.constants'
-import CodeEditor from '@/components/ui/CodeEditor/CodeEditor'
+import { CodeEditor } from '@/components/ui/CodeEditor/CodeEditor'
interface SqlSnippetSectionProps {
form: UseFormReturn<CreateCronJobForm>
diff --git a/apps/studio/components/interfaces/Integrations/Queues/SingleQueue/MessageDetailsPanel.tsx b/apps/studio/components/interfaces/Integrations/Queues/SingleQueue/MessageDetailsPanel.tsx
index a3cac384e40..ef5215d7303 100644
--- a/apps/studio/components/interfaces/Integrations/Queues/SingleQueue/MessageDetailsPanel.tsx
+++ b/apps/studio/components/interfaces/Integrations/Queues/SingleQueue/MessageDetailsPanel.tsx
@@ -1,7 +1,7 @@
import { useEscapeKeydown } from '@radix-ui/react-use-escape-keydown'
import { useParams } from 'common'
import dayjs from 'dayjs'
-import { isNil, noop } from 'lodash'
+import { isNil } from 'lodash'
import { Archive, Clock12, Trash2, X } from 'lucide-react'
import { useState } from 'react'
import {
@@ -14,8 +14,8 @@ import {
TabsTrigger_Shadcn_,
} from 'ui'
-import { MonacoEditor } from '@/components/grid/components/common/MonacoEditor'
import { RowAction, RowData } from '@/components/interfaces/Auth/Users/UserOverview'
+import { CodeEditor } from '@/components/ui/CodeEditor/CodeEditor'
import { useDatabaseQueueMessageArchiveMutation } from '@/data/database-queues/database-queue-messages-archive-mutation'
import { useDatabaseQueueMessageDeleteMutation } from '@/data/database-queues/database-queue-messages-delete-mutation'
import { PostgresQueueMessage } from '@/data/database-queues/database-queue-messages-infinite-query'
@@ -123,15 +123,15 @@ export const MessageDetailsPanel = ({
/>
<RowData property="Retries" value={`${selectedMessage.read_ct}`} />
- <div>
- <h3 className="text-foreground-light py-1">Payload</h3>
- <MonacoEditor
- key={selectedMessage.msg_id}
- onChange={noop}
- width="100%"
+ <div className="mt-2">
+ <h4 className="text-foreground-light py-1">Payload</h4>
+ <CodeEditor
+ isReadOnly
+ hideLineNumbers
+ id={selectedMessage.msg_id.toString()}
value={jsonString || 'NULL'}
language="json"
- readOnly
+ className="h-[200px]"
/>
</div>
</div>
diff --git a/apps/studio/components/interfaces/Integrations/Queues/SingleQueue/SendMessageModal.tsx b/apps/studio/components/interfaces/Integrations/Queues/SingleQueue/SendMessageModal.tsx
index f7d5ff2653d..53a95fee327 100644
--- a/apps/studio/components/interfaces/Integrations/Queues/SingleQueue/SendMessageModal.tsx
+++ b/apps/studio/components/interfaces/Integrations/Queues/SingleQueue/SendMessageModal.tsx
@@ -23,7 +23,7 @@ import {
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
import z from 'zod'
-import CodeEditor from '@/components/ui/CodeEditor/CodeEditor'
+import { CodeEditor } from '@/components/ui/CodeEditor/CodeEditor'
import { useDatabaseQueueMessageSendMutation } from '@/data/database-queues/database-queue-messages-send-mutation'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
diff --git a/apps/studio/components/interfaces/Realtime/Inspector/SendMessageModal.tsx b/apps/studio/components/interfaces/Realtime/Inspector/SendMessageModal.tsx
index 7f00e199f5b..24d0b79b232 100644
--- a/apps/studio/components/interfaces/Realtime/Inspector/SendMessageModal.tsx
+++ b/apps/studio/components/interfaces/Realtime/Inspector/SendMessageModal.tsx
@@ -12,7 +12,7 @@ import {
} from 'ui'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
-import CodeEditor from '@/components/ui/CodeEditor/CodeEditor'
+import { CodeEditor } from '@/components/ui/CodeEditor/CodeEditor'
import { tryParseJson } from '@/lib/helpers'
interface SendMessageModalProps {
diff --git a/apps/studio/components/interfaces/SQLEditor/MonacoEditor.tsx b/apps/studio/components/interfaces/SQLEditor/MonacoEditor.tsx
index bc1c42f030d..70b246d9847 100644
--- a/apps/studio/components/interfaces/SQLEditor/MonacoEditor.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/MonacoEditor.tsx
@@ -1,16 +1,16 @@
-import Editor, { Monaco, OnMount } from '@monaco-editor/react'
+import { Monaco, OnMount } from '@monaco-editor/react'
import { useDebounce } from '@uidotdev/usehooks'
import { LOCAL_STORAGE_KEYS, useParams } from 'common'
+import { noop } from 'lodash'
import { useRouter } from 'next/router'
-import { MutableRefObject, useEffect, useRef, useState } from 'react'
-import { cn } from 'ui'
+import { RefObject, useEffect, useRef, useState } from 'react'
import { Admonition } from 'ui-patterns'
-import { useSetCommandMenuOpen } from 'ui-patterns/CommandMenu'
import type { IStandaloneCodeEditor } from './SQLEditor.types'
import { createSqlSnippetSkeletonV2 } from './SQLEditor.utils'
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'
@@ -25,8 +25,8 @@ export type MonacoEditorProps = {
id: string
snippetName: string
className?: string
- editorRef: MutableRefObject<IStandaloneCodeEditor | null>
- monacoRef: MutableRefObject<Monaco | null>
+ editorRef: RefObject<IStandaloneCodeEditor | null>
+ monacoRef: RefObject<Monaco | null>
autoFocus?: boolean
executeQuery: () => void
executeExplainQuery: () => void
@@ -44,7 +44,7 @@ export type MonacoEditorProps = {
placeholder?: string
}
-const MonacoEditor = ({
+export const MonacoEditor = ({
id,
snippetName,
editorRef,
@@ -74,11 +74,7 @@ const MonacoEditor = ({
LOCAL_STORAGE_KEYS.SQL_EDITOR_INTELLISENSE,
true
)
- const isAIAssistantHotkeyEnabled = useIsShortcutEnabled(SHORTCUT_IDS.AI_ASSISTANT_TOGGLE)
- const isCommandMenuHotkeyEnabled = useIsShortcutEnabled(SHORTCUT_IDS.COMMAND_MENU_OPEN)
- const setCommandMenuOpen = useSetCommandMenuOpen()
- // [Joshen] Lodash debounce doesn't seem to be working here, so opting to use useDebounce
const [value, setValue] = useState('')
const debouncedValue = useDebounce(value, 1000)
@@ -86,31 +82,20 @@ const MonacoEditor = ({
const disableEdit =
snippet?.snippet.visibility === 'project' && snippet?.snippet.owner_id !== profile?.id
- const executeQueryRef = useRef(executeQuery)
- executeQueryRef.current = executeQuery
-
const executeExplainQueryRef = useRef(executeExplainQuery)
executeExplainQueryRef.current = executeExplainQuery
const prettifyQueryRef = useRef(prettifyQuery)
prettifyQueryRef.current = prettifyQuery
+ const isAIAssistantHotkeyEnabled = useIsShortcutEnabled(SHORTCUT_IDS.AI_ASSISTANT_TOGGLE)
const aiHotkeyEnabledRef = useRef(isAIAssistantHotkeyEnabled)
aiHotkeyEnabledRef.current = isAIAssistantHotkeyEnabled
- const commandMenuHotkeyEnabledRef = useRef(isCommandMenuHotkeyEnabled)
- commandMenuHotkeyEnabledRef.current = isCommandMenuHotkeyEnabled
-
- const setCommandMenuOpenRef = useRef(setCommandMenuOpen)
- setCommandMenuOpenRef.current = setCommandMenuOpen
-
- const handleEditorOnMount: OnMount = async (editor, monaco) => {
- editorRef.current = editor
- monacoRef.current = monaco
-
- const model = editorRef.current.getModel()
+ const handleEditorOnMount: OnMount = (editor, monaco) => {
+ const model = editor.getModel()
if (model !== null) {
- monacoRef.current.editor.setModelMarkers(model, 'owner', [])
+ monaco.editor.setModelMarkers(model, 'owner', [])
}
// Blur the editor on Escape so users can hop out to the rest of the UI.
@@ -136,17 +121,6 @@ const MonacoEditor = ({
].join(' && ')
)
- editor.addAction({
- id: 'run-query',
- label: 'Run Query',
- keybindings: [monaco.KeyMod.CtrlCmd + monaco.KeyCode.Enter],
- contextMenuGroupId: 'operation',
- contextMenuOrder: 0,
- run: () => {
- executeQueryRef.current()
- },
- })
-
if (showExplainAction) {
editor.addAction({
id: 'run-explain-query',
@@ -188,13 +162,15 @@ const MonacoEditor = ({
contextMenuGroupId: 'operation',
contextMenuOrder: 1,
run: () => {
- const selectedValue = (editorRef?.current as any)
- .getModel()
- .getValueInRange((editorRef?.current as any)?.getSelection())
+ const selection = editorRef?.current?.getSelection()
+ if (!selection) return
+
+ const selectedValue = editorRef?.current?.getModel()?.getValueInRange(selection)
+
openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)
aiSnap.newChat({
name: 'Explain code section',
- sqlSnippets: [selectedValue],
+ sqlSnippets: [selectedValue ?? ''],
initialInput: 'Can you explain this section to me in more detail?',
})
},
@@ -223,15 +199,6 @@ const MonacoEditor = ({
})
}
- // Monaco claims Cmd+K as a chord prefix, which swallows the global command
- // menu shortcut while the editor is focused. Intercept it here and open the
- // command menu directly so it works the same inside and outside the editor.
- editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyK, () => {
- if (commandMenuHotkeyEnabledRef.current) {
- setCommandMenuOpenRef.current(true)
- }
- })
-
editor.onDidChangeCursorSelection(({ selection }) => {
const noSelection =
selection.startLineNumber === selection.endLineNumber &&
@@ -239,11 +206,6 @@ const MonacoEditor = ({
onHasSelection(!noSelection)
})
- if (autoFocus) {
- if (editor.getValue().length === 1) editor.setPosition({ lineNumber: 1, column: 2 })
- editor.focus()
- }
-
onMount?.(editor)
}
@@ -297,29 +259,26 @@ const MonacoEditor = ({
description="This snippet has been shared to the project and is only editable by the owner who created this snippet. You may duplicate this snippet into a personal copy by right clicking on the snippet and selecting “Duplicate query”."
/>
)}
- <Editor
- className={cn(className, 'monaco-editor')}
- theme={'supabase'}
- onMount={handleEditorOnMount}
- onChange={handleEditorChange}
- defaultLanguage="pgsql"
+ <CodeEditor
+ id={id}
+ language="pgsql"
+ className={className}
+ autofocus={autoFocus}
+ isReadOnly={disableEdit}
defaultValue={snippet?.snippet.content?.unchecked_sql}
- path={id}
+ editorRef={editorRef}
+ monacoRef={monacoRef}
+ actions={{
+ runQuery: { enabled: true, callback: executeQuery },
+ formatDocument: { enabled: false, callback: noop },
+ placeholderFill: { enabled: false },
+ }}
options={{
- tabSize: 2,
- fontSize: 13,
placeholder,
lineDecorationsWidth: 0,
- readOnly: disableEdit,
- minimap: { enabled: false },
- wordWrap: 'on',
- padding: { top: 4 },
- // [Joshen] Commenting the following out as it causes the autocomplete suggestion popover
- // to be positioned wrongly somehow. I'm not sure if this affects anything though, but leaving
- // comment just in case anyone might be wondering. Relevant issues:
- // - https://github.com/microsoft/monaco-editor/issues/2229
- // - https://github.com/microsoft/monaco-editor/issues/2503
- // fixedOverflowWidgets: true,
+ fixedOverflowWidgets: false,
+ lineNumbersMinChars: 5,
+ scrollBeyondLastLine: true,
suggest: {
showMethods: intellisenseEnabled,
showFunctions: intellisenseEnabled,
@@ -351,9 +310,9 @@ const MonacoEditor = ({
showSnippets: intellisenseEnabled,
},
}}
+ onInputChange={handleEditorChange}
+ onMount={handleEditorOnMount}
/>
</>
)
}
-
-export default MonacoEditor
diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
index 1fb030732f9..c3f736f8caf 100644
--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
@@ -96,7 +96,10 @@ import { getSqlEditorV2StateSnapshot, useSqlEditorV2StateSnapshot } from '@/stat
import { createTabId, useTabsStateSnapshot } from '@/state/tabs'
// Load the monaco editor client-side only (does not behave well server-side)
-const MonacoEditor = dynamic(() => import('./MonacoEditor'), { ssr: false })
+const MonacoEditor = dynamic(
+ () => import('./MonacoEditor').then(({ MonacoEditor }) => MonacoEditor),
+ { ssr: false }
+)
const DiffEditor = dynamic(
() => import('../../ui/DiffEditor').then(({ DiffEditor }) => DiffEditor),
{ ssr: false }
diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/CellDetailPanel.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/CellDetailPanel.tsx
index e969b189f38..1ef52e82351 100644
--- a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/CellDetailPanel.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/CellDetailPanel.tsx
@@ -3,7 +3,7 @@ import remarkGfm from 'remark-gfm'
import { Sheet, SheetContent, SheetHeader, SheetTitle } from 'ui'
import { Markdown } from '@/components/interfaces/Markdown'
-import CodeEditor from '@/components/ui/CodeEditor/CodeEditor'
+import { CodeEditor } from '@/components/ui/CodeEditor/CodeEditor'
import { TwoOptionToggle } from '@/components/ui/TwoOptionToggle'
interface CellDetailPanelProps {
diff --git a/apps/studio/components/ui/CodeEditor/CodeEditor.tsx b/apps/studio/components/ui/CodeEditor/CodeEditor.tsx
index 63bd1d7e314..c9d5f4d2f9f 100644
--- a/apps/studio/components/ui/CodeEditor/CodeEditor.tsx
+++ b/apps/studio/components/ui/CodeEditor/CodeEditor.tsx
@@ -1,27 +1,29 @@
import Editor, { EditorProps, Monaco, OnChange, OnMount, useMonaco } from '@monaco-editor/react'
import { merge, noop } from 'lodash'
import type { editor } from 'monaco-editor'
-import { MutableRefObject, useEffect, useRef, useState } from 'react'
+import { RefObject, useEffect, useRef, useState } from 'react'
import { cn, LogoLoader } from 'ui'
+import { useSetCommandMenuOpen } from 'ui-patterns/CommandMenu'
import { alignEditor } from './CodeEditor.utils'
import { Markdown } from '@/components/interfaces/Markdown'
+import { useLatest } from '@/hooks/misc/useLatest'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { formatSql } from '@/lib/formatSql'
-import { timeout } from '@/lib/helpers'
+import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
+import { useIsShortcutEnabled } from '@/state/shortcuts/useIsShortcutEnabled'
type CodeEditorActions = { enabled: boolean; callback: (value: any) => void }
+
const DEFAULT_ACTIONS = {
runQuery: { enabled: false, callback: noop },
- explainCode: { enabled: false, callback: noop },
formatDocument: { enabled: true, callback: noop },
placeholderFill: { enabled: true },
- closeAssistant: { enabled: false, callback: noop },
}
interface CodeEditorProps {
- id: string
- language: 'pgsql' | 'json' | 'html' | 'typescript' | undefined
+ id?: string
+ language: 'pgsql' | 'json' | 'html' | 'typescript' | 'plaintext' | undefined
autofocus?: boolean
defaultValue?: string
isReadOnly?: boolean
@@ -36,11 +38,15 @@ interface CodeEditorProps {
runQuery: CodeEditorActions
formatDocument: CodeEditorActions
placeholderFill: Omit<CodeEditorActions, 'callback'>
- explainCode: CodeEditorActions
- closeAssistant: CodeEditorActions
}>
- editorRef?: MutableRefObject<editor.IStandaloneCodeEditor | null>
+ editorRef?: RefObject<editor.IStandaloneCodeEditor | null>
+ monacoRef?: RefObject<Monaco | null>
onInputChange?: (value?: string) => void
+ /**
+ * Fired after CodeEditor's own mount setup runs, so wrappers can register
+ * additional actions/keybindings on the shared editor instance.
+ */
+ onMount?: OnMount
}
export const CodeEditor = ({
@@ -55,9 +61,11 @@ export const CodeEditor = ({
options,
value,
placeholder,
- actions = DEFAULT_ACTIONS,
+ actions,
editorRef: editorRefProps,
+ monacoRef: monacoRefProps,
onInputChange = noop,
+ onMount: onMountProps,
}: CodeEditorProps) => {
const monaco = useMonaco()
const { data: project } = useSelectedProjectQuery()
@@ -65,17 +73,22 @@ export const CodeEditor = ({
const hasValue = useRef<editor.IContextKey<boolean>>(null)
const ref = useRef<editor.IStandaloneCodeEditor>(null)
const editorRef = editorRefProps || ref
- const monacoRef = useRef<Monaco>(null)
+ const internalMonacoRef = useRef<Monaco | null>(null)
+ const monacoRef = monacoRefProps || internalMonacoRef
- const { runQuery, placeholderFill, formatDocument, explainCode, closeAssistant } = {
+ const { runQuery, placeholderFill, formatDocument } = {
...DEFAULT_ACTIONS,
...actions,
}
- const runQueryCallbackRef = useRef(runQuery.callback)
- useEffect(() => {
- runQueryCallbackRef.current = runQuery.callback
- }, [runQuery.callback])
+ // Monaco claims Cmd+K as a chord prefix, which swallows the global command menu
+ // shortcut while the editor is focused. CodeEditor intercepts it for every editor
+ // (see handleMount) so it behaves the same inside and outside the editor.
+ const commandMenuHotkeyEnabledRef = useLatest(
+ useIsShortcutEnabled(SHORTCUT_IDS.COMMAND_MENU_OPEN)
+ )
+ const setCommandMenuOpenRef = useLatest(useSetCommandMenuOpen())
+ const runQueryCallbackRef = useLatest(runQuery.callback)
const showPlaceholderDefault = placeholder !== undefined && (value ?? '').trim().length === 0
const [showPlaceholder, setShowPlaceholder] = useState(showPlaceholderDefault)
@@ -98,7 +111,7 @@ export const CodeEditor = ({
options
)
- const onMount: OnMount = async (editor, monaco) => {
+ const handleMount: OnMount = async (editor, monaco) => {
editorRef.current = editor
monacoRef.current = monaco
alignEditor(editor)
@@ -107,6 +120,12 @@ export const CodeEditor = ({
hasValue.current.set(value !== undefined && value.trim().length > 0)
setShowPlaceholder(showPlaceholderDefault)
+ editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyK, () => {
+ if (commandMenuHotkeyEnabledRef.current) {
+ setCommandMenuOpenRef.current(true)
+ }
+ })
+
if (placeholderFill.enabled) {
editor.addCommand(
monaco.KeyCode.Tab,
@@ -132,35 +151,14 @@ export const CodeEditor = ({
contextMenuGroupId: 'operation',
contextMenuOrder: 0,
run: () => {
- const selectedValue = (editorRef?.current as any)
- .getModel()
- .getValueInRange((editorRef?.current as any)?.getSelection())
- runQueryCallbackRef.current(selectedValue || (editorRef?.current as any)?.getValue())
- },
- })
- }
+ const selection = editorRef?.current?.getSelection()
+ if (!selection) return
- if (explainCode.enabled) {
- editor.addAction({
- id: 'explain-code',
- label: 'Explain Code',
- contextMenuGroupId: 'operation',
- contextMenuOrder: 1,
- run: () => {
- const selectedValue = (editorRef?.current as any)
- .getModel()
- .getValueInRange((editorRef?.current as any)?.getSelection())
- explainCode.callback(selectedValue)
- },
- })
- }
+ const selectedValue = editorRef?.current?.getModel()?.getValueInRange(selection)
+ const editorValue = editorRef?.current?.getValue()
- if (closeAssistant.enabled) {
- editor.addAction({
- id: 'close-assistant',
- label: 'Close Assistant',
- keybindings: [monaco.KeyMod.CtrlCmd + monaco.KeyCode.KeyI],
- run: () => closeAssistant.callback(),
+ runQueryCallbackRef.current(selectedValue || editorValue)
+ },
})
}
@@ -170,8 +168,17 @@ export const CodeEditor = ({
editor.setPosition(position)
}
- await timeout(500)
- if (autofocus) editor?.focus()
+ // Run last so wrappers can register actions and have the final say on cursor
+ // position / focus before CodeEditor's own (timeout-deferred) autofocus.
+ onMountProps?.(editor, monaco)
+
+ // auto focus on mount
+ setTimeout(() => {
+ if (autofocus) {
+ if (editor.getValue().length === 1) editor.setPosition({ lineNumber: 1, column: 2 })
+ editor.focus()
+ }
+ }, 0)
}
const onChangeContent: OnChange = (value) => {
@@ -244,7 +251,7 @@ export const CodeEditor = ({
defaultValue={defaultValue ?? undefined}
loading={loading || <LogoLoader />}
options={optionsMerged}
- onMount={onMount}
+ onMount={handleMount}
onChange={onChangeContent}
/>
{placeholder !== undefined && (
@@ -261,5 +268,3 @@ export const CodeEditor = ({
</>
)
}
-
-export default CodeEditor
diff --git a/apps/studio/pages/project/[ref]/logs/explorer/index.tsx b/apps/studio/pages/project/[ref]/logs/explorer/index.tsx
index 99bd536b04e..17a086e7590 100644
--- a/apps/studio/pages/project/[ref]/logs/explorer/index.tsx
+++ b/apps/studio/pages/project/[ref]/logs/explorer/index.tsx
@@ -30,7 +30,7 @@ import { LogTable } from '@/components/interfaces/Settings/Logs/LogTable'
import UpgradePrompt from '@/components/interfaces/Settings/Logs/UpgradePrompt'
import DefaultLayout from '@/components/layouts/DefaultLayout'
import LogsLayout from '@/components/layouts/LogsLayout/LogsLayout'
-import CodeEditor from '@/components/ui/CodeEditor/CodeEditor'
+import { CodeEditor } from '@/components/ui/CodeEditor/CodeEditor'
import LoadingOpacity from '@/components/ui/LoadingOpacity'
import ShimmerLine from '@/components/ui/ShimmerLine'
import { useContentQuery } from '@/data/content/content-query'