The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(sql-editor): ask ai widget poc
Greg Richardsone94a9188bbb9
diff --git a/package-lock.json b/package-lock.jsonindex f7ba214ff40..4c5343a3296 100644--- a/package-lock.json+++ b/package-lock.json@@ -30233,9 +30233,9 @@}},"node_modules/monaco-editor": {- "version": "0.38.0",- "resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.38.0.tgz",- "integrity": "sha512-11Fkh6yzEmwx7O0YoLxeae0qEGFwmyPRlVxpg7oF9czOOCB/iCjdJrG5I67da5WiXK3YJCxoz9TJFE8Tfq/v9A==",+ "version": "0.33.0",+ "resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.33.0.tgz",+ "integrity": "sha512-VcRWPSLIUEgQJQIE0pVT8FcGBIgFoxz7jtqctE+IiCxWugD0DwgyQBcZBhdSrdMC84eumoqMZsGl2GTreOzwqw==","peer": true},"node_modules/moo": {@@ -43978,11 +43978,6 @@"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz","integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="},- "studio/node_modules/monaco-editor": {- "version": "0.33.0",- "resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.33.0.tgz",- "integrity": "sha512-VcRWPSLIUEgQJQIE0pVT8FcGBIgFoxz7jtqctE+IiCxWugD0DwgyQBcZBhdSrdMC84eumoqMZsGl2GTreOzwqw=="- },"studio/node_modules/proxy-compare": {"version": "2.3.0","license": "MIT"diff --git a/studio/components/interfaces/SQLEditor/AskAIWidget.tsx b/studio/components/interfaces/SQLEditor/AskAIWidget.tsxnew file mode 100644index 00000000000..7e5e357898c--- /dev/null+++ b/studio/components/interfaces/SQLEditor/AskAIWidget.tsx@@ -0,0 +1,55 @@+import { detectOS } from 'lib/helpers'+import { useCallback } from 'react'+import { AiIcon, IconCornerDownLeft, Input } from 'ui'++const AskAIWidget = () => {+ const os = detectOS()++ // Auto focus input+ const inputRef = useCallback((input: HTMLInputElement | null) => {+ setTimeout(() => {+ input?.focus()+ }, 0)+ }, [])++ return (+ <div className="bg-scale-200 rounded-md p-2 my-2 border border-scale-700 shadow-xl shadow-scale-100 flex flex-col gap-2 text-sm text-scale-1100 max-w-xl">+ <Input+ inputRef={inputRef}+ size="xlarge"+ icon={<AiIcon className="w-4 h-4 ml-1" />}+ inputClassName="bg-scale-100 placeholder:text-scale-900 rounded-sm focus:!border-brand-900"+ iconContainerClassName="transition text-scale-800 peer-focus/input:text-brand-900"+ placeholder="Ask Supabase AI to do something"+ autoFocus+ actions={+ <div className="flex items-center space-x-1 mr-6">+ {os === 'macos' ? (+ <svg+ width="16"+ height="16"+ viewBox="0 0 24 24"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ >+ <path+ d="M3 5H7.76472L16.2353 19H21M16.2353 5H21"+ stroke="currentColor"+ strokeWidth="1.5"+ strokeLinecap="square"+ strokeLinejoin="round"+ />+ </svg>+ ) : (+ <p className="text-xs text-scale-1100">ALT</p>+ )}+ <IconCornerDownLeft size={16} strokeWidth={1.5} />+ </div>+ }+ />+ AI generated code may be incorrect.+ </div>+ )+}++export default AskAIWidgetdiff --git a/studio/components/interfaces/SQLEditor/InlineWidget.tsx b/studio/components/interfaces/SQLEditor/InlineWidget.tsxnew file mode 100644index 00000000000..9c07fdb9f3c--- /dev/null+++ b/studio/components/interfaces/SQLEditor/InlineWidget.tsx@@ -0,0 +1,102 @@+import { editor } from 'monaco-editor'+import { PropsWithChildren, useEffect, useMemo } from 'react'+import { createPortal } from 'react-dom'++export interface InlineWidgetProps {+ /**+ * The Monaco editor instance.+ */+ editor: editor.IStandaloneCodeEditor++ /**+ * ID used by Monaco to reference this widget+ */+ id: string++ /**+ * The line number after which this zone should appear.+ * Use 0 to place a view zone before the first line number.+ */+ afterLineNumber: number++ /**+ * The height in lines of the view zone.+ * @default 1+ */+ heightInLines?: number+}++/**+ * Adds an inline widget to a Monaco editor instance. Acts as a+ * container for custom widgets that are rendered inline.+ *+ * Implemented using the same techniques VS Code uses for their inline+ * widgets (such as "Go to References"), but built for React.+ * Uses a combination of a view zone and overlay widget.+ */+const InlineWidget = ({+ children,+ editor,+ id,+ afterLineNumber,+ heightInLines = 1,+}: PropsWithChildren<InlineWidgetProps>) => {+ const key = `${id}-${afterLineNumber.toString()}`++ const containerElement = useMemo(() => document.createElement('div'), [])++ useEffect(() => {+ let zoneId: string+ let viewZoneTop = 0+ let viewZoneHeight = 0++ const overlayWidget: editor.IOverlayWidget = {+ getId: () => id,+ getDomNode: () => containerElement,+ getPosition: () => null,+ }++ const recalculateLayout = () => {+ const layoutInfo = editor.getLayoutInfo()++ if (!layoutInfo) {+ return+ }++ containerElement.style.left = `${layoutInfo.contentLeft}px`+ containerElement.style.top = `${viewZoneTop}px`+ containerElement.style.width = `${layoutInfo.width - layoutInfo.contentLeft}px`+ containerElement.style.height = `${viewZoneHeight}px`+ }++ editor.changeViewZones((accessor) => {+ zoneId = accessor.addZone({+ afterLineNumber,+ heightInLines,+ domNode: document.createElement('div'),+ onDomNodeTop: (top) => {+ viewZoneTop = top+ recalculateLayout()+ },+ onComputedHeight: (height) => {+ viewZoneHeight = height+ recalculateLayout()+ },+ })++ editor.addOverlayWidget(overlayWidget)+ })++ // Remove the view zone & overlay widget on unmount+ return () => {+ editor.changeViewZones((accessor) => {+ accessor.removeZone(zoneId)+ editor.removeOverlayWidget(overlayWidget)+ })+ }+ }, [editor, id, afterLineNumber, heightInLines, containerElement])++ return createPortal(children, containerElement, key)+}++export default InlineWidgetdiff --git a/studio/components/interfaces/SQLEditor/MonacoEditor.tsx b/studio/components/interfaces/SQLEditor/MonacoEditor.tsxindex f14676c6484..29ff495937e 100644--- a/studio/components/interfaces/SQLEditor/MonacoEditor.tsx+++ b/studio/components/interfaces/SQLEditor/MonacoEditor.tsx@@ -1,8 +1,10 @@import Editor, { Monaco, OnMount } from '@monaco-editor/react'import { timeout } from 'lib/helpers'-import { MutableRefObject, useEffect, useRef, useState } from 'react'-import { createPortal } from 'react-dom'+import { Selection, editor } from 'monaco-editor'+import { MutableRefObject, useRef, useState } from 'react'import { useSqlEditorStateSnapshot } from 'state/sql-editor'+import AskAIWidget from './AskAIWidget'+import InlineWidget from './InlineWidget'export type IStandaloneCodeEditor = Parameters<OnMount>[0]@@ -21,23 +23,23 @@ const MonacoEditor = ({ id, editorRef, isExecuting, executeQuery }: MonacoEditorconst executeQueryRef = useRef(executeQuery)executeQueryRef.current = executeQuery- const [domNode, setDomNode] = useState<HTMLElement>()+ const [editor, setEditor] = useState<editor.IStandaloneCodeEditor>()+ const [isAiWidgetOpen, setIsAiWidgetOpen] = useState(false)+ const [aiWidgetSelection, setAiWidgetSelection] = useState<Selection>()- useEffect(() => {- if (!editorRef.current || !monacoRef.current) return+ const handleEditorOnMount: OnMount = async (editor, monaco) => {+ editorRef.current = editor+ monacoRef.current = monaco++ setEditor(editor)const model = editorRef.current.getModel()if (model !== null) {monacoRef.current.editor.setModelMarkers(model, 'owner', [])}- }, [])-- const handleEditorOnMount: OnMount = async (editor, monaco) => {- editorRef.current = editor- monacoRef.current = monacoeditor.addAction({- id: 'supabase',+ id: 'run-query',label: 'Run Query',keybindings: [monaco.KeyMod.CtrlCmd + monaco.KeyCode.Enter],contextMenuGroupId: 'operation',@@ -47,63 +49,29 @@ const MonacoEditor = ({ id, editorRef, isExecuting, executeQuery }: MonacoEditor},})- const domNode = document.createElement('div')-- let viewZoneTop = 0- let viewZoneHeight = 0-- setDomNode(domNode)-- function layoutOverlayWidget() {- const layoutInfo = editorRef.current?.getLayoutInfo()-- if (!layoutInfo) {- return- }-- console.log({ layoutInfo })+ editor.addAction({+ id: 'ask-ai',+ label: 'Ask AI',+ keybindings: [monaco.KeyMod.Alt + monaco.KeyCode.Enter],+ contextMenuGroupId: 'operation',+ contextMenuOrder: 0,+ run: () => {+ const selection = editor.getSelection()- domNode.style.left = `${layoutInfo.contentLeft}px`- domNode.style.top = `${viewZoneTop}px`- domNode.style.width = `${layoutInfo.width}px`- domNode.style.height = `${viewZoneHeight}px`- }+ if (selection) {+ setAiWidgetSelection(selection)+ setIsAiWidgetOpen(true)+ }+ },+ })+ // add margin above first lineeditorRef.current.changeViewZones((accessor) => {- // add margin above first lineaccessor.addZone({afterLineNumber: 0,heightInPx: 4,domNode: document.createElement('div'),})-- accessor.addZone({- afterLineNumber: 1,- heightInLines: 4,- domNode: document.createElement('div'),- onDomNodeTop: (top) => {- console.log({ top })- viewZoneTop = top- layoutOverlayWidget()- },- onComputedHeight: (height) => {- console.log({ height })- viewZoneHeight = height- layoutOverlayWidget()- },- })-- editorRef.current?.addOverlayWidget({- getId: function () {- return 'my.inline.widget'- },- getDomNode: function () {- return domNode- },- getPosition: function () {- return null- },- })})// when editor did mount, it will need a delay before focus() works properly@@ -135,7 +103,16 @@ const MonacoEditor = ({ id, editorRef, isExecuting, executeQuery }: MonacoEditorfixedOverflowWidgets: true,}}/>- {domNode && createPortal(<>My inline widget</>, domNode)}+ {editor && isAiWidgetOpen && aiWidgetSelection && (+ <InlineWidget+ editor={editor}+ id="ask-ai"+ afterLineNumber={aiWidgetSelection.endLineNumber}+ heightInLines={6}+ >+ <AskAIWidget />+ </InlineWidget>+ )}</>)}