Skip to content

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

Hybrid RLS Assistant (#21806)

Joshen Lim4327d58df52d
diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyEditorPanel.utils.ts b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyEditorPanel.utils.ts
index d15b78a73d4..064e627c017 100644
--- a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyEditorPanel.utils.ts
+++ b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyEditorPanel.utils.ts
@@ -1,6 +1,7 @@
import type { PostgresPolicy } from '@supabase/postgres-meta'
import { Message } from 'ai/react'
import { uuidv4 } from 'lib/helpers'
+import { isEqual } from 'lodash'
export type MessageWithDebug = Message & { isDebug: boolean }
@@ -77,3 +78,86 @@ ${policy.check ? `WITH CHECK (${policy.check})` : ''}
;
`.trim()
}
+
+export const generateCreatePolicyQuery = ({
+ name,
+ schema,
+ table,
+ behavior,
+ command,
+ roles,
+ using,
+ check,
+}: {
+ name: string
+ schema: string
+ table: string
+ behavior: string
+ command: string
+ roles: string
+ using?: string
+ check?: string
+}) => {
+ const querySkeleton = `create policy "${name}" on "${schema}"."${table}" as ${behavior} for ${command} to ${roles}`
+ const query =
+ command === 'insert'
+ ? `${querySkeleton} with check (${check});`
+ : `${querySkeleton} using (${using})${(check ?? '').length > 0 ? `with check (${check});` : ';'}`
+ return query
+}
+
+export const generateAlterPolicyQuery = ({
+ name,
+ newName,
+ schema,
+ table,
+ command,
+ roles,
+ using,
+ check,
+}: {
+ name: string
+ newName: string
+ schema: string
+ table: string
+ command: string
+ roles: string
+ using: string
+ check: string
+}) => {
+ const querySkeleton = `alter policy "${name}" on "${schema}"."${table}" to ${roles}`
+ const query =
+ command === 'insert'
+ ? `${querySkeleton} with check (${check});`
+ : `${querySkeleton} using (${using})${(check ?? '').length > 0 ? `with check (${check});` : ';'}`
+ if (newName === name) return query
+ else return `${query}\n${querySkeleton} rename to "${newName}"`
+}
+
+export const checkIfPolicyHasChanged = (
+ selectedPolicy: PostgresPolicy,
+ policyForm: {
+ name: string
+ roles: string[]
+ check: string | null
+ definition: string | null
+ }
+) => {
+ if (selectedPolicy.command === 'INSERT' && selectedPolicy.check !== policyForm.check) {
+ return true
+ }
+ if (
+ selectedPolicy.command !== 'INSERT' &&
+ (selectedPolicy.definition !== policyForm.definition ||
+ selectedPolicy.check !== policyForm.check)
+ ) {
+ return true
+ }
+ if (selectedPolicy.name !== policyForm.name) {
+ return true
+ }
+ if (!isEqual(selectedPolicy.roles, policyForm.roles)) {
+ return true
+ }
+ return false
+}
diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyHeader.tsx b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyHeader.tsx
index e3c23df101e..f9c2eb98f55 100644
--- a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyHeader.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyHeader.tsx
@@ -1,7 +1,13 @@
import type { PostgresPolicy } from '@supabase/postgres-meta'
import { PanelLeftClose, PanelRightClose, X } from 'lucide-react'
+import { useState } from 'react'
+import { useIsRLSAIAssistantEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'
import {
+ CollapsibleContent_Shadcn_,
+ CollapsibleTrigger_Shadcn_,
+ Collapsible_Shadcn_,
+ IconChevronDown,
SheetClose,
SheetHeader,
SheetTitle,
@@ -20,31 +26,87 @@ export const AIPolicyHeader = ({
assistantVisible: boolean
setAssistantVisible: (v: boolean) => void
}) => {
+ const [showDetails, setShowDetails] = useState(false)
+ const isAiAssistantEnabled = useIsRLSAIAssistantEnabled()
+
return (
- <SheetHeader
- className={cn(
- selectedPolicy !== undefined ? 'pt-3 pb-0' : 'py-3',
- 'flex flex-row justify-between items-center'
- )}
- >
- <div className="flex flex-row gap-3 items-center max-w-[75%]">
+ <SheetHeader className={cn('py-3 flex flex-row justify-between items-start border-b')}>
+ <div
+ className={`flex flex-row gap-3 max-w-[75%] ${isAiAssistantEnabled ? 'items-start' : 'items-center'}`}
+ >
<SheetClose
className={cn(
'text-muted hover:text ring-offset-background transition-opacity hover:opacity-100',
'focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',
- 'disabled:pointer-events-none data-[state=open]:bg-secondary',
- 'transition'
+ 'transition disabled:pointer-events-none data-[state=open]:bg-secondary',
+ isAiAssistantEnabled ? 'mt-1.5' : ''
)}
>
<X className="h-3 w-3" />
<span className="sr-only">Close</span>
</SheetClose>
<div className="h-[24px] w-[1px] bg-border-overlay" />
- <SheetTitle className="truncate">
- {selectedPolicy !== undefined
- ? `Update policy: ${selectedPolicy.name}`
- : 'Create a new Row Level Security policy'}
- </SheetTitle>
+ <div>
+ <SheetTitle className="truncate">
+ {selectedPolicy !== undefined
+ ? `Update policy: ${selectedPolicy.name}`
+ : 'Create a new Row Level Security policy'}
+ </SheetTitle>
+ {isAiAssistantEnabled && selectedPolicy !== undefined && (
+ <Collapsible_Shadcn_
+ className="-mt-1.5 pb-1.5"
+ open={showDetails}
+ onOpenChange={setShowDetails}
+ >
+ <CollapsibleTrigger_Shadcn_ className="group font-normal p-0 [&[data-state=open]>div>svg]:!-rotate-180">
+ <div className="flex items-center gap-x-2 w-full">
+ <p className="text-xs text-foreground-light group-hover:text-foreground transition">
+ View policy details
+ </p>
+ <IconChevronDown
+ className="transition-transform duration-200"
+ strokeWidth={1.5}
+ size={14}
+ />
+ </div>
+ </CollapsibleTrigger_Shadcn_>
+ <CollapsibleContent_Shadcn_ className="grid gap-1.5">
+ <div className="flex my-2">
+ <div>
+ <div className="text-xs flex items-start space-x-2 border-b py-1.5">
+ <p className="w-[110px] text-foreground-light">Name:</p>
+ <p className="pr-4">{selectedPolicy?.name}</p>
+ </div>
+ <div className="text-xs flex items-start space-x-2 border-b py-1.5">
+ <p className="w-[110px] text-foreground-light">Action:</p>
+ <p className="font-mono pr-4">{selectedPolicy?.action}</p>
+ </div>
+ <div className="text-xs flex items-start space-x-2 border-b py-1.5">
+ <p className="w-[110px] text-foreground-light">Command:</p>
+ <p className="font-mono pr-4">{selectedPolicy?.command}</p>
+ </div>
+ <div className="text-xs flex items-start space-x-2 border-b py-1.5">
+ <p className="w-[110px] text-foreground-light">Target roles:</p>
+ <p className="font-mono pr-4">{selectedPolicy?.roles.join(', ')}</p>
+ </div>
+ <div className="text-xs flex items-start space-x-2 border-b py-1.5">
+ <p className="w-[110px] text-foreground-light">USING expression:</p>
+ <p className="font-mono pr-4">{selectedPolicy?.definition}</p>
+ </div>
+ <div className="text-xs flex items-start space-x-2 pt-1.5">
+ <p className="w-[110px] text-foreground-light">CHECK expression:</p>
+ <p
+ className={`${selectedPolicy?.check ? '' : 'text-foreground-light'} font-mono pr-4`}
+ >
+ {selectedPolicy?.check ?? 'None'}
+ </p>
+ </div>
+ </div>
+ </div>
+ </CollapsibleContent_Shadcn_>
+ </Collapsible_Shadcn_>
+ )}
+ </div>
</div>
<Tooltip_Shadcn_>
<TooltipTrigger_Shadcn_ asChild>
@@ -53,8 +115,7 @@ export const AIPolicyHeader = ({
aria-controls="ai-chat-assistant"
className={cn(
!assistantVisible ? 'text-foreground-lighter' : 'text-light',
- 'hover:text-foreground',
- 'transition'
+ 'mt-1 hover:text-foreground transition'
)}
onClick={() => setAssistantVisible(!assistantVisible)}
>
diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/LockedQuerySection.tsx b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/LockedQuerySection.tsx
new file mode 100644
index 00000000000..02dd1daac6b
--- /dev/null
+++ b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/LockedQuerySection.tsx
@@ -0,0 +1,171 @@
+import { PostgresPolicy } from '@supabase/postgres-meta'
+import { Lock } from 'lucide-react'
+import { useRouter } from 'next/router'
+
+import { useParams } from 'common'
+import { useTableEditorStateSnapshot } from 'state/table-editor'
+import { Button } from 'ui'
+import { generateAlterPolicyQuery, generateCreatePolicyQuery } from './AIPolicyEditorPanel.utils'
+
+interface LockedCreateQuerySection {
+ selectedPolicy?: PostgresPolicy
+ formFields: { name: string; table: string; behavior: string; command: string; roles: string }
+ editorOneRef: any
+ editorTwoRef: any
+}
+
+export const LockedCreateQuerySection = ({
+ selectedPolicy,
+ formFields,
+ editorOneRef,
+ editorTwoRef,
+}: LockedCreateQuerySection) => {
+ const router = useRouter()
+ const { ref } = useParams()
+ const state = useTableEditorStateSnapshot()
+
+ const isEditing = selectedPolicy !== undefined
+ const { name, table, behavior, command, roles } = formFields
+
+ return (
+ <div className="bg-surface-300 pt-2 pb-1">
+ <div className="flex items-center justify-between px-5 mb-1">
+ <div className="flex items-center">
+ <div className="pl-0.5 pr-5 flex items-center justify-center">
+ <Lock size={14} className="text-foreground-lighter" />
+ </div>
+ <p className="text-xs text-foreground-lighter font-mono uppercase">
+ Use options above to edit
+ </p>
+ </div>
+ <Button
+ type="default"
+ onClick={() => {
+ const query = isEditing
+ ? generateCreatePolicyQuery({
+ name,
+ schema: state.selectedSchemaName,
+ table,
+ behavior,
+ command,
+ roles: roles.length === 0 ? 'public' : roles,
+ using: (editorOneRef.current?.getValue() ?? undefined)?.trim(),
+ check:
+ command === 'insert'
+ ? (editorOneRef.current?.getValue() ?? undefined)?.trim()
+ : (editorTwoRef.current?.getValue() ?? undefined)?.trim(),
+ })
+ : generateAlterPolicyQuery({
+ name: '',
+ newName: name,
+ schema: state.selectedSchemaName,
+ table,
+ command,
+ roles: roles.length === 0 ? 'public' : roles,
+ using: (editorOneRef.current?.getValue() ?? undefined)?.trim(),
+ check:
+ command === 'insert'
+ ? (editorOneRef.current?.getValue() ?? undefined)?.trim()
+ : (editorTwoRef.current?.getValue() ?? undefined)?.trim(),
+ })
+ router.push(`/project/${ref}/sql/new?content=${query}`)
+ }}
+ >
+ Open in SQL Editor
+ </Button>
+ </div>
+ <div className="flex items-start" style={{ fontSize: '14px' }}>
+ <p className="px-6 font-mono text-sm text-foreground-light select-none">1</p>
+ <p className="font-mono tracking-tighter">
+ <span className="text-[#569cd6]">{isEditing ? 'alter' : 'create'}</span> policy "
+ {name.length === 0 ? 'policy_name' : name}"
+ </p>
+ </div>
+ <div className="flex items-start" style={{ fontSize: '14px' }}>
+ <p className="px-6 font-mono text-sm text-foreground-light select-none">2</p>
+ <p className="font-mono tracking-tighter">
+ <span className="text-[#569cd6]">on</span> "{state.selectedSchemaName}"."
+ {table}"
+ </p>
+ </div>
+ {!isEditing && (
+ <>
+ <div className="flex items-start" style={{ fontSize: '14px' }}>
+ <p className="px-6 font-mono text-sm text-foreground-light select-none">3</p>
+ <p className="font-mono tracking-tighter">
+ <span className="text-[#569cd6]">as</span> {behavior.toLocaleUpperCase()}
+ </p>
+ </div>
+ <div className="flex items-start" style={{ fontSize: '14px' }}>
+ <p className="px-6 font-mono text-sm text-foreground-light select-none">4</p>
+ <p className="font-mono tracking-tighter">
+ <span className="text-[#569cd6]">for</span> {command.toLocaleUpperCase()}
+ </p>
+ </div>
+ </>
+ )}
+ <div className="flex items-start" style={{ fontSize: '14px' }}>
+ <p className="px-6 font-mono text-sm text-foreground-light select-none">5</p>
+ <p className="font-mono tracking-tighter">
+ <span className="text-[#569cd6]">to</span> {roles.length === 0 ? 'public' : roles}
+ </p>
+ </div>
+ <div className="flex items-start" style={{ fontSize: '14px' }}>
+ <p className="px-6 font-mono text-sm text-foreground-light select-none">6</p>
+ <p className="font-mono tracking-tighter">
+ <span className="text-[#569cd6]">{command === 'insert' ? 'with check' : 'using'}</span>{' '}
+ <span className="text-[#ffd700]">(</span>
+ </p>
+ </div>
+ </div>
+ )
+}
+
+export const LockedRenameQuerySection = ({
+ oldName,
+ newName,
+ table,
+ lineNumber,
+}: {
+ oldName: string
+ newName: string
+ table: string
+ lineNumber: number
+}) => {
+ const state = useTableEditorStateSnapshot()
+
+ return (
+ <div className="bg-surface-300 py-1">
+ <div className="flex items-center" style={{ fontSize: '14px' }}>
+ <div className="w-[57px]">
+ <p className="w-[31px] flex justify-end font-mono text-sm text-foreground-light select-none">
+ {lineNumber}
+ </p>
+ </div>
+ <p className="font-mono tracking-tighter">
+ <span className="text-[#569cd6]">alter</span> policy {oldName}
+ </p>
+ </div>
+ <div className="flex items-center" style={{ fontSize: '14px' }}>
+ <div className="w-[57px]">
+ <p className="w-[31px] flex justify-end font-mono text-sm text-foreground-light select-none">
+ {lineNumber + 1}
+ </p>
+ </div>
+ <p className="font-mono tracking-tighter">
+ <span className="text-[#569cd6]">on</span> "{state.selectedSchemaName}"."{table}"
+ </p>
+ </div>
+ <div className="flex items-center" style={{ fontSize: '14px' }}>
+ <div className="w-[57px]">
+ <p className="w-[31px] flex justify-end font-mono text-sm text-foreground-light select-none">
+ {lineNumber + 2}
+ </p>
+ </div>
+ <p className="font-mono tracking-tighter">
+ <span className="text-[#569cd6]">rename</span> to "{newName}";
+ </p>
+ </div>
+ </div>
+ )
+}
diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/PolicyDetails.tsx b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/PolicyDetails.tsx
deleted file mode 100644
index e5148c1faa9..00000000000
--- a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/PolicyDetails.tsx
+++ /dev/null
@@ -1,72 +0,0 @@
-import type { PostgresPolicy } from '@supabase/postgres-meta'
-import {
- CollapsibleContent_Shadcn_,
- CollapsibleTrigger_Shadcn_,
- Collapsible_Shadcn_,
- IconChevronDown,
-} from 'ui'
-
-interface PolicyDetailsProps {
- policy?: PostgresPolicy
- showDetails: boolean
- toggleShowDetails: () => void
-}
-
-const PolicyDetails = ({ policy, showDetails, toggleShowDetails }: PolicyDetailsProps) => {
- if (!policy) return null
-
- return (
- <Collapsible_Shadcn_
- className="-mt-1.5 pb-1.5"
- open={showDetails}
- onOpenChange={toggleShowDetails}
- >
- <CollapsibleTrigger_Shadcn_ className="group pl-[3.6rem] font-normal p-0 [&[data-state=open]>div>svg]:!-rotate-180">
- <div className="flex items-center gap-x-2 w-full">
- <p className="text-xs text-foreground-light group-hover:text-foreground transition">
- View policy details
- </p>
- <IconChevronDown
- className="transition-transform duration-200"
- strokeWidth={1.5}
- size={14}
- />
- </div>
- </CollapsibleTrigger_Shadcn_>
- <CollapsibleContent_Shadcn_ className="pl-[3.6rem] grid gap-1.5">
- <div className="flex my-2">
- <div>
- <div className="text-xs flex items-start space-x-2 border-b py-1.5">
- <p className="w-[110px] text-foreground-light">Name:</p>
- <p className="pr-4">{policy.name}</p>
- </div>
- <div className="text-xs flex items-start space-x-2 border-b py-1.5">
- <p className="w-[110px] text-foreground-light">Action:</p>
- <p className="font-mono pr-4">{policy.action}</p>
- </div>
- <div className="text-xs flex items-start space-x-2 border-b py-1.5">
- <p className="w-[110px] text-foreground-light">Command:</p>
- <p className="font-mono pr-4">{policy.command}</p>
- </div>
- <div className="text-xs flex items-start space-x-2 border-b py-1.5">
- <p className="w-[110px] text-foreground-light">Target roles:</p>
- <p className="font-mono pr-4">{policy.roles.join(', ')}</p>
- </div>
- <div className="text-xs flex items-start space-x-2 border-b py-1.5">
- <p className="w-[110px] text-foreground-light">USING expression:</p>
- <p className="font-mono pr-4">{policy.definition}</p>
- </div>
- <div className="text-xs flex items-start space-x-2 pt-1.5">
- <p className="w-[110px] text-foreground-light">CHECK expression:</p>
- <p className={`${policy.check ? '' : 'text-foreground-light'} font-mono pr-4`}>
- {policy.check ?? 'None'}
- </p>
- </div>
- </div>
- </div>
- </CollapsibleContent_Shadcn_>
- </Collapsible_Shadcn_>
- )
-}
-
-export default PolicyDetails
diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/PolicyDetailsV2.tsx b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/PolicyDetailsV2.tsx
new file mode 100644
index 00000000000..4770cec345c
--- /dev/null
+++ b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/PolicyDetailsV2.tsx
@@ -0,0 +1,228 @@
+import { useEffect } from 'react'
+
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { useDatabaseRolesQuery } from 'data/database-roles/database-roles-query'
+import { useTablesQuery } from 'data/tables/tables-query'
+import { useTableEditorStateSnapshot } from 'state/table-editor'
+import {
+ FormControl_Shadcn_,
+ FormField_Shadcn_,
+ FormItem_Shadcn_,
+ FormLabel_Shadcn_,
+ FormMessage_Shadcn_,
+ Input_Shadcn_,
+ RadioGroupLargeItem_Shadcn_,
+ RadioGroup_Shadcn_,
+ SelectContent_Shadcn_,
+ SelectGroup_Shadcn_,
+ SelectItem_Shadcn_,
+ SelectTrigger_Shadcn_,
+ Select_Shadcn_,
+} from 'ui'
+import { MultiSelectV2 } from 'ui-patterns/MultiSelect/MultiSelectV2'
+
+interface PolicyDetailsV2Props {
+ isEditing: boolean
+ form: any
+ onUpdateCommand: (command: string) => void
+}
+
+export const PolicyDetailsV2 = ({ isEditing, form, onUpdateCommand }: PolicyDetailsV2Props) => {
+ const { project } = useProjectContext()
+ const snap = useTableEditorStateSnapshot()
+
+ const { data: tables, isSuccess: isSuccessTables } = useTablesQuery({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ schema: snap.selectedSchemaName,
+ sortByProperty: 'name',
+ includeColumns: true,
+ })
+
+ const { data: dbRoles } = useDatabaseRolesQuery({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ })
+ const formattedRoles = (dbRoles ?? [])
+ .map((role) => {
+ return {
+ id: role.id,
+ name: role.name,
+ value: role.name,
+ disabled: false,
+ }
+ })
+ .sort((a, b) => a.name.localeCompare(b.name))
+
+ useEffect(() => {
+ if (isSuccessTables && tables.length > 0) form.setValue('table', tables[0].name)
+ }, [isSuccessTables, tables])
+
+ return (
+ <>
+ <div className="px-5 py-5 flex flex-col gap-y-4 border-b">
+ <div className="flex items-center justify-between gap-4 grid grid-cols-12">
+ <FormField_Shadcn_
+ control={form.control}
+ name="name"
+ render={({ field }) => (
+ <FormItem_Shadcn_ className="col-span-6 flex flex-col gap-y-1">
+ <FormLabel_Shadcn_>Policy Name</FormLabel_Shadcn_>
+ <FormControl_Shadcn_>
+ <Input_Shadcn_
+ {...field}
+ className="bg-control border-control"
+ placeholder="Provide a name for your policy"
+ />
+ </FormControl_Shadcn_>
+ <FormMessage_Shadcn_ />
+ </FormItem_Shadcn_>
+ )}
+ />
+
+ <FormField_Shadcn_
+ control={form.control}
+ name="table"
+ render={({ field }) => (
+ <FormItem_Shadcn_ className="col-span-6 flex flex-col gap-y-1">
+ <FormLabel_Shadcn_ className="flex items-center gap-x-4">
+ <p className="text-foreground-light text-sm">Table</p>
+ <p className="text-foreground-light text-sm">
+ <code className="text-xs">on</code> clause
+ </p>
+ </FormLabel_Shadcn_>
+ <FormControl_Shadcn_>
+ <Select_Shadcn_
+ disabled={isEditing}
+ value={field.value}
+ onValueChange={(value) => form.setValue('table', value)}
+ >
+ <SelectTrigger_Shadcn_ className="text-sm h-10">
+ {snap.selectedSchemaName}.{field.value}
+ </SelectTrigger_Shadcn_>
+ <SelectContent_Shadcn_>
+ <SelectGroup_Shadcn_>
+ {(tables ?? []).map((table) => (
+ <SelectItem_Shadcn_ key={table.id} value={table.name} className="text-sm">
+ {table.name}
+ </SelectItem_Shadcn_>
+ ))}
+ </SelectGroup_Shadcn_>
+ </SelectContent_Shadcn_>
+ </Select_Shadcn_>
+ </FormControl_Shadcn_>
+ <FormMessage_Shadcn_ />
+ </FormItem_Shadcn_>
+ )}
+ />
+
+ <FormField_Shadcn_
+ control={form.control}
+ name="behavior"
+ render={({ field }) => (
+ <FormItem_Shadcn_ className="col-span-6 flex flex-col gap-y-1">
+ <FormLabel_Shadcn_ className="flex items-center gap-x-4">
+ <p className="text-foreground-light text-sm">Policy Behavior</p>
+ <p className="text-foreground-light text-sm">
+ <code className="text-xs">as</code> clause
+ </p>
+ </FormLabel_Shadcn_>
+ <FormControl_Shadcn_>
+ <Select_Shadcn_
+ disabled={isEditing}
+ value={field.value}
+ onValueChange={(value) => form.setValue('behavior', value)}
+ >
+ <SelectTrigger_Shadcn_ className="text-sm h-10 capitalize">
+ {field.value}
+ </SelectTrigger_Shadcn_>
+ <SelectContent_Shadcn_>
+ <SelectGroup_Shadcn_>
+ <SelectItem_Shadcn_ value="permissive" className="text-sm">
+ <p>Permissive</p>
+ <p className="text-foreground-light text-xs">
+ Policies are combined using the "OR" Boolean operator
+ </p>
+ </SelectItem_Shadcn_>
+ <SelectItem_Shadcn_ value="restrictive" className="text-sm">
+ <p>Restrictive</p>
+ <p className="text-foreground-light text-xs">
+ Policies are combined using the "AND" Boolean operator
+ </p>
+ </SelectItem_Shadcn_>
+ </SelectGroup_Shadcn_>
+ </SelectContent_Shadcn_>
+ </Select_Shadcn_>
+ </FormControl_Shadcn_>
+ <FormMessage_Shadcn_ />
+ </FormItem_Shadcn_>
+ )}
+ />
+
+ <FormField_Shadcn_
+ control={form.control}
+ name="command"
+ render={({ field }) => (
+ <FormItem_Shadcn_ className="col-span-12 flex flex-col gap-y-1">
+ <FormLabel_Shadcn_ className="flex items-center gap-x-4">
+ <p className="text-foreground-light text-sm">Policy Command</p>
+ <p className="text-foreground-light text-sm">
+ <code className="text-xs">for</code> clause
+ </p>
+ </FormLabel_Shadcn_>
+ <FormControl_Shadcn_>
+ <RadioGroup_Shadcn_
+ disabled={isEditing}
+ value={field.value}
+ defaultValue={field.value}
+ onValueChange={(value) => {
+ form.setValue('command', value)
+ onUpdateCommand(value)
+ }}
+ className={`grid grid-cols-10 gap-3 ${isEditing ? 'opacity-50' : ''}`}
+ >
+ {['select', 'insert', 'update', 'delete', 'all'].map((x) => (
+ <RadioGroupLargeItem_Shadcn_
+ key={x}
+ value={x}
+ disabled={isEditing}
+ label={x.toLocaleUpperCase()}
+ className={`col-span-2 w-auto ${isEditing ? 'cursor-not-allowed' : ''}`}
+ />
+ ))}
+ </RadioGroup_Shadcn_>
+ </FormControl_Shadcn_>
+ <FormMessage_Shadcn_ />
+ </FormItem_Shadcn_>
+ )}
+ />
+
+ <FormField_Shadcn_
+ control={form.control}
+ name="roles"
+ render={({ field }) => (
+ <FormItem_Shadcn_ className="col-span-12 flex flex-col gap-y-1">
+ <FormLabel_Shadcn_ className="flex items-center gap-x-4">
+ <p className="text-foreground-light text-sm">Target Roles</p>
+ <p className="text-foreground-light text-sm">
+ <code className="text-xs">to</code> clause
+ </p>
+ </FormLabel_Shadcn_>
+ <FormControl_Shadcn_>
+ <MultiSelectV2
+ options={formattedRoles}
+ value={field.value.length === 0 ? [] : field.value?.split(', ')}
+ placeholder="Defaults to all (public) roles if none selected"
+ searchPlaceholder="Search for a role"
+ onChange={(roles) => form.setValue('roles', roles.join(', '))}
+ />
+ </FormControl_Shadcn_>
+ <FormMessage_Shadcn_ />
+ </FormItem_Shadcn_>
+ )}
+ />
+ </div>
+ </div>
+ </>
+ )
+}
diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/PolicyTemplates.tsx b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/PolicyTemplates.tsx
index dfc1b5ceb0c..2a074524dd4 100644
--- a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/PolicyTemplates.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/PolicyTemplates.tsx
@@ -1,3 +1,4 @@
+import { PostgresPolicy } from '@supabase/postgres-meta'
import { Search } from 'lucide-react'
import { useState } from 'react'
import { Badge, HoverCard, HoverCardContent, HoverCardTrigger, Input, cn } from 'ui'
@@ -8,23 +9,35 @@ import CardButton from 'components/ui/CardButton'
import CopyButton from 'components/ui/CopyButton'
import NoSearchResults from 'components/ui/NoSearchResults'
import { getGeneralPolicyTemplates } from '../PolicyEditorModal/PolicyEditorModal.constants'
+import { useTableEditorStateSnapshot } from 'state/table-editor'
interface PolicyTemplatesProps {
+ selectedPolicy?: PostgresPolicy
selectedTemplate?: string
- onSelectTemplate: (template: { id: string; content: string }) => void
+ onSelectTemplate: (template: any) => void
}
-export const PolicyTemplates = ({ selectedTemplate, onSelectTemplate }: PolicyTemplatesProps) => {
+export const PolicyTemplates = ({
+ selectedPolicy,
+ selectedTemplate,
+ onSelectTemplate,
+}: PolicyTemplatesProps) => {
const [search, setSearch] = useState('')
- const templates = getGeneralPolicyTemplates('schema_name', 'table_name')
+ const state = useTableEditorStateSnapshot()
+ const templates = getGeneralPolicyTemplates(state.selectedSchemaName, 'table_name')
+
+ const baseTemplates =
+ selectedPolicy !== undefined
+ ? templates.filter((t) => t.command === selectedPolicy.command)
+ : templates
const filteredTemplates =
search.length > 0
- ? templates.filter(
+ ? baseTemplates.filter(
(template) =>
template.name.toLowerCase().includes(search.toLowerCase()) ||
template.command.toLowerCase().includes(search.toLowerCase())
)
- : templates
+ : baseTemplates
return (
<div className="h-full px-content py-content flex flex-col gap-3">
@@ -47,7 +60,7 @@ export const PolicyTemplates = ({ selectedTemplate, onSelectTemplate }: PolicyTe
<div className="flex flex-col gap-1.5">
{filteredTemplates.map((template) => {
return (
- <HoverCard key={template.id} openDelay={100} closeDelay={0}>
+ <HoverCard key={template.id} openDelay={100} closeDelay={100}>
<HoverCardTrigger>
<CardButton
title={template.name}
@@ -59,7 +72,7 @@ export const PolicyTemplates = ({ selectedTemplate, onSelectTemplate }: PolicyTe
: ''
)}
key={template.id}
- onClick={() => onSelectTemplate({ id: template.id, content: template.statement })}
+ onClick={() => onSelectTemplate(template)}
hideChevron
fixedHeight={false}
icon={
@@ -90,7 +103,7 @@ export const PolicyTemplates = ({ selectedTemplate, onSelectTemplate }: PolicyTe
hideWhenDetached
side="left"
align="center"
- className="w-96 flex"
+ className="w-[500px] flex"
animate="slide-in"
>
<SimpleCodeBlock
diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/RLSCodeEditor.tsx b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/RLSCodeEditor.tsx
index 39691c5082d..3cf30731b8b 100644
--- a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/RLSCodeEditor.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/RLSCodeEditor.tsx
@@ -1,10 +1,10 @@
-import Editor, { OnChange, OnMount } from '@monaco-editor/react'
+import Editor, { Monaco, OnChange, OnMount } from '@monaco-editor/react'
import type { editor } from 'monaco-editor'
import { MutableRefObject, useRef } from 'react'
import { cn } from 'ui'
-import { alignEditor } from 'components/ui/CodeEditor'
import { Markdown } from 'components/interfaces/Markdown'
+import { noop } from 'lodash'
// [Joshen] Is there a way we can just have one single MonacoEditor component that's shared across the dashboard?
// Feels like we're creating multiple copies of Editor
@@ -17,7 +17,13 @@ interface RLSCodeEditorProps {
className?: string
value?: string
placeholder?: string
+ readOnly?: boolean
+
+ lineNumberStart?: number
+ onChange?: () => void
+
editorRef: MutableRefObject<editor.IStandaloneCodeEditor | null>
+ monacoRef?: MutableRefObject<Monaco>
}
const RLSCodeEditor = ({
@@ -27,18 +33,38 @@ const RLSCodeEditor = ({
className,
value,
placeholder,
+ readOnly = false,
+
+ lineNumberStart,
+ onChange = noop,
+
editorRef,
+ monacoRef,
}: RLSCodeEditorProps) => {
const hasValue = useRef<any>()
+ const options: editor.IStandaloneEditorConstructionOptions = {
+ tabSize: 2,
+ fontSize: 13,
+ readOnly,
+ minimap: { enabled: false },
+ wordWrap: 'on' as const,
+ contextmenu: true,
+ lineNumbers:
+ lineNumberStart !== undefined ? (num) => (num + lineNumberStart).toString() : undefined,
+ glyphMargin: undefined,
+ lineNumbersMinChars: 4,
+ folding: undefined,
+ scrollBeyondLastLine: false,
+ }
+
const onMount: OnMount = async (editor, monaco) => {
editorRef.current = editor
- alignEditor(editor)
+ if (monacoRef !== undefined) monacoRef.current = monaco
hasValue.current = editor.createContextKey('hasValue', false)
-
const placeholderEl = document.querySelector('.monaco-placeholder') as HTMLElement | null
- if (placeholderEl) placeholderEl.style.display = 'block'
+ if (placeholderEl && placeholder !== undefined) placeholderEl.style.display = 'block'
editor.addCommand(
monaco.KeyCode.Tab,
@@ -62,7 +88,7 @@ const RLSCodeEditor = ({
editor.focus()
}
- const onChange: OnChange = (value) => {
+ const onChangeContent: OnChange = (value) => {
hasValue.current.set((value ?? '').length > 0)
const placeholderEl = document.querySelector('.monaco-placeholder') as HTMLElement | null
@@ -73,20 +99,8 @@ const RLSCodeEditor = ({
placeholderEl.style.display = 'none'
}
}
- }
- const options = {
- tabSize: 2,
- fontSize: 13,
- readOnly: false,
- minimap: { enabled: false },
- wordWrap: 'on' as const,
- contextmenu: true,
- lineNumbers: undefined,
- glyphMargin: undefined,
- lineNumbersMinChars: 4,
- folding: undefined,
- scrollBeyondLastLine: false,
+ onChange()
}
return (
@@ -101,11 +115,11 @@ const RLSCodeEditor = ({
defaultValue={defaultValue ?? undefined}
options={options}
onMount={onMount}
- onChange={onChange}
+ onChange={onChangeContent}
/>
{placeholder !== undefined && (
<div
- className="monaco-placeholder absolute top-[3px] left-[57px] text-sm pointer-events-none font-mono [&>div>p]:text-foreground-lighter [&>div>p]:!m-0 tracking-tighter"
+ className="monaco-placeholder absolute top-[0px] left-[57px] text-sm pointer-events-none font-mono [&>div>p]:text-foreground-lighter [&>div>p]:!m-0 tracking-tighter"
style={{ display: 'none' }}
>
<Markdown content={placeholder} />
diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/index.tsx b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/index.tsx
index 6e5791fd6c0..0f2d0c1419d 100644
--- a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/index.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/index.tsx
@@ -1,17 +1,20 @@
+import { zodResolver } from '@hookform/resolvers/zod'
import type { PostgresPolicy } from '@supabase/postgres-meta'
import { useQueryClient } from '@tanstack/react-query'
import { useChat } from 'ai/react'
import { useParams, useTelemetryProps } from 'common'
-import { uniqBy } from 'lodash'
+import { isEqual, uniqBy } from 'lodash'
import { FileDiff } from 'lucide-react'
import dynamic from 'next/dynamic'
import { useRouter } from 'next/router'
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { useForm } from 'react-hook-form'
import toast from 'react-hot-toast'
import {
Button,
- IconEdit,
- IconGrid,
+ Checkbox_Shadcn_,
+ Form_Shadcn_,
+ Label_Shadcn_,
Modal,
ScrollArea,
Sheet,
@@ -23,35 +26,42 @@ import {
Tabs_Shadcn_,
cn,
} from 'ui'
+import * as z from 'zod'
+import { Monaco } from '@monaco-editor/react'
+import { useIsRLSAIAssistantEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'
+import { subscriptionHasHipaaAddon } from 'components/interfaces/Billing/Subscription/Subscription.utils'
import {
IStandaloneCodeEditor,
IStandaloneDiffEditor,
} from 'components/interfaces/SQLEditor/SQLEditor.types'
-import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
import { useSqlDebugMutation } from 'data/ai/sql-debug-mutation'
+import { useDatabasePolicyUpdateMutation } from 'data/database-policies/database-policy-update-mutation'
import { databasePoliciesKeys } from 'data/database-policies/keys'
import { useEntityDefinitionsQuery } from 'data/database/entity-definitions-query'
import { QueryResponseError, useExecuteSqlMutation } from 'data/sql/execute-sql-mutation'
+import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
import { useSelectedOrganization, useSelectedProject } from 'hooks'
-import { BASE_PATH, LOCAL_STORAGE_KEYS, OPT_IN_TAGS } from 'lib/constants'
+import { BASE_PATH, OPT_IN_TAGS } from 'lib/constants'
import { uuidv4 } from 'lib/helpers'
import Telemetry from 'lib/telemetry'
-import { useAppStateSnapshot } from 'state/app-state'
+import { useTableEditorStateSnapshot } from 'state/table-editor'
+import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
import { AIPolicyChat } from './AIPolicyChat'
import {
MessageWithDebug,
+ checkIfPolicyHasChanged,
+ generateCreatePolicyQuery,
generatePlaceholder,
generatePolicyDefinition,
generateThreadMessage,
} from './AIPolicyEditorPanel.utils'
import { AIPolicyHeader } from './AIPolicyHeader'
-import PolicyDetails from './PolicyDetails'
+import { LockedCreateQuerySection, LockedRenameQuerySection } from './LockedQuerySection'
+import { PolicyDetailsV2 } from './PolicyDetailsV2'
+import { PolicyTemplates } from './PolicyTemplates'
import QueryError from './QueryError'
import RLSCodeEditor from './RLSCodeEditor'
-import { PolicyTemplates } from './PolicyTemplates'
-import { subscriptionHasHipaaAddon } from 'components/interfaces/Billing/Subscription/Subscription.utils'
-import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
const DiffEditor = dynamic(
() => import('@monaco-editor/react').then(({ DiffEditor }) => DiffEditor),
@@ -72,19 +82,33 @@ export const AIPolicyEditorPanel = memo(function ({
selectedPolicy,
onSelectCancel,
}: AIPolicyEditorPanelProps) {
+ const router = useRouter()
const { ref } = useParams()
const queryClient = useQueryClient()
const selectedProject = useSelectedProject()
const selectedOrganization = useSelectedOrganization()
- const router = useRouter()
- const snap = useAppStateSnapshot()
+
const telemetryProps = useTelemetryProps()
+ const state = useTableEditorStateSnapshot()
+ const isAiAssistantEnabled = useIsRLSAIAssistantEnabled()
+
+ // [Joshen] Hyrid form fields, just spit balling to get a decent POC out
+ const [using, setUsing] = useState('')
+ const [check, setCheck] = useState('')
+ const [showCheckBlock, setShowCheckBlock] = useState(false)
- // use chat id because useChat doesn't have a reset function to clear all messages
+ const monacoOneRef = useRef<Monaco | null>(null)
+ const editorOneRef = useRef<IStandaloneCodeEditor | null>(null)
+ const [expOneLineCount, setExpOneLineCount] = useState(1)
+
+ const monacoTwoRef = useRef<Monaco | null>(null)
+ const editorTwoRef = useRef<IStandaloneCodeEditor | null>(null)
+ const [expTwoLineCount, setExpTwoLineCount] = useState(1)
+
+ // Use chat id because useChat doesn't have a reset function to clear all messages
const [chatId, setChatId] = useState(uuidv4())
- const editorRef = useRef<IStandaloneCodeEditor | null>(null)
+
const diffEditorRef = useRef<IStandaloneDiffEditor | null>(null)
- const isTogglingPreviewRef = useRef<boolean>(false)
const placeholder = generatePlaceholder(selectedPolicy)
const isOptedInToAI = selectedOrganization?.opt_in_tags?.includes(OPT_IN_TAGS.AI_SQL) ?? false
@@ -97,9 +121,31 @@ export const AIPolicyEditorPanel = memo(function ({
const [assistantVisible, setAssistantPanel] = useState<boolean>(false)
const [isAssistantChatInputEmpty, setIsAssistantChatInputEmpty] = useState<boolean>(true)
const [incomingChange, setIncomingChange] = useState<string | undefined>(undefined)
- // used for confirmation when closing the panel with unsaved changes
+ // Used for confirmation when closing the panel with unsaved changes
const [isClosingPolicyEditorPanel, setIsClosingPolicyEditorPanel] = useState<boolean>(false)
+ const formId = 'rls-editor'
+ const FormSchema = z.object({
+ name: z.string(),
+ table: z.string(),
+ behavior: z.string(),
+ command: z.string(),
+ roles: z.string(),
+ })
+ const defaultValues = {
+ name: '',
+ table: '',
+ behavior: 'permissive',
+ command: 'select',
+ roles: '',
+ }
+ const form = useForm<z.infer<typeof FormSchema>>({
+ mode: 'onBlur',
+ reValidateMode: 'onBlur',
+ resolver: zodResolver(FormSchema),
+ defaultValues,
+ })
+
// Customers on HIPAA plans should not have access to Supabase AI
const { data: subscription } = useOrgSubscriptionQuery({ orgSlug: selectedOrganization?.slug })
const hasHipaaAddon = subscriptionHasHipaaAddon(subscription)
@@ -111,9 +157,12 @@ export const AIPolicyEditorPanel = memo(function ({
},
{ enabled: true, refetchOnWindowFocus: false }
)
-
const entityDefinitions = entities?.map((def) => def.sql.trim())
+ const { name, table, behavior, command, roles } = form.watch()
+ const supportWithCheck = ['update', 'all'].includes(command)
+ const isRenamingPolicy = selectedPolicy !== undefined && name !== selectedPolicy.name
+
const {
messages: chatMessages,
append,
@@ -145,80 +194,69 @@ export const AIPolicyEditorPanel = memo(function ({
toast.success('Successfully created new policy')
onSelectCancel()
},
- onError: (error) => {
- setError(error)
+ onError: (error) => setError(error),
+ })
+
+ const { mutate: updatePolicy, isLoading: isUpdating } = useDatabasePolicyUpdateMutation({
+ onSuccess: () => {
+ toast.success('Successfully updated policy')
+ onSelectCancel()
},
})
const { mutateAsync: debugSql, isLoading: isDebugSqlLoading } = useSqlDebugMutation()
- const onExecuteSQL = useCallback(() => {
- // clean up the sql before sending
- const policy = editorRef.current?.getValue().replaceAll(' ', ' ')
-
- if (policy) {
- setError(undefined)
- executeMutation({
- sql: policy,
- projectRef: selectedProject?.ref,
- connectionString: selectedProject?.connectionString,
- handleError: (error) => {
- throw error
- },
- })
- }
- }, [executeMutation, selectedProject?.connectionString, selectedProject?.ref])
-
const acceptChange = useCallback(async () => {
- if (!incomingChange) {
- return
- }
-
- if (!editorRef.current || !diffEditorRef.current) {
- return
- }
+ if (!incomingChange || !editorOneRef.current || !diffEditorRef.current) return
- const editorModel = editorRef.current.getModel()
+ const editorModel = editorOneRef.current.getModel()
const diffModel = diffEditorRef.current.getModel()
-
- if (!editorModel || !diffModel) {
- return
- }
+ if (!editorModel || !diffModel) return
const sql = diffModel.modified.getValue()
// apply the incoming change in the editor directly so that Undo/Redo work properly
- editorRef.current.executeEdits('apply-ai-edit', [
- {
- text: sql,
- range: editorModel.getFullModelRange(),
- },
+ editorOneRef.current.executeEdits('apply-ai-edit', [
+ { text: sql, range: editorModel.getFullModelRange() },
])
// remove the incoming change to revert to the original editor
setIncomingChange(undefined)
}, [incomingChange])
- const toggleFeaturePreviewModal = () => {
- isTogglingPreviewRef.current = true
- onClosingPanel()
- }
-
const onClosingPanel = () => {
- const policy = editorRef.current?.getValue()
- if (policy || messages.length > 0 || !isAssistantChatInputEmpty) {
+ const editorOneValue = editorOneRef.current?.getValue().trim() ?? null
+ const editorOneFormattedValue = !editorOneValue ? null : editorOneValue
+ const editorTwoValue = editorTwoRef.current?.getValue().trim() ?? null
+ const editorTwoFormattedValue = !editorTwoValue ? null : editorTwoValue
+
+ const policyCreateUnsaved =
+ selectedPolicy === undefined &&
+ (name.length > 0 || roles.length > 0 || editorOneFormattedValue || editorTwoFormattedValue)
+ const policyUpdateUnsaved =
+ selectedPolicy !== undefined
+ ? checkIfPolicyHasChanged(selectedPolicy, {
+ name,
+ roles: roles.length === 0 ? ['public'] : roles.split(', '),
+ definition: editorOneFormattedValue,
+ check: command === 'INSERT' ? editorOneFormattedValue : editorTwoFormattedValue,
+ })
+ : false
+
+ if (
+ policyCreateUnsaved ||
+ policyUpdateUnsaved ||
+ messages.length > 0 ||
+ !isAssistantChatInputEmpty
+ ) {
setIsClosingPolicyEditorPanel(true)
} else {
- if (isTogglingPreviewRef.current) {
- snap.setSelectedFeaturePreview(LOCAL_STORAGE_KEYS.UI_PREVIEW_RLS_AI_ASSISTANT)
- snap.setShowFeaturePreviewModal(!snap.showFeaturePreviewModal)
- }
onSelectCancel()
}
}
const onSelectDebug = async () => {
- const policy = editorRef.current?.getValue().replaceAll('\n', ' ').replaceAll(' ', ' ')
+ const policy = editorOneRef.current?.getValue().replaceAll('\n', ' ').replaceAll(' ', ' ')
if (error === undefined || policy === undefined) return
setAssistantPanel(true)
@@ -248,12 +286,12 @@ export const AIPolicyEditorPanel = memo(function ({
}
const updateEditorWithCheckForDiff = (value: { id: string; content: string }) => {
- const editorModel = editorRef.current?.getModel()
+ const editorModel = editorOneRef.current?.getModel()
if (!editorModel) return
- const existingValue = editorRef.current?.getValue() ?? ''
+ const existingValue = editorOneRef.current?.getValue() ?? ''
if (existingValue.length === 0) {
- editorRef.current?.executeEdits('apply-template', [
+ editorOneRef.current?.executeEdits('apply-template', [
{
text: value.content,
range: editorModel.getFullModelRange(),
@@ -265,10 +303,63 @@ export const AIPolicyEditorPanel = memo(function ({
}
}
+ const onSubmit = (data: z.infer<typeof FormSchema>) => {
+ const { name, table, behavior, command, roles } = data
+ const using = editorOneRef.current?.getValue().trim() ?? undefined
+ const check = editorTwoRef.current?.getValue().trim() ?? undefined
+
+ if (selectedPolicy === undefined) {
+ const sql = generateCreatePolicyQuery({
+ name: name,
+ schema: state.selectedSchemaName,
+ table,
+ behavior,
+ command,
+ roles: roles.length === 0 ? 'public' : roles,
+ using: using ?? '',
+ check: command === 'insert' ? using ?? '' : check ?? '',
+ })
+
+ setError(undefined)
+ executeMutation({
+ sql,
+ projectRef: selectedProject?.ref,
+ connectionString: selectedProject?.connectionString,
+ handleError: (error) => {
+ throw error
+ },
+ })
+ } else if (selectedProject !== undefined) {
+ const payload: {
+ name?: string
+ definition?: string
+ check?: string
+ roles?: string[]
+ } = {}
+ const updatedRoles = roles.length === 0 ? ['public'] : roles.split(', ')
+
+ if (name !== selectedPolicy.name) payload.name = name
+ if (!isEqual(selectedPolicy.roles, updatedRoles)) payload.roles = updatedRoles
+ if (selectedPolicy.definition !== null && selectedPolicy.definition !== using)
+ payload.definition = using
+ if (selectedPolicy.check !== null && selectedPolicy.check !== check) payload.check = check
+
+ if (Object.keys(payload).length === 0) return onSelectCancel()
+
+ updatePolicy({
+ id: selectedPolicy.id,
+ projectRef: selectedProject.ref,
+ connectionString: selectedProject?.connectionString,
+ payload,
+ })
+ }
+ }
+
// when the panel is closed, reset all values
useEffect(() => {
if (!visible) {
- editorRef.current?.setValue('')
+ editorOneRef.current?.setValue('')
+ editorTwoRef.current?.setValue('')
setIncomingChange(undefined)
setAssistantPanel(false)
setIsClosingPolicyEditorPanel(false)
@@ -277,244 +368,405 @@ export const AIPolicyEditorPanel = memo(function ({
setChatId(uuidv4())
setShowDetails(false)
setSelectedDiff(undefined)
+
+ setUsing('')
+ setCheck('')
+ setShowCheckBlock(false)
+
+ form.reset(defaultValues)
} else {
setAssistantPanel(true)
+ if (selectedPolicy !== undefined) {
+ const { name, action, table, command, roles } = selectedPolicy
+ form.reset({
+ name,
+ table,
+ behavior: action.toLowerCase(),
+ command: command.toLowerCase(),
+ roles: roles.length === 1 && roles[0] === 'public' ? '' : roles.join(', '),
+ })
+ if (selectedPolicy.definition) setUsing(` ${selectedPolicy.definition}`)
+ if (selectedPolicy.check) setCheck(` ${selectedPolicy.check}`)
+ if (selectedPolicy.check && selectedPolicy.command !== 'INSERT') {
+ setShowCheckBlock(true)
+ }
+ }
}
}, [visible])
// whenever the deps (current policy details, new error or error panel opens) change, recalculate
// the height of the editor
useEffect(() => {
- editorRef.current?.layout({ width: 0, height: 0 })
+ editorOneRef.current?.layout({ width: 0, height: 0 })
window.requestAnimationFrame(() => {
- editorRef.current?.layout()
+ editorOneRef.current?.layout()
})
}, [showDetails, error, errorPanelOpen])
return (
<>
- <Sheet open={visible} onOpenChange={() => onClosingPanel()}>
- <SheetContent
- size={assistantVisible ? 'lg' : 'default'}
- className={cn(
- 'bg-surface-200',
- 'p-0 flex flex-row gap-0',
- assistantVisible ? '!min-w-[1200px]' : '!min-w-[600px]'
- )}
- showClose={false}
- >
- <div className={cn('flex flex-col grow w-full', assistantVisible && 'w-[60%]')}>
- <AIPolicyHeader
- selectedPolicy={selectedPolicy}
- assistantVisible={assistantVisible}
- setAssistantVisible={setAssistantPanel}
- />
- <PolicyDetails
- policy={selectedPolicy}
- showDetails={showDetails}
- toggleShowDetails={() => setShowDetails(!showDetails)}
- />
- <div className="flex flex-col h-full w-full justify-between">
- {incomingChange ? (
- <div className="px-5 py-3 flex justify-between gap-3 bg-surface-75">
- <div className="flex gap-2 items-center text-foreground-light">
- <FileDiff className="h-4 w-4" />
- <span className="text-sm">Accept changes from assistant</span>
- </div>
- <div className="flex gap-3">
- <Button
- type="default"
- onClick={() => {
- setIncomingChange(undefined)
- setSelectedDiff(undefined)
- Telemetry.sendEvent(
- {
- category: 'rls_editor',
- action: 'ai_suggestion_discarded',
- label: 'rls-ai-assistant',
- },
- telemetryProps,
- router
- )
- }}
- >
- Discard
- </Button>
- <Button
- type="primary"
- onClick={() => {
- acceptChange()
- setSelectedDiff(undefined)
- Telemetry.sendEvent(
- {
- category: 'rls_editor',
- action: 'ai_suggestion_accepted',
- label: 'rls-ai-assistant',
- },
- telemetryProps,
- router
- )
- }}
- >
- Accept
- </Button>
- </div>
- </div>
- ) : null}
-
- {incomingChange ? (
- <DiffEditor
- theme="supabase"
- language="pgsql"
- className="grow"
- original={editorRef.current?.getValue()}
- modified={incomingChange}
- onMount={(editor) => (diffEditorRef.current = editor)}
- options={{
- wordWrap: 'on',
- renderSideBySide: false,
- scrollBeyondLastLine: false,
- renderOverviewRuler: false,
- renderLineHighlight: 'none',
- minimap: { enabled: false },
- occurrencesHighlight: false,
- folding: false,
- selectionHighlight: false,
- lineHeight: 20,
- padding: { top: 10, bottom: 10 },
- }}
- />
- ) : null}
- <div className={`relative h-full ${incomingChange ? 'hidden' : 'block'}`}>
- <RLSCodeEditor
- id="rls-sql-policy"
- defaultValue={''}
- editorRef={editorRef}
- placeholder={placeholder}
- />
- </div>
-
- <div className="flex flex-col">
- {error !== undefined && (
- <QueryError
- error={error}
- onSelectDebug={onSelectDebug}
- open={errorPanelOpen}
- setOpen={setErrorPanelOpen}
- />
- )}
- <SheetFooter className="flex items-center !justify-between px-5 py-4 w-full">
- <Button type="text" onClick={toggleFeaturePreviewModal}>
- Toggle feature preview
- </Button>
- <div className="flex items-center gap-x-2">
- <Button type="default" disabled={isExecuting} onClick={() => onSelectCancel()}>
- Cancel
- </Button>
- <Button
- loading={isExecuting}
- htmlType="submit"
- disabled={isExecuting || incomingChange !== undefined}
- onClick={() => onExecuteSQL()}
- >
- Save policy
- </Button>
- </div>
- </SheetFooter>
- </div>
- </div>
- </div>
- {assistantVisible && (
- <div
+ <Form_Shadcn_ {...form}>
+ <form id={formId} onSubmit={form.handleSubmit(onSubmit)}>
+ <Sheet open={visible} onOpenChange={() => onClosingPanel()}>
+ <SheetContent
+ showClose={false}
+ size={assistantVisible ? 'lg' : 'default'}
className={cn(
- 'border-l shadow-[rgba(0,0,0,0.13)_-4px_0px_6px_0px] z-10',
- assistantVisible && 'w-[50%]',
- 'bg-studio'
+ 'bg-surface-200',
+ 'p-0 flex flex-row gap-0',
+ assistantVisible ? '!min-w-[1200px]' : '!min-w-[600px]'
)}
>
- <Tabs_Shadcn_ defaultValue="templates" className="flex flex-col h-full w-full">
- <TabsList_Shadcn_ className="flex gap-4 px-content pt-2">
- <TabsTrigger_Shadcn_
- key="templates"
- value="templates"
- className="px-0 data-[state=active]:bg-transparent"
- >
- Templates
- </TabsTrigger_Shadcn_>
- {!hasHipaaAddon && (
- <TabsTrigger_Shadcn_
- key="conversation"
- value="conversation"
- className="px-0 data-[state=active]:bg-transparent"
- >
- Assistant
- </TabsTrigger_Shadcn_>
+ <div className={cn('flex flex-col grow w-full', assistantVisible && 'w-[60%]')}>
+ <AIPolicyHeader
+ selectedPolicy={selectedPolicy}
+ assistantVisible={assistantVisible}
+ setAssistantVisible={setAssistantPanel}
+ />
+
+ <div className="flex flex-col h-full w-full justify-between overflow-y-auto">
+ {incomingChange ? (
+ <div className="px-5 py-3 flex justify-between gap-3 bg-surface-75">
+ <div className="flex gap-2 items-center text-foreground-light">
+ <FileDiff className="h-4 w-4" />
+ <span className="text-sm">Accept changes from assistant</span>
+ </div>
+ <div className="flex gap-3">
+ <Button
+ type="default"
+ onClick={() => {
+ setIncomingChange(undefined)
+ setSelectedDiff(undefined)
+ Telemetry.sendEvent(
+ {
+ category: 'rls_editor',
+ action: 'ai_suggestion_discarded',
+ label: 'rls-ai-assistant',
+ },
+ telemetryProps,
+ router
+ )
+ }}
+ >
+ Discard
+ </Button>
+ <Button
+ type="primary"
+ onClick={() => {
+ acceptChange()
+ setSelectedDiff(undefined)
+ Telemetry.sendEvent(
+ {
+ category: 'rls_editor',
+ action: 'ai_suggestion_accepted',
+ label: 'rls-ai-assistant',
+ },
+ telemetryProps,
+ router
+ )
+ }}
+ >
+ Accept
+ </Button>
+ </div>
+ </div>
+ ) : null}
+
+ {incomingChange ? (
+ <DiffEditor
+ theme="supabase"
+ language="pgsql"
+ className="grow"
+ original={editorOneRef.current?.getValue()}
+ modified={incomingChange}
+ onMount={(editor) => (diffEditorRef.current = editor)}
+ options={{
+ wordWrap: 'on',
+ renderSideBySide: false,
+ scrollBeyondLastLine: false,
+ renderOverviewRuler: false,
+ renderLineHighlight: 'none',
+ minimap: { enabled: false },
+ occurrencesHighlight: false,
+ folding: false,
+ selectionHighlight: false,
+ lineHeight: 20,
+ padding: { top: 10, bottom: 10 },
+ }}
+ />
+ ) : null}
+
+ {isAiAssistantEnabled ? (
+ <div className={`relative h-full ${incomingChange ? 'hidden' : 'block'}`}>
+ <RLSCodeEditor
+ id="rls-sql-policy"
+ defaultValue={''}
+ editorRef={editorOneRef}
+ placeholder={placeholder}
+ />
+ </div>
+ ) : (
+ <>
+ <PolicyDetailsV2
+ isEditing={selectedPolicy !== undefined}
+ form={form}
+ onUpdateCommand={(command: string) => {
+ if (!['update', 'all'].includes(command)) setShowCheckBlock(false)
+ }}
+ />
+ <div className="h-full">
+ <LockedCreateQuerySection
+ selectedPolicy={selectedPolicy}
+ editorOneRef={editorOneRef}
+ editorTwoRef={editorTwoRef}
+ formFields={{ name, table, behavior, command, roles }}
+ />
+
+ <div
+ className={`py-1 relative ${incomingChange ? 'hidden' : 'block'}`}
+ style={{
+ height:
+ expOneLineCount <= 5 ? `${8 + expOneLineCount * 20}px` : '108px',
+ }}
+ >
+ <RLSCodeEditor
+ id="rls-exp-one-editor"
+ defaultValue={command === 'insert' ? check : using}
+ value={command === 'insert' ? check : using}
+ editorRef={editorOneRef}
+ monacoRef={monacoOneRef as any}
+ lineNumberStart={6}
+ onChange={() => {
+ setExpOneLineCount(
+ editorOneRef.current?.getModel()?.getLineCount() ?? 1
+ )
+ }}
+ />
+ </div>
+
+ <div className="bg-surface-300 py-1">
+ <div className="flex items-center" style={{ fontSize: '14px' }}>
+ <div className="w-[57px]">
+ <p className="w-[31px] flex justify-end font-mono text-sm text-foreground-light select-none">
+ {7 + expOneLineCount}
+ </p>
+ </div>
+ <p className="font-mono tracking-tighter">
+ {showCheckBlock ? (
+ <>
+ <span className="text-[#569cd6]">with check</span>{' '}
+ <span className="text-[#ffd700]">(</span>
+ </>
+ ) : (
+ <>
+ <span className="text-[#ffd700]">)</span>;
+ </>
+ )}
+ </p>
+ </div>
+ </div>
+
+ {showCheckBlock && (
+ <>
+ <div
+ className={`py-1 relative ${incomingChange ? 'hidden' : 'block'}`}
+ style={{
+ height:
+ expTwoLineCount <= 5 ? `${8 + expTwoLineCount * 20}px` : '108px',
+ }}
+ >
+ <RLSCodeEditor
+ id="rls-exp-two-editor"
+ defaultValue={check}
+ value={check}
+ editorRef={editorTwoRef}
+ monacoRef={monacoTwoRef as any}
+ lineNumberStart={7 + expOneLineCount}
+ onChange={() => {
+ setExpTwoLineCount(
+ editorTwoRef.current?.getModel()?.getLineCount() ?? 1
+ )
+ }}
+ />
+ </div>
+ <div className="bg-surface-300 py-1">
+ <div className="flex items-center" style={{ fontSize: '14px' }}>
+ <div className="w-[57px]">
+ <p className="w-[31px] flex justify-end font-mono text-sm text-foreground-light select-none">
+ {8 + expOneLineCount + expTwoLineCount}
+ </p>
+ </div>
+ <p className="font-mono tracking-tighter">
+ <span className="text-[#ffd700]">)</span>;
+ </p>
+ </div>
+ </div>
+ </>
+ )}
+
+ {isRenamingPolicy && (
+ <LockedRenameQuerySection
+ oldName={selectedPolicy.name}
+ newName={name}
+ table={table}
+ lineNumber={
+ 8 + expOneLineCount + (showCheckBlock ? expTwoLineCount : 0)
+ }
+ />
+ )}
+
+ {supportWithCheck && (
+ <div className="px-5 py-3 flex items-center gap-x-2">
+ <Checkbox_Shadcn_
+ id="use-check"
+ name="use-check"
+ checked={showCheckBlock}
+ onCheckedChange={() => setShowCheckBlock(!showCheckBlock)}
+ />
+ <Label_Shadcn_ className="text-xs cursor-pointer" htmlFor="use-check">
+ Use check expression
+ </Label_Shadcn_>
+ </div>
+ )}
+ </div>
+ </>
)}
- </TabsList_Shadcn_>
- <TabsContent_Shadcn_
- value="templates"
+
+ <div className="flex flex-col">
+ {error !== undefined && (
+ <QueryError
+ error={error}
+ onSelectDebug={onSelectDebug}
+ open={errorPanelOpen}
+ setOpen={setErrorPanelOpen}
+ />
+ )}
+ <SheetFooter className="flex items-center !justify-end px-5 py-4 w-full border-t">
+ <Button
+ type="default"
+ disabled={isExecuting || isUpdating}
+ onClick={() => onClosingPanel()}
+ >
+ Cancel
+ </Button>
+ <Button
+ form={formId}
+ htmlType="submit"
+ loading={isExecuting || isUpdating}
+ disabled={isExecuting || isUpdating || incomingChange !== undefined}
+ >
+ Save policy
+ </Button>
+ </SheetFooter>
+ </div>
+ </div>
+ </div>
+ {assistantVisible && (
+ <div
className={cn(
- '!mt-0 overflow-y-auto',
- 'data-[state=active]:flex data-[state=active]:grow'
+ 'border-l shadow-[rgba(0,0,0,0.13)_-4px_0px_6px_0px] z-10',
+ assistantVisible && 'w-[50%]',
+ 'bg-studio'
)}
>
- <ScrollArea className="h-full w-full">
- <PolicyTemplates
- selectedTemplate={selectedDiff}
- onSelectTemplate={updateEditorWithCheckForDiff}
- />
- </ScrollArea>
- </TabsContent_Shadcn_>
- <TabsContent_Shadcn_
- value="conversation"
- className="flex grow !mt-0 overflow-y-auto"
- >
- <AIPolicyChat
- messages={messages}
- selectedMessage={selectedDiff}
- onSubmit={(message) =>
- append({
- content: message,
- role: 'user',
- createdAt: new Date(),
- })
- }
- onDiff={updateEditorWithCheckForDiff}
- onChange={setIsAssistantChatInputEmpty}
- loading={isLoading || isDebugSqlLoading}
- />
- </TabsContent_Shadcn_>
- </Tabs_Shadcn_>
- </div>
- )}
-
- <ConfirmationModal
- visible={isClosingPolicyEditorPanel}
- header="Discard changes"
- buttonLabel="Discard"
- onSelectCancel={() => {
- isTogglingPreviewRef.current = false
- setIsClosingPolicyEditorPanel(false)
- }}
- onSelectConfirm={() => {
- if (isTogglingPreviewRef.current) {
- snap.setSelectedFeaturePreview(LOCAL_STORAGE_KEYS.UI_PREVIEW_RLS_AI_ASSISTANT)
- snap.setShowFeaturePreviewModal(!snap.showFeaturePreviewModal)
- }
- onSelectCancel()
- isTogglingPreviewRef.current = false
- setIsClosingPolicyEditorPanel(false)
- }}
- >
- <Modal.Content>
- <p className="py-4 text-sm text-foreground-light">
- Are you sure you want to close the editor? Any unsaved changes on your policy and
- conversations with the Assistant will be lost.
- </p>
- </Modal.Content>
- </ConfirmationModal>
- </SheetContent>
- </Sheet>
+ <Tabs_Shadcn_ defaultValue="templates" className="flex flex-col h-full w-full">
+ <TabsList_Shadcn_ className="flex gap-4 px-content pt-2">
+ <TabsTrigger_Shadcn_
+ key="templates"
+ value="templates"
+ className="px-0 data-[state=active]:bg-transparent"
+ >
+ Templates
+ </TabsTrigger_Shadcn_>
+ {isAiAssistantEnabled && !hasHipaaAddon && (
+ <TabsTrigger_Shadcn_
+ key="conversation"
+ value="conversation"
+ className="px-0 data-[state=active]:bg-transparent"
+ >
+ Assistant
+ </TabsTrigger_Shadcn_>
+ )}
+ </TabsList_Shadcn_>
+ <TabsContent_Shadcn_
+ value="templates"
+ className={cn(
+ '!mt-0 overflow-y-auto',
+ 'data-[state=active]:flex data-[state=active]:grow'
+ )}
+ >
+ <ScrollArea className="h-full w-full">
+ <PolicyTemplates
+ selectedPolicy={selectedPolicy}
+ selectedTemplate={selectedDiff}
+ onSelectTemplate={(value) => {
+ form.setValue('name', value.name)
+ form.setValue('behavior', 'permissive')
+ form.setValue('command', value.command.toLowerCase())
+ form.setValue('roles', value.roles.join(', ') ?? '')
+
+ setUsing(` ${value.definition}`)
+ setCheck(` ${value.check}`)
+ setExpOneLineCount(1)
+ setExpTwoLineCount(1)
+
+ if (!['update', 'all'].includes(value.command.toLowerCase())) {
+ setShowCheckBlock(false)
+ } else if (value.check.length > 0) {
+ setShowCheckBlock(true)
+ } else {
+ setShowCheckBlock(false)
+ }
+ }}
+ />
+ </ScrollArea>
+ </TabsContent_Shadcn_>
+ <TabsContent_Shadcn_
+ value="conversation"
+ className="flex grow !mt-0 overflow-y-auto"
+ >
+ <AIPolicyChat
+ messages={messages}
+ selectedMessage={selectedDiff}
+ onSubmit={(message) =>
+ append({
+ content: message,
+ role: 'user',
+ createdAt: new Date(),
+ })
+ }
+ onDiff={updateEditorWithCheckForDiff}
+ onChange={setIsAssistantChatInputEmpty}
+ loading={isLoading || isDebugSqlLoading}
+ />
+ </TabsContent_Shadcn_>
+ </Tabs_Shadcn_>
+ </div>
+ )}
+ </SheetContent>
+ </Sheet>
+ </form>
+ </Form_Shadcn_>
+
+ <ConfirmationModal
+ visible={isClosingPolicyEditorPanel}
+ header="Discard changes"
+ buttonLabel="Discard"
+ onSelectCancel={() => {
+ setIsClosingPolicyEditorPanel(false)
+ }}
+ onSelectConfirm={() => {
+ onSelectCancel()
+ setIsClosingPolicyEditorPanel(false)
+ }}
+ >
+ <Modal.Content>
+ <p className="py-4 text-sm text-foreground-light">
+ Are you sure you want to close the editor? Any unsaved changes on your policy and
+ conversations with the Assistant will be lost.
+ </p>
+ </Modal.Content>
+ </ConfirmationModal>
</>
)
})
diff --git a/apps/studio/components/interfaces/Auth/Policies/Policies.tsx b/apps/studio/components/interfaces/Auth/Policies/Policies.tsx
index 0848cb88244..14b063ce0f6 100644
--- a/apps/studio/components/interfaces/Auth/Policies/Policies.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/Policies.tsx
@@ -1,24 +1,21 @@
import type { PostgresPolicy, PostgresTable } from '@supabase/postgres-meta'
-import { useParams } from 'common/hooks'
-import { PolicyEditorModal, PolicyTableRow } from 'components/interfaces/Auth/Policies'
import { isEmpty } from 'lodash'
+import { HelpCircle } from 'lucide-react'
import { useRouter } from 'next/router'
-import { useCallback, useState } from 'react'
+import { useState } from 'react'
import toast from 'react-hot-toast'
-import { IconHelpCircle } from 'ui'
-import ConfirmModal from 'ui-patterns/Dialogs/ConfirmDialog'
-import { useIsRLSAIAssistantEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'
+import { useParams } from 'common'
+import { PolicyTableRow } from 'components/interfaces/Auth/Policies'
import ProtectedSchemaWarning from 'components/interfaces/Database/ProtectedSchemaWarning'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import NoSearchResults from 'components/to-be-cleaned/NoSearchResults'
import ProductEmptyState from 'components/to-be-cleaned/ProductEmptyState'
import InformationBox from 'components/ui/InformationBox'
-import { useDatabasePolicyCreateMutation } from 'data/database-policies/database-policy-create-mutation'
import { useDatabasePolicyDeleteMutation } from 'data/database-policies/database-policy-delete-mutation'
-import { useDatabasePolicyUpdateMutation } from 'data/database-policies/database-policy-update-mutation'
import { useTableUpdateMutation } from 'data/tables/table-update-mutation'
import { useTableEditorStateSnapshot } from 'state/table-editor'
+import ConfirmModal from 'ui-patterns/Dialogs/ConfirmDialog'
interface PoliciesProps {
tables: PostgresTable[]
@@ -37,16 +34,10 @@ const Policies = ({
const { ref } = useParams()
const { project } = useProjectContext()
const snap = useTableEditorStateSnapshot()
- const isAiAssistantEnabled = useIsRLSAIAssistantEnabled()
- const [selectedSchemaAndTable, setSelectedSchemaAndTable] = useState<any>({})
const [selectedTableToToggleRLS, setSelectedTableToToggleRLS] = useState<any>({})
- const [RLSEditorWithAIShown, showRLSEditorWithAI] = useState(false)
- const [selectedPolicyToEdit, setSelectedPolicyToEdit] = useState<PostgresPolicy | {}>({})
const [selectedPolicyToDelete, setSelectedPolicyToDelete] = useState<any>({})
- const { mutateAsync: createDatabasePolicy } = useDatabasePolicyCreateMutation()
- const { mutateAsync: updateDatabasePolicy } = useDatabasePolicyUpdateMutation()
const { mutate: updateTable } = useTableUpdateMutation({
onError: (error) => {
toast.error(`Failed to toggle RLS: ${error.message}`)
@@ -64,14 +55,6 @@ const Policies = ({
},
})
- const closePolicyEditorModal = useCallback(() => {
- setSelectedPolicyToEdit({})
- setSelectedSchemaAndTable({})
- if (RLSEditorWithAIShown) {
- showRLSEditorWithAI(false)
- }
- }, [RLSEditorWithAIShown])
-
const closeConfirmModal = () => {
setSelectedPolicyToDelete({})
setSelectedTableToToggleRLS({})
@@ -81,28 +64,14 @@ const Policies = ({
setSelectedTableToToggleRLS(table)
}
- const onSelectCreatePolicy = (table: any) => {
- setSelectedSchemaAndTable({ schema: table.schema, table: table.name })
- }
-
const onSelectEditPolicy = (policy: any) => {
- if (isAiAssistantEnabled) {
- onSelectEditPolicyAI(policy)
- } else {
- setSelectedPolicyToEdit(policy)
- setSelectedSchemaAndTable({ schema: policy.schema, table: policy.table })
- }
+ onSelectEditPolicyAI(policy)
}
const onSelectDeletePolicy = (policy: any) => {
setSelectedPolicyToDelete(policy)
}
- const onSavePolicySuccess = useCallback(async () => {
- toast.success('Policy successfully saved!')
- closePolicyEditorModal()
- }, [closePolicyEditorModal])
-
// Methods that involve some API
const onToggleRLS = async () => {
const payload = {
@@ -119,46 +88,6 @@ const Policies = ({
})
}
- const onCreatePolicy = useCallback(
- async (payload: any) => {
- if (!project) {
- console.error('Project is required')
- return true
- }
-
- try {
- await createDatabasePolicy({
- projectRef: project.ref,
- connectionString: project.connectionString,
- payload,
- })
- return false
- } catch (error) {
- return true
- }
- },
- [project]
- )
-
- const onUpdatePolicy = async (payload: any) => {
- if (!project) {
- console.error('Project is required')
- return true
- }
-
- try {
- await updateDatabasePolicy({
- projectRef: project.ref,
- connectionString: project.connectionString,
- id: payload.id,
- payload,
- })
- return false
- } catch (error) {
- return true
- }
- }
-
const onDeletePolicy = async () => {
if (!project) return console.error('Project is required')
deleteDatabasePolicy({
@@ -182,7 +111,7 @@ const Policies = ({
<div className="space-y-4">
<InformationBox
title="What are policies?"
- icon={<IconHelpCircle strokeWidth={2} />}
+ icon={<HelpCircle size={14} strokeWidth={2} />}
description={
<div className="space-y-2">
<p className="text-sm">
@@ -216,7 +145,6 @@ const Policies = ({
table={table}
isLocked={isLocked}
onSelectToggleRLS={onSelectToggleRLS}
- onSelectCreatePolicy={onSelectCreatePolicy}
onSelectEditPolicy={onSelectEditPolicy}
onSelectDeletePolicy={onSelectDeletePolicy}
/>
@@ -227,18 +155,6 @@ const Policies = ({
) : null}
</div>
- <PolicyEditorModal
- showAssistantPreview
- visible={!isEmpty(selectedSchemaAndTable)}
- schema={selectedSchemaAndTable.schema}
- table={selectedSchemaAndTable.table}
- selectedPolicyToEdit={selectedPolicyToEdit}
- onSelectCancel={closePolicyEditorModal}
- onCreatePolicy={onCreatePolicy}
- onUpdatePolicy={onUpdatePolicy}
- onSaveSuccess={onSavePolicySuccess}
- />
-
<ConfirmModal
danger
visible={!isEmpty(selectedPolicyToDelete)}
diff --git a/apps/studio/components/interfaces/Auth/Policies/PolicyEditorModal/PolicyEditorModal.constants.ts b/apps/studio/components/interfaces/Auth/Policies/PolicyEditorModal/PolicyEditorModal.constants.ts
index e55f8381737..386225f5c18 100644
--- a/apps/studio/components/interfaces/Auth/Policies/PolicyEditorModal/PolicyEditorModal.constants.ts
+++ b/apps/studio/components/interfaces/Auth/Policies/PolicyEditorModal/PolicyEditorModal.constants.ts
@@ -38,7 +38,7 @@ for select using (true);`.trim(),
description: 'This policy gives insert access to your table for all authenticated users only.',
statement: `
create policy "Enable insert for authenticated users only"
-on ${schema}.${table}
+on "${schema}"."${table}"
for insert to authenticated
with check (true);`.trim(),
name: 'Enable insert for authenticated users only',
@@ -55,7 +55,7 @@ with check (true);`.trim(),
'This policy assumes that your table has a column "email", and allows users to update rows which the "email" column matches their email.',
statement: `
create policy "Enable update for users based on email"
-on ${schema}.${table}
+on "${schema}"."${table}"
for update using (
auth.jwt() ->> 'email' = email
) with check (
@@ -75,7 +75,7 @@ for update using (
'This policy assumes that your table has a column "user_id", and allows users to delete rows which the "user_id" column matches their ID',
statement: `
create policy "Enable delete for users based on user_id"
-on ${schema}.${table}
+on "${schema}"."${table}"
for delete using (
auth.uid() = user_id
);`.trim(),
@@ -93,7 +93,7 @@ for delete using (
'This policy assumes that your table has a column "user_id", and allows users to insert rows which the "user_id" column matches their ID',
statement: `
create policy "Enable insert for users based on user_id"
-on ${schema}.${table}
+on "${schema}"."${table}"
for insert with check (
auth.uid() = user_id
);`.trim(),
@@ -113,7 +113,7 @@ Query across tables to build more advanced RLS rules
Assuming 2 tables called \`teams\` and \`members\`, you can query both tables in the policy to control access to the members table.`,
statement: `
-create policy "Team members can update team details if they belong to the team"
+create policy "Members can update team details if they belong to the team"
on teams for update using (
auth.uid() in (
select user_id from members where team_id = id
@@ -159,10 +159,10 @@ for all using (
description: `
Implement a TTL-like feature that you see in Instagram stories or Snapchat where messages expire after a day.
-Assuming a \`stories\` table, rows under the table are available only if they have been created within the last 24 hours.`,
+Rows under the table are available only if they have been created within the last 24 hours.`,
statement: `
create policy "Stories are live for a day"
-on stories
+on "${schema}"."${table}"
for select using (
created_at > (current_timestamp - interval '1 day')
);
diff --git a/apps/studio/components/interfaces/Auth/Policies/PolicyEditorModal/PolicyEditorModalTitle.tsx b/apps/studio/components/interfaces/Auth/Policies/PolicyEditorModal/PolicyEditorModalTitle.tsx
index 8ac09122ea2..27545786dde 100644
--- a/apps/studio/components/interfaces/Auth/Policies/PolicyEditorModal/PolicyEditorModalTitle.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/PolicyEditorModal/PolicyEditorModalTitle.tsx
@@ -1,9 +1,8 @@
import { noop } from 'lodash'
+import { FlaskConical } from 'lucide-react'
import { Button, IconChevronLeft, IconExternalLink } from 'ui'
import { POLICY_MODAL_VIEWS } from 'components/interfaces/Auth/Policies'
-import { FlaskConical } from 'lucide-react'
-import { useAppStateSnapshot } from 'state/app-state'
interface PolicyEditorModalTitleProps {
view: string
@@ -24,8 +23,6 @@ const PolicyEditorModalTitle = ({
onSelectBackFromTemplates = noop,
onToggleFeaturePreviewModal,
}: PolicyEditorModalTitleProps) => {
- const snap = useAppStateSnapshot()
-
const getTitle = () => {
if (view === POLICY_MODAL_VIEWS.EDITOR || view === POLICY_MODAL_VIEWS.SELECTION) {
return `${isNewPolicy ? 'Adding new policy to' : 'Editing policy from'} ${schema}.${table}`
diff --git a/apps/studio/components/interfaces/Auth/Policies/PolicyEditorModal/index.tsx b/apps/studio/components/interfaces/Auth/Policies/PolicyEditorModal/index.tsx
index 83dc6de9ec8..39681d19b41 100644
--- a/apps/studio/components/interfaces/Auth/Policies/PolicyEditorModal/index.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/PolicyEditorModal/index.tsx
@@ -231,9 +231,7 @@ const PolicyEditorModal = ({
onSelectBack={onViewEditor}
onSelectSave={onReviewSave}
/>
- ) : (
- <div />
- )}
+ ) : null}
</div>
</Modal>
)
diff --git a/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyRow.tsx b/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyRow.tsx
index 18f049616b5..c0c8edcf1bb 100644
--- a/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyRow.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyRow.tsx
@@ -84,15 +84,15 @@ const PolicyRow = ({
icon={<IconMoreVertical />}
/>
</DropdownMenuTrigger>
- <DropdownMenuContent side="bottom" align="end" className="w-32">
+ <DropdownMenuContent side="bottom" align="end" className="w-40">
<DropdownMenuItem className="space-x-2" onClick={() => onSelectEditPolicy(policy)}>
<IconEdit size={14} />
- <p>Edit</p>
+ <p>Edit policy</p>
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem className="space-x-2" onClick={() => onSelectDeletePolicy(policy)}>
<IconTrash size={14} />
- <p>Delete</p>
+ <p>Delete policy</p>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
diff --git a/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyTableRowHeader.tsx b/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyTableRowHeader.tsx
index a68d5325b60..314434d2662 100644
--- a/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyTableRowHeader.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyTableRowHeader.tsx
@@ -4,29 +4,24 @@ import { PermissionAction } from '@supabase/shared-types/out/constants'
import { noop } from 'lodash'
import Link from 'next/link'
import { useRouter } from 'next/router'
-import { Badge, Button, IconLock } from 'ui'
import { useCheckPermissions } from 'hooks'
-import { useIsRLSAIAssistantEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'
+import { Badge, Button, IconLock } from 'ui'
interface PolicyTableRowHeaderProps {
table: PostgresTable
isLocked: boolean
onSelectToggleRLS: (table: PostgresTable) => void
- onSelectCreatePolicy: (table: PostgresTable) => void
}
const PolicyTableRowHeader = ({
table,
isLocked,
onSelectToggleRLS = noop,
- onSelectCreatePolicy = noop,
}: PolicyTableRowHeaderProps) => {
const router = useRouter()
const { ref } = router.query
- const isAiAssistantEnabled = useIsRLSAIAssistantEnabled()
const canToggleRLS = useCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'tables')
- const canCreatePolicies = useCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'policies')
return (
<div id={table.id.toString()} className="flex w-full items-center justify-between">
@@ -78,36 +73,6 @@ const PolicyTableRowHeader = ({
</Tooltip.Portal>
)}
</Tooltip.Root>
- {!isAiAssistantEnabled && (
- <Tooltip.Root delayDuration={0}>
- <Tooltip.Trigger asChild>
- <Button
- type="outline"
- disabled={!canCreatePolicies}
- onClick={() => onSelectCreatePolicy(table)}
- >
- New Policy
- </Button>
- </Tooltip.Trigger>
- {!canCreatePolicies && (
- <Tooltip.Portal>
- <Tooltip.Content side="bottom">
- <Tooltip.Arrow className="radix-tooltip-arrow" />
- <div
- className={[
- 'rounded bg-alternative py-1 px-2 leading-none shadow',
- 'border border-background',
- ].join(' ')}
- >
- <span className="text-xs text-foreground">
- You need additional permissions to create RLS policies
- </span>
- </div>
- </Tooltip.Content>
- </Tooltip.Portal>
- )}
- </Tooltip.Root>
- )}
</div>
</div>
)}
diff --git a/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/index.tsx b/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/index.tsx
index b2dc06136fb..999a83a735e 100644
--- a/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/index.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/index.tsx
@@ -13,7 +13,6 @@ interface PolicyTableRowProps {
table: PostgresTable
isLocked: boolean
onSelectToggleRLS: (table: PostgresTable) => void
- onSelectCreatePolicy: (table: PostgresTable) => void
onSelectEditPolicy: (policy: PostgresPolicy) => void
onSelectDeletePolicy: (policy: PostgresPolicy) => void
}
@@ -22,7 +21,6 @@ const PolicyTableRow = ({
table,
isLocked,
onSelectToggleRLS = noop,
- onSelectCreatePolicy = noop,
onSelectEditPolicy = noop,
onSelectDeletePolicy = noop,
}: PolicyTableRowProps) => {
@@ -43,7 +41,6 @@ const PolicyTableRow = ({
table={table}
isLocked={isLocked}
onSelectToggleRLS={onSelectToggleRLS}
- onSelectCreatePolicy={onSelectCreatePolicy}
/>
}
>
diff --git a/apps/studio/components/interfaces/Database/Extensions/EnableExtensionModal.tsx b/apps/studio/components/interfaces/Database/Extensions/EnableExtensionModal.tsx
index 94f8df1e0e4..a657a4469b6 100644
--- a/apps/studio/components/interfaces/Database/Extensions/EnableExtensionModal.tsx
+++ b/apps/studio/components/interfaces/Database/Extensions/EnableExtensionModal.tsx
@@ -197,7 +197,7 @@ const EnableExtensionModal = ({ visible, extension, onCancel }: EnableExtensionM
<AlertDescription_Shadcn_>
You can still enable the extension, but pg_cron jobs may not run due to the
- behaviour of Fly projects.
+ behavior of Fly projects.
</AlertDescription_Shadcn_>
<AlertDescription_Shadcn_ className="mt-3">
diff --git a/apps/studio/components/interfaces/Database/Triggers/CreateTrigger.tsx b/apps/studio/components/interfaces/Database/Triggers/CreateTrigger.tsx
index cab4eb7602c..a06d5df1acb 100644
--- a/apps/studio/components/interfaces/Database/Triggers/CreateTrigger.tsx
+++ b/apps/studio/components/interfaces/Database/Triggers/CreateTrigger.tsx
@@ -458,7 +458,7 @@ const SelectEnabledMode = observer(({}) => {
label="Origin"
>
Origin
- <span className="block text-foreground-lighter">This is a default behaviour</span>
+ <span className="block text-foreground-lighter">This is a default behavior</span>
</Listbox.Option>
<Listbox.Option
addOnBefore={({ active, selected }: any) => {
diff --git a/apps/studio/components/interfaces/Reports/Reports.tsx b/apps/studio/components/interfaces/Reports/Reports.tsx
index 3ac92de5b59..e036c0521dd 100644
--- a/apps/studio/components/interfaces/Reports/Reports.tsx
+++ b/apps/studio/components/interfaces/Reports/Reports.tsx
@@ -193,7 +193,7 @@ const Reports = () => {
/*
* handleChartSelection()
*
- * Handler for the chart behaviour
+ * Handler for the chart behavior
*/
function handleChartSelection({ metric, value }: any) {
if (value) {
diff --git a/apps/studio/data/database-policies/database-policy-update-mutation.ts b/apps/studio/data/database-policies/database-policy-update-mutation.ts
index 6accc7fdc9d..075873820c1 100644
--- a/apps/studio/data/database-policies/database-policy-update-mutation.ts
+++ b/apps/studio/data/database-policies/database-policy-update-mutation.ts
@@ -10,10 +10,10 @@ export type DatabasePolicyUpdateVariables = {
connectionString?: string
id: number
payload: {
- name: string
- definition: string
- check: string
- roles: string[]
+ name?: string
+ definition?: string
+ check?: string
+ roles?: string[]
}
}
diff --git a/apps/studio/data/integrations/github-connections-query.ts b/apps/studio/data/integrations/github-connections-query.ts
index 638445d0297..b173daa6a39 100644
--- a/apps/studio/data/integrations/github-connections-query.ts
+++ b/apps/studio/data/integrations/github-connections-query.ts
@@ -41,6 +41,6 @@ export const useGitHubConnectionsQuery = <TData = GitHubConnectionsData>(
return useQuery<GitHubConnectionsData, GitHubConnectionsError, TData>(
integrationKeys.githubConnectionsList(organizationId),
({ signal }) => getGitHubConnections({ organizationId }, signal),
- { enabled, ...options }
+ { enabled: enabled && typeof organizationId !== 'undefined', ...options }
)
}
diff --git a/apps/studio/pages/project/[ref]/auth/policies.tsx b/apps/studio/pages/project/[ref]/auth/policies.tsx
index 86b2e177206..01c801aae30 100644
--- a/apps/studio/pages/project/[ref]/auth/policies.tsx
+++ b/apps/studio/pages/project/[ref]/auth/policies.tsx
@@ -1,4 +1,3 @@
-import * as Tooltip from '@radix-ui/react-tooltip'
import type { PostgresPolicy, PostgresTable } from '@supabase/postgres-meta'
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { partition } from 'lodash'
@@ -21,7 +20,15 @@ import { useCheckPermissions, usePermissionsLoaded } from 'hooks'
import { EXCLUDED_SCHEMAS } from 'lib/constants/schemas'
import { useTableEditorStateSnapshot } from 'state/table-editor'
import type { NextPageWithLayout } from 'types'
-import { Button, IconExternalLink, IconSearch, Input } from 'ui'
+import {
+ Button,
+ IconExternalLink,
+ IconSearch,
+ Input,
+ TooltipContent_Shadcn_,
+ TooltipTrigger_Shadcn_,
+ Tooltip_Shadcn_,
+} from 'ui'
/**
* Filter tables by table name and policy name
@@ -107,6 +114,7 @@ const AuthPoliciesPage: NextPageWithLayout = () => {
const canReadPolicies = useCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_READ, 'policies')
const canCreatePolicies = useCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'policies')
const isPermissionsLoaded = usePermissionsLoaded()
+ const schemaHasNoTables = (tables ?? []).length === 0
if (isPermissionsLoaded && !canReadPolicies) {
return <NoPermission isFullPage resourceText="view this project's RLS policies" />
@@ -146,36 +154,27 @@ const AuthPoliciesPage: NextPageWithLayout = () => {
Documentation
</a>
</Button>
- {isAiAssistantEnabled && (
- <Tooltip.Root delayDuration={0}>
- <Tooltip.Trigger asChild>
- <Button
- type="primary"
- disabled={!canCreatePolicies}
- onClick={() => setShowPolicyAiEditor(true)}
- >
- Create a new policy
- </Button>
- </Tooltip.Trigger>
- {isPermissionsLoaded && !canCreatePolicies && (
- <Tooltip.Portal>
- <Tooltip.Content side="bottom">
- <Tooltip.Arrow className="radix-tooltip-arrow" />
- <div
- className={[
- 'rounded bg-alternative py-1 px-2 leading-none shadow',
- 'border border-background',
- ].join(' ')}
- >
- <span className="text-xs text-foreground">
- You need additional permissions to create RLS policies
- </span>
- </div>
- </Tooltip.Content>
- </Tooltip.Portal>
- )}
- </Tooltip.Root>
- )}
+
+ <Tooltip_Shadcn_>
+ <TooltipTrigger_Shadcn_ asChild>
+ <Button
+ type="primary"
+ disabled={!canCreatePolicies || schemaHasNoTables}
+ onClick={() => setShowPolicyAiEditor(true)}
+ >
+ Create a new policy
+ </Button>
+ </TooltipTrigger_Shadcn_>
+ {(!canCreatePolicies || schemaHasNoTables) && (
+ <TooltipContent_Shadcn_ side="bottom">
+ {!canCreatePolicies
+ ? 'You need additional permissions to create RLS policies'
+ : schemaHasNoTables
+ ? `No table in schema ${snap.selectedSchemaName} to create policies on`
+ : null}
+ </TooltipContent_Shadcn_>
+ )}
+ </Tooltip_Shadcn_>
</div>
</div>
</div>
diff --git a/apps/studio/pages/project/[ref]/sql/[id].tsx b/apps/studio/pages/project/[ref]/sql/[id].tsx
index 7fa0997cde0..87f616494ce 100644
--- a/apps/studio/pages/project/[ref]/sql/[id].tsx
+++ b/apps/studio/pages/project/[ref]/sql/[id].tsx
@@ -23,7 +23,7 @@ import { useSnippets, useSqlEditorStateSnapshot } from 'state/sql-editor'
const SqlEditor: NextPageWithLayout = () => {
const router = useRouter()
const monaco = useMonaco()
- const { id, ref } = useParams()
+ const { id, ref, content } = useParams()
const { project } = useProjectContext()
const snap = useSqlEditorStateSnapshot()
@@ -103,11 +103,11 @@ const SqlEditor: NextPageWithLayout = () => {
}
useEffect(() => {
- if (id === 'new' && appSnap.dashboardHistory.sql !== undefined) {
+ if (id === 'new' && appSnap.dashboardHistory.sql !== undefined && content === undefined) {
const snippet = snippets.find((snippet) => snippet.id === appSnap.dashboardHistory.sql)
if (snippet !== undefined) router.push(`/project/${ref}/sql/${appSnap.dashboardHistory.sql}`)
}
- }, [id, snippets])
+ }, [id, snippets, content])
// Enable pgsql format
useEffect(() => {
diff --git a/apps/studio/styles/monaco.scss b/apps/studio/styles/monaco.scss
index a1a4d279935..9abbd76e8db 100644
--- a/apps/studio/styles/monaco.scss
+++ b/apps/studio/styles/monaco.scss
@@ -3,6 +3,16 @@
-webkit-text-size-adjust: 100%;
}
+.monaco-editor-alt.monaco-editor-alt,
+.monaco-editor-alt > .monaco-editor {
+ --vscode-editor-background: hsl(var(--background-surface-300)) !important;
+ --vscode-editorGutter-background: hsl(var(--background-surface-300)) !important;
+}
+
+.monaco-editor-alt .current-line {
+ border: 0 !important;
+}
+
.monaco-editor,
.monaco-diff-editor {
--vscode-editor-background: hsl(var(--background-surface-200)) !important;
diff --git a/apps/studio/tests/pages/projects/Logs.utils.test.js b/apps/studio/tests/pages/projects/Logs.utils.test.js
index bcc9cb45868..a03d832a813 100644
--- a/apps/studio/tests/pages/projects/Logs.utils.test.js
+++ b/apps/studio/tests/pages/projects/Logs.utils.test.js
@@ -24,7 +24,7 @@ describe.each(Object.values(LogsTableName))('%s', (table) => {
{ filter: { search_query: undefined } },
{ filter: {} },
{ filter: { search_query: '123test' }, contains: ['123test'] },
- // test behaviour with overrides
+ // test behavior with overrides
{
filter: { search_query: '123test', override: 'something' },
contains: ['123test', 'override', 'something'],
diff --git a/packages/ui-patterns/MultiSelect/MultiSelectV2.tsx b/packages/ui-patterns/MultiSelect/MultiSelectV2.tsx
new file mode 100644
index 00000000000..899e089b1c8
--- /dev/null
+++ b/packages/ui-patterns/MultiSelect/MultiSelectV2.tsx
@@ -0,0 +1,151 @@
+import { orderBy, without } from 'lodash'
+import { Check, ChevronDown } from 'lucide-react'
+import { ReactNode, useState } from 'react'
+import {
+ CommandEmpty_Shadcn_,
+ CommandGroup_Shadcn_,
+ CommandInput_Shadcn_,
+ CommandItem_Shadcn_,
+ CommandList_Shadcn_,
+ Command_Shadcn_,
+ PopoverContent_Shadcn_,
+ PopoverTrigger_Shadcn_,
+ Popover_Shadcn_,
+ ScrollArea,
+ cn,
+} from 'ui'
+import { BadgeDisabled, BadgeSelected } from './Badges'
+
+interface MultiSelectOption {
+ id: string | number
+ value: string
+ name: string
+ description?: string
+ disabled: boolean
+}
+
+interface MultiSelectProps {
+ value: string[]
+ options: MultiSelectOption[]
+ placeholder?: string | ReactNode
+ searchPlaceholder?: string
+ disabled?: boolean
+ onChange?(x: string[]): void
+}
+
+export const MultiSelectV2 = ({
+ options,
+ value,
+ placeholder,
+ searchPlaceholder = 'Search for option',
+ disabled = false,
+ onChange = () => {},
+}: MultiSelectProps) => {
+ const [open, setOpen] = useState(false)
+ const [selected, setSelected] = useState<string[]>(value || [])
+
+ // Selected is `value` if defined, otherwise use local useState
+ const selectedOptions = value || selected
+
+ // Order the options so disabled items are at the beginning
+ const formattedOptions = orderBy(options, ['disabled'], ['desc'])
+
+ const checkIfActive = (option: MultiSelectOption) => {
+ const isOptionSelected = (selectedOptions || []).find((x) => x === option.value)
+ return isOptionSelected !== undefined
+ }
+
+ const handleChange = (option: MultiSelectOption) => {
+ const _selected = selectedOptions
+ const isActive = checkIfActive(option)
+
+ const updatedPayload = isActive
+ ? [...without(_selected, option.value)]
+ : [..._selected.concat([option.value])]
+
+ // Payload must always include disabled options
+ const compulsoryOptions = options
+ .filter((option) => option.disabled)
+ .map((option) => option.name)
+
+ const formattedPayload = [...new Set(updatedPayload.concat(compulsoryOptions))]
+
+ setSelected(formattedPayload)
+ onChange(formattedPayload)
+ }
+
+ return (
+ <div className={disabled ? 'pointer-events-none opacity-50' : ''}>
+ <Popover_Shadcn_ open={open} onOpenChange={setOpen} modal={false}>
+ <PopoverTrigger_Shadcn_ asChild>
+ <div
+ className={cn(
+ 'relative border border-strong bg-control rounded',
+ 'flex w-full flex-wrap items-start gap-1.5 p-1.5 cursor-pointer',
+ `${selectedOptions.length === 0 ? 'h-9' : ''}`
+ )}
+ onClick={() => setOpen(true)}
+ >
+ {selectedOptions.length === 0 && placeholder && (
+ <div className="px-2 text-sm text-foreground-light h-full flex items-center">
+ {placeholder}
+ </div>
+ )}
+ {selectedOptions.map((value, idx) => {
+ const id = `${value}-${idx}`
+ const option = formattedOptions.find((x) => x.value === value)
+ const isDisabled = option?.disabled ?? false
+ if (!option) {
+ return <></>
+ } else if (isDisabled) {
+ return <BadgeDisabled key={id} name={value} />
+ } else {
+ return (
+ <BadgeSelected key={id} name={value} handleRemove={() => handleChange(option)} />
+ )
+ }
+ })}
+ <div className="absolute inset-y-0 right-0 pl-3 pr-2 flex space-x-1 items-center cursor-pointer ">
+ <ChevronDown size={16} strokeWidth={2} className="text-foreground-lighter" />
+ </div>
+ </div>
+ </PopoverTrigger_Shadcn_>
+ <PopoverContent_Shadcn_ className="p-0 w-96 border-strong" side="bottom" align="start">
+ <Command_Shadcn_>
+ <CommandInput_Shadcn_ placeholder={searchPlaceholder} />
+ <CommandList_Shadcn_>
+ <CommandEmpty_Shadcn_>No options found</CommandEmpty_Shadcn_>
+ <CommandGroup_Shadcn_>
+ <ScrollArea className={cn(formattedOptions.length > 5 ? 'h-[225px]' : '')}>
+ {formattedOptions?.map((option) => {
+ const active =
+ selectedOptions &&
+ selectedOptions.find((selected) => {
+ return selected === option.value
+ })
+ ? true
+ : false
+ return (
+ <CommandItem_Shadcn_
+ key={option.id}
+ value={option.value}
+ className="cursor-pointer w-full"
+ onClick={() => handleChange(option)}
+ onSelect={() => handleChange(option)}
+ >
+ <div className="w-full flex items-center justify-between">
+ {option.name}
+ {active && <Check size={14} />}
+ </div>
+ </CommandItem_Shadcn_>
+ )
+ })}
+ </ScrollArea>
+ </CommandGroup_Shadcn_>
+ </CommandList_Shadcn_>
+ </Command_Shadcn_>
+ </PopoverContent_Shadcn_>
+ </Popover_Shadcn_>
+ </div>
+ )
+}
diff --git a/packages/ui-patterns/MultiSelect/index.tsx b/packages/ui-patterns/MultiSelect/index.tsx
index 29d2b4096b5..e0dae0bbce0 100644
--- a/packages/ui-patterns/MultiSelect/index.tsx
+++ b/packages/ui-patterns/MultiSelect/index.tsx
@@ -43,6 +43,9 @@ interface Props {
* input base + standard
*/
+/**
+ * @deprecated To be replaced with MultiSelectV2
+ */
export default function MultiSelect({
options,
value,
@@ -126,7 +129,7 @@ export default function MultiSelect({
<div
className={[
'form-control form-control--multi-select',
- 'border border-strong bg-studio',
+ 'border border-strong bg-control',
'multi-select relative block w-full space-x-1 overflow-auto rounded',
`${error !== undefined ? 'border-red-800 bg-red-100' : ''}`,
].join(' ')}
diff --git a/packages/ui/src/components/shadcn/ui/radio-group.tsx b/packages/ui/src/components/shadcn/ui/radio-group.tsx
index 89c40b4084f..428744662d6 100644
--- a/packages/ui/src/components/shadcn/ui/radio-group.tsx
+++ b/packages/ui/src/components/shadcn/ui/radio-group.tsx
@@ -101,7 +101,7 @@ const RadioGroupLargeItem = React.forwardRef<
'text-xs transition-colors text-left',
'text-light',
'group-hover:text-foreground group-data-[state=checked]:text-foreground',
- 'cursor-pointer'
+ props.disabled ? 'cursor-not-allowed' : 'cursor-pointer'
)}
>
{label}