Skip to content

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

refactor form logic in org settings page, and refactor generate sql into smaller files

Joshen Limf0e1103f2425
diff --git a/packages/ui/src/components/Command/CommandMenuProvider.tsx b/packages/ui/src/components/Command/CommandMenuProvider.tsx
index 8787b032695..161e71681eb 100644
--- a/packages/ui/src/components/Command/CommandMenuProvider.tsx
+++ b/packages/ui/src/components/Command/CommandMenuProvider.tsx
@@ -1,5 +1,4 @@
import { useTheme, UseThemeProps } from 'common'
-import * as React from 'react'
import { createContext, PropsWithChildren, useContext, useEffect, useState } from 'react'
import CommandMenu from './CommandMenu'
import { ReactMarkdownOptions } from 'react-markdown/lib/react-markdown'
@@ -17,12 +16,22 @@ export interface CommandMenuContextValue {
currentPage?: string
site: 'studio' | 'docs'
- // Project metadata for easy retrieval
+ /**
+ * Project metadata for easy retrieval
+ */
project?: { ref?: string; apiKeys?: { anon?: string; service?: string } }
+ /**
+ * Any additional metadata that CMDK component can use in its AI prompts
+ */
+ metadata: any
+ /**
+ * Opt in flag to use additional metadata in AI prompts
+ */
+ isOptedInToAI: boolean
// to do: remove this prop
// this is a temporary hack as ReactMarkdown fails our jest tests if we import the package within this UI package
- MarkdownHandler: (props: ReactMarkdownOptions) => JSX.Element // to do: remove this. although it breaks our jest tests
+ MarkdownHandler: (props: ReactMarkdownOptions) => JSX.Element
// Optional callback to save a generated SQL output
onSaveGeneratedSQL?: (answer: string, resolve: any) => void
@@ -45,12 +54,27 @@ export interface CommandMenuActions {
export interface CommandMenuProviderProps {
site: 'studio' | 'docs'
projectRef?: string
+ /**
+ * Project's API keys, for easy access through CMDK
+ */
apiKeys?: { anon?: string; service?: string }
- // to do: remove this prop
- // this is a temporary hack as ReactMarkdown fails our jest tests if we import the package within this UI package
+ /**
+ * Opt in flag to use additional metadata in AI prompts
+ */
+ isOptedInToAI?: boolean
+ /**
+ * Any additional metadata that CMDK component can use in its AI prompts
+ */
+ metadata?: any
+ /**
+ * TODO: remove this prop, temporary hack as ReactMarkdown fails our jest tests
+ * if we import the package directly within this UI package
+ */
MarkdownHandler: (props: ReactMarkdownOptions) => JSX.Element
+ /**
+ * Call back when save SQL snippet button is selected
+ */
onSaveGeneratedSQL?: (answer: string, resolve: any) => void
- isOptedInToAI: boolean
}
const CommandMenuProvider = ({
@@ -58,14 +82,15 @@ const CommandMenuProvider = ({
site,
projectRef,
apiKeys,
+ metadata,
+ isOptedInToAI = false,
MarkdownHandler,
onSaveGeneratedSQL,
- isOptedInToAI,
}: PropsWithChildren<CommandMenuProviderProps>) => {
const [isOpen, setIsOpen] = useState(false)
const [isLoading, setIsLoading] = useState(false)
- const [search, setSearch] = React.useState('')
- const [pages, setPages] = React.useState<string[]>([])
+ const [search, setSearch] = useState('')
+ const [pages, setPages] = useState<string[]>([])
const { toggleTheme } = useTheme()
const currentPage = pages[pages.length - 1]
@@ -73,7 +98,7 @@ const CommandMenuProvider = ({
const project = projectRef !== undefined ? { ref: projectRef, apiKeys } : undefined
useKeyboardEvents({ setIsOpen, currentPage, setSearch, setPages })
- console.log('org opted in to OpenAI?', isOptedInToAI ? 'true' : 'false')
+
return (
<CommandMenuContext.Provider
value={{
@@ -89,6 +114,8 @@ const CommandMenuProvider = ({
currentPage,
site,
project,
+ metadata,
+ isOptedInToAI,
MarkdownHandler,
onSaveGeneratedSQL,
}}
diff --git a/packages/ui/src/components/Command/GenerateSQL.tsx b/packages/ui/src/components/Command/GenerateSQL/GenerateSQL.tsx
similarity index 74%
rename from packages/ui/src/components/Command/GenerateSQL.tsx
rename to packages/ui/src/components/Command/GenerateSQL/GenerateSQL.tsx
index 13515742bb0..8363b52d78e 100644
--- a/packages/ui/src/components/Command/GenerateSQL.tsx
+++ b/packages/ui/src/components/Command/GenerateSQL/GenerateSQL.tsx
@@ -7,147 +7,18 @@ import {
CodeBlock,
IconAlertCircle,
IconAlertTriangle,
- IconCheck,
- IconClipboard,
IconCornerDownLeft,
- IconSave,
IconUser,
Input,
} from 'ui'
-import { cn } from './../../utils/cn'
-import { AiIcon, AiIconChat } from './Command.icons'
-import { CommandItem } from './Command.utils'
-import { useCommandMenu } from './CommandMenuProvider'
-import CopyToClipboard from 'react-copy-to-clipboard'
-import { SAMPLE_QUERIES } from './Command.constants'
-
-function getEdgeFunctionUrl() {
- const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL?.replace(/\/$/, '')
-
- if (!supabaseUrl) return undefined
-
- // https://github.com/supabase/supabase-js/blob/10d3423506cbd56345f7f6ab2ec2093c8db629d4/src/SupabaseClient.ts#L96
- const isPlatform = supabaseUrl.match(/(supabase\.co)|(supabase\.in)/)
-
- if (isPlatform) {
- const [schemeAndProjectId, domain, tld] = supabaseUrl.split('.')
- return `${schemeAndProjectId}.functions.${domain}.${tld}`
- } else {
- return `${supabaseUrl}/functions/v1`
- }
-}
-
-function promptDataReducer(
- state: any[],
- action: {
- index?: number
- answer?: string | undefined
- status?: string
- query?: string | undefined
- type?: 'remove-last-item' | string
- }
-) {
- // set a standard state to use later
- let current = [...state]
-
- if (action.type) {
- switch (action.type) {
- case 'remove-last-item':
- current.pop()
- return [...current]
- default:
- break
- }
- }
-
- // check that an index is present
- if (action.index === undefined) return [...state]
-
- if (!current[action.index]) {
- current[action.index] = { query: '', answer: '', status: '' }
- }
-
- current[action.index].answer = action.answer
-
- if (action.query) {
- current[action.index].query = action.query
- }
- if (action.status) {
- current[action.index].status = action.status
- }
-
- return [...current]
-}
-
-const SQLOutputActions = ({ answer }: { answer: string }) => {
- const [showCopied, setShowCopied] = useState(false)
- const [isSaving, setIsSaving] = useState(false)
- const [isSaved, setIsSaved] = useState(false)
-
- const { project, onSaveGeneratedSQL } = useCommandMenu()
-
- const applyCallback = () =>
- onSaveGeneratedSQL !== undefined
- ? new Promise((resolve) => onSaveGeneratedSQL(answer, resolve))
- : {}
-
- const onSelectSaveSnippet = async () => {
- setIsSaving(true)
- await applyCallback()
- setIsSaved(true)
- setIsSaving(false)
- }
-
- useEffect(() => {
- if (!showCopied) return
- const timer = setTimeout(() => setShowCopied(false), 2000)
- return () => clearTimeout(timer)
- }, [showCopied])
-
- useEffect(() => {
- if (!isSaved) return
- const timer = setTimeout(() => setIsSaved(false), 2000)
- return () => clearTimeout(timer)
- }, [isSaved])
-
- return (
- <div className="flex items-center justify-end space-x-2">
- <CopyToClipboard text={answer?.replace(/```.*/g, '').trim()}>
- <Button
- type="default"
- icon={
- showCopied ? (
- <IconCheck size="tiny" className="text-brand-900" strokeWidth={2} />
- ) : (
- <IconClipboard size="tiny" />
- )
- }
- onClick={() => setShowCopied(true)}
- >
- {showCopied ? 'Copied' : 'Copy SQL'}
- </Button>
- </CopyToClipboard>
- {project?.ref !== undefined && onSaveGeneratedSQL !== undefined && (
- <Button
- type="default"
- loading={isSaving}
- disabled={isSaving}
- icon={
- isSaved ? (
- <IconCheck size="tiny" className="text-brand-900" strokeWidth={2} />
- ) : (
- <IconSave size="tiny" />
- )
- }
- onClick={() => onSelectSaveSnippet()}
- >
- {isSaved ? 'Snippet saved!' : 'Save into new snippet'}
- </Button>
- )}
- </div>
- )
-}
+import { cn } from '../../../utils/cn'
+import { AiIcon, AiIconChat } from '../Command.icons'
+import { CommandItem } from '../Command.utils'
+import { useCommandMenu } from '../CommandMenuProvider'
+import { SAMPLE_QUERIES } from '../Command.constants'
+import SQLOutputActions from './SQLOutputActions'
+import { getEdgeFunctionUrl, promptDataReducer } from './GenerateSQL.utils'
const GenerateSQL = () => {
const [promptIndex, setPromptIndex] = useState(0)
@@ -158,10 +29,12 @@ const GenerateSQL = () => {
const eventSourceRef = useRef<SSE>()
const [promptData, dispatchPromptData] = useReducer(promptDataReducer, [])
- const { isLoading, setIsLoading, search, setSearch } = useCommandMenu()
+ const { isLoading, setIsLoading, search, setSearch, isOptedInToAI, metadata } = useCommandMenu()
const cantHelp = answer?.trim() === "Sorry, I don't know how to help with that."
+ console.log('Generate SQL', { isOptedInToAI, metadata })
+
const handleConfirm = useCallback(
async (query: string) => {
const edgeFunctionUrl = getEdgeFunctionUrl()
diff --git a/packages/ui/src/components/Command/GenerateSQL/GenerateSQL.utils.ts b/packages/ui/src/components/Command/GenerateSQL/GenerateSQL.utils.ts
new file mode 100644
index 00000000000..afddc313f66
--- /dev/null
+++ b/packages/ui/src/components/Command/GenerateSQL/GenerateSQL.utils.ts
@@ -0,0 +1,57 @@
+export function getEdgeFunctionUrl() {
+ const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL?.replace(/\/$/, '')
+
+ if (!supabaseUrl) return undefined
+
+ // https://github.com/supabase/supabase-js/blob/10d3423506cbd56345f7f6ab2ec2093c8db629d4/src/SupabaseClient.ts#L96
+ const isPlatform = supabaseUrl.match(/(supabase\.co)|(supabase\.in)/)
+
+ if (isPlatform) {
+ const [schemeAndProjectId, domain, tld] = supabaseUrl.split('.')
+ return `${schemeAndProjectId}.functions.${domain}.${tld}`
+ } else {
+ return `${supabaseUrl}/functions/v1`
+ }
+}
+
+export function promptDataReducer(
+ state: any[],
+ action: {
+ index?: number
+ answer?: string | undefined
+ status?: string
+ query?: string | undefined
+ type?: 'remove-last-item' | string
+ }
+) {
+ // set a standard state to use later
+ let current = [...state]
+
+ if (action.type) {
+ switch (action.type) {
+ case 'remove-last-item':
+ current.pop()
+ return [...current]
+ default:
+ break
+ }
+ }
+
+ // check that an index is present
+ if (action.index === undefined) return [...state]
+
+ if (!current[action.index]) {
+ current[action.index] = { query: '', answer: '', status: '' }
+ }
+
+ current[action.index].answer = action.answer
+
+ if (action.query) {
+ current[action.index].query = action.query
+ }
+ if (action.status) {
+ current[action.index].status = action.status
+ }
+
+ return [...current]
+}
diff --git a/packages/ui/src/components/Command/GenerateSQL/SQLOutputActions.tsx b/packages/ui/src/components/Command/GenerateSQL/SQLOutputActions.tsx
new file mode 100644
index 00000000000..9b661edd4da
--- /dev/null
+++ b/packages/ui/src/components/Command/GenerateSQL/SQLOutputActions.tsx
@@ -0,0 +1,75 @@
+import { useState, useEffect } from 'react'
+import CopyToClipboard from 'react-copy-to-clipboard'
+import { Button, IconCheck, IconClipboard, IconSave } from 'ui'
+import { useCommandMenu } from '../CommandMenuProvider'
+
+const SQLOutputActions = ({ answer }: { answer: string }) => {
+ const [showCopied, setShowCopied] = useState(false)
+ const [isSaving, setIsSaving] = useState(false)
+ const [isSaved, setIsSaved] = useState(false)
+
+ const { project, onSaveGeneratedSQL } = useCommandMenu()
+
+ const applyCallback = () =>
+ onSaveGeneratedSQL !== undefined
+ ? new Promise((resolve) => onSaveGeneratedSQL(answer, resolve))
+ : {}
+
+ const onSelectSaveSnippet = async () => {
+ setIsSaving(true)
+ await applyCallback()
+ setIsSaved(true)
+ setIsSaving(false)
+ }
+
+ useEffect(() => {
+ if (!showCopied) return
+ const timer = setTimeout(() => setShowCopied(false), 2000)
+ return () => clearTimeout(timer)
+ }, [showCopied])
+
+ useEffect(() => {
+ if (!isSaved) return
+ const timer = setTimeout(() => setIsSaved(false), 2000)
+ return () => clearTimeout(timer)
+ }, [isSaved])
+
+ return (
+ <div className="flex items-center justify-end space-x-2">
+ <CopyToClipboard text={answer?.replace(/```.*/g, '').trim()}>
+ <Button
+ type="default"
+ icon={
+ showCopied ? (
+ <IconCheck size="tiny" className="text-brand-900" strokeWidth={2} />
+ ) : (
+ <IconClipboard size="tiny" />
+ )
+ }
+ onClick={() => setShowCopied(true)}
+ >
+ {showCopied ? 'Copied' : 'Copy SQL'}
+ </Button>
+ </CopyToClipboard>
+ {project?.ref !== undefined && onSaveGeneratedSQL !== undefined && (
+ <Button
+ type="default"
+ loading={isSaving}
+ disabled={isSaving}
+ icon={
+ isSaved ? (
+ <IconCheck size="tiny" className="text-brand-900" strokeWidth={2} />
+ ) : (
+ <IconSave size="tiny" />
+ )
+ }
+ onClick={() => onSelectSaveSnippet()}
+ >
+ {isSaved ? 'Snippet saved!' : 'Save into new snippet'}
+ </Button>
+ )}
+ </div>
+ )
+}
+
+export default SQLOutputActions
diff --git a/packages/ui/src/components/Command/GenerateSQL/index.ts b/packages/ui/src/components/Command/GenerateSQL/index.ts
new file mode 100644
index 00000000000..13cc54742fc
--- /dev/null
+++ b/packages/ui/src/components/Command/GenerateSQL/index.ts
@@ -0,0 +1,3 @@
+import GenerateSQL from './GenerateSQL'
+
+export default GenerateSQL
diff --git a/studio/components/interfaces/Organization/GeneralSettings/GeneralSettings.tsx b/studio/components/interfaces/Organization/GeneralSettings/GeneralSettings.tsx
index 268bd071836..7593c031587 100644
--- a/studio/components/interfaces/Organization/GeneralSettings/GeneralSettings.tsx
+++ b/studio/components/interfaces/Organization/GeneralSettings/GeneralSettings.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useState } from 'react'
+import { useEffect } from 'react'
import { observer } from 'mobx-react-lite'
import { Form, Input, Toggle } from 'ui'
import { PermissionAction } from '@supabase/shared-types/out/constants'
@@ -22,21 +22,9 @@ const GeneralSettings = () => {
const { slug } = useParams()
const { name, opt_in_tags } = ui.selectedOrganization ?? {}
- const [optIn, setOptIn] = useState(
- opt_in_tags?.includes('AI_SQL_GENERATOR_OPT_IN') ? true : false
- )
- const isOptedInToAI = opt_in_tags?.includes('AI_SQL_GENERATOR_OPT_IN')
-
- useEffect(() => {
- setOptIn(isOptedInToAI ? true : false)
- }, [opt_in_tags])
-
+ const isOptedIntoAi = opt_in_tags?.includes('AI_SQL_GENERATOR_OPT_IN')
const formId = 'org-general-settings'
-
- const initialValues = {
- name: name ?? '',
- opt_in_tags: optIn,
- }
+ const initialValues = { name: name ?? '', isOptedIntoAi }
const canUpdateOrganization = checkPermissions(PermissionAction.UPDATE, 'organizations')
const canDeleteOrganization = checkPermissions(PermissionAction.UPDATE, 'organizations')
@@ -51,12 +39,12 @@ const GeneralSettings = () => {
setSubmitting(true)
+ // [Joshen] Need to update this logic once we support multiple opt in tags
+ const optInTags = values.isOptedIntoAi ? ['AI_SQL_GENERATOR_OPT_IN'] : []
const response = await patch(`${API_URL}/organizations/${slug}`, {
- ...values,
- opt_in_tags: optIn
- ? [...(ui.selectedOrganization?.opt_in_tags ?? []), 'AI_SQL_GENERATOR_OPT_IN']
- : [],
+ name: values.name,
billing_email: ui.selectedOrganization?.billing_email ?? '',
+ opt_in_tags: optInTags,
})
if (response.error) {
@@ -65,17 +53,9 @@ const GeneralSettings = () => {
message: `Failed to update organization: ${response.error.message}`,
})
} else {
- const { name, opt_in_tags } = response
- resetForm({
- values: { name, opt_in_tags },
- initialValues: { name, opt_in_tags },
- })
-
+ resetForm({ values, initialValues: values })
app.onOrgUpdated(response)
- ui.setNotification({
- category: 'success',
- message: 'Successfully saved settings',
- })
+ ui.setNotification({ category: 'success', message: 'Successfully saved settings' })
}
setSubmitting(false)
}
@@ -87,10 +67,7 @@ const GeneralSettings = () => {
const hasChanges = JSON.stringify(values) !== JSON.stringify(initialValues)
useEffect(() => {
- const values = {
- name: name ?? '',
- opt_in_tags: isOptedInToAI ?? false,
- }
+ const values = { name: name ?? '', isOptedIntoAi }
resetForm({ values, initialValues: values })
}, [ui.selectedOrganization?.slug])
@@ -118,12 +95,10 @@ const GeneralSettings = () => {
<Input id="name" size="small" disabled={!canUpdateOrganization} />
<Toggle
- checked={isOptedInToAI}
- id="opt_in_tags"
- name="opt_in_tags"
+ id="isOptedIntoAi"
+ name="isOptedIntoAi"
disabled={!canUpdateOrganization}
size="small"
- onChange={() => setOptIn(!optIn)}
label="Opt-in to sending anonymous data to OpenAI"
descriptionText="You can choose to share anonymous metadata with OpenAI to enhance your experience on Supabase anywhere we use AI. Only information such as table schemas with table names, column names, and data types will be shared. None of your actual table data will be sent to OpenAI."
/>