Skip to content

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

chore(studio): share single-value field array editor (#44059)

Danny White36269df34763
diff --git a/apps/design-system/__registry__/index.tsx b/apps/design-system/__registry__/index.tsx
index f6ba8a7f0cd..cf4f32de518 100644
--- a/apps/design-system/__registry__/index.tsx
+++ b/apps/design-system/__registry__/index.tsx
@@ -445,6 +445,17 @@ export const Index: Record<string, any> = {
subcategory: "undefined",
chunks: []
},
+ "single-value-field-array-demo": {
+ name: "single-value-field-array-demo",
+ type: "components:example",
+ registryDependencies: ["button","form","input"],
+ component: React.lazy(() => import("@/registry/default/example/single-value-field-array-demo")),
+ source: "",
+ files: ["registry/default/example/single-value-field-array-demo.tsx"],
+ category: "undefined",
+ subcategory: "undefined",
+ chunks: []
+ },
"checkbox-demo": {
name: "checkbox-demo",
type: "components:example",
diff --git a/apps/design-system/config/docs.ts b/apps/design-system/config/docs.ts
index d15ae959d9a..afbaae811b8 100644
--- a/apps/design-system/config/docs.ts
+++ b/apps/design-system/config/docs.ts
@@ -217,6 +217,11 @@ export const docsConfig: DocsConfig = {
href: '/docs/fragments/key-value-field-array',
items: [],
},
+ {
+ title: 'Single Value Field Array',
+ href: '/docs/fragments/single-value-field-array',
+ items: [],
+ },
],
},
{
diff --git a/apps/design-system/content/docs/fragments/key-value-field-array.mdx b/apps/design-system/content/docs/fragments/key-value-field-array.mdx
index 2ae4b87649e..0bdd124791a 100644
--- a/apps/design-system/content/docs/fragments/key-value-field-array.mdx
+++ b/apps/design-system/content/docs/fragments/key-value-field-array.mdx
@@ -38,6 +38,6 @@ import { KeyValueFieldArray } from 'ui-patterns/form/KeyValueFieldArray/KeyValue
## When to use it
-- Use a plain field array for repeated single values such as redirect URIs.
+- Use [Single Value Field Array](./single-value-field-array) for repeated single values such as redirect URIs.
- Use `KeyValueFieldArray` for repeated text/text pairs such as headers, parameters, and config entries.
- Build a custom row UI instead when each row mixes different controls, such as a text input paired with a `Select`.
diff --git a/apps/design-system/content/docs/fragments/single-value-field-array.mdx b/apps/design-system/content/docs/fragments/single-value-field-array.mdx
new file mode 100644
index 00000000000..d96d74fa105
--- /dev/null
+++ b/apps/design-system/content/docs/fragments/single-value-field-array.mdx
@@ -0,0 +1,41 @@
+---
+title: Single Value Field Array
+description: A shared form fragment for repeated single text inputs.
+component: true
+fragment: true
+---
+
+<ComponentPreview
+ name="single-value-field-array-demo"
+ description="A shared form fragment for repeated single text inputs."
+ peekCode
+ showDottedGrid
+ wide
+/>
+
+## Usage
+
+Use `SingleValueFieldArray` when each row is a single text input backed by `react-hook-form`, such as redirect URIs, SSO domains, or repeated attribute mapping values.
+
+```tsx
+import { SingleValueFieldArray } from 'ui-patterns/form/SingleValueFieldArray/SingleValueFieldArray'
+```
+
+```tsx
+<SingleValueFieldArray
+ control={form.control}
+ name="redirectUris"
+ valueFieldName="value"
+ createEmptyRow={() => ({ value: '' })}
+ placeholder="https://example.com/callback"
+ addLabel="Add redirect URI"
+/>
+```
+
+`SingleValueFieldArray` owns the row add/remove behavior and renders the per-input form messages for you. Compose it inside `FormItemLayout` when you want the standard label, description, and message treatment around the entire section.
+
+## When to use it
+
+- Use `SingleValueFieldArray` for repeated single text values such as redirect URIs and domains.
+- Use [Key/Value Field Array](./key-value-field-array) when each row is two text inputs.
+- Build a custom row UI instead when each row mixes different controls, such as a text input paired with a `Select`.
diff --git a/apps/design-system/content/docs/ui-patterns/forms.mdx b/apps/design-system/content/docs/ui-patterns/forms.mdx
index f37ab471ce9..4dd556f82a8 100644
--- a/apps/design-system/content/docs/ui-patterns/forms.mdx
+++ b/apps/design-system/content/docs/ui-patterns/forms.mdx
@@ -34,7 +34,11 @@ The form previews above include both repeated-field patterns used across Studio:
- **Field Array** for repeated single-value rows such as redirect URIs.
- **Key/Value Field Array** for repeated text pairs such as headers, parameters, and config entries.
-Use the shared [Key/Value Field Array](../fragments/key-value-field-array) fragment when each row is two text inputs managed by `react-hook-form`. Keep using a plain field array when each row is just one input, and build a custom row when the cells are mixed controls.
+Use the shared [Single Value Field Array](../fragments/single-value-field-array) fragment when each row is one text input managed by `react-hook-form`.
+
+Use the shared [Key/Value Field Array](../fragments/key-value-field-array) fragment when each row is two text inputs managed by `react-hook-form`.
+
+Build a custom row when the cells are mixed controls, such as an input paired with a `Select`.
## Best Practices
diff --git a/apps/design-system/registry/default/example/form-patterns-pagelayout.tsx b/apps/design-system/registry/default/example/form-patterns-pagelayout.tsx
index f1b6cc5ea68..9cd8af4d7f9 100644
--- a/apps/design-system/registry/default/example/form-patterns-pagelayout.tsx
+++ b/apps/design-system/registry/default/example/form-patterns-pagelayout.tsx
@@ -1,8 +1,8 @@
import { zodResolver } from '@hookform/resolvers/zod'
import { format } from 'date-fns'
-import { CalendarIcon, ExternalLink, Plus, Trash, Upload } from 'lucide-react'
+import { CalendarIcon, ExternalLink, Trash, Upload } from 'lucide-react'
import { useRef, useState } from 'react'
-import { useFieldArray, useForm } from 'react-hook-form'
+import { useForm } from 'react-hook-form'
import {
Button,
Calendar,
@@ -35,6 +35,7 @@ import {
import { Input } from 'ui-patterns/DataInputs/Input'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
import { KeyValueFieldArray } from 'ui-patterns/form/KeyValueFieldArray/KeyValueFieldArray'
+import { SingleValueFieldArray } from 'ui-patterns/form/SingleValueFieldArray/SingleValueFieldArray'
import {
MultiSelector,
MultiSelectorContent,
@@ -102,11 +103,6 @@ export default function FormPatternsPageLayout() {
},
})
- const { fields, append, remove } = useFieldArray({
- control: form.control,
- name: 'redirectUris',
- })
-
function onSubmit(values: z.infer<typeof formSchema>) {
console.log(values)
}
@@ -690,42 +686,15 @@ export default function FormPatternsPageLayout() {
label="Field Array"
description="Dynamic list for adding/removing items"
>
- <div className="space-y-2 w-full">
- {fields.map((field, index) => (
- <FormField_Shadcn_
- key={field.id}
- control={form.control}
- name={`redirectUris.${index}.value`}
- render={({ field: inputField }) => (
- <div className="flex gap-2">
- <FormControl_Shadcn_>
- <Input_Shadcn_
- {...inputField}
- placeholder="https://example.com/callback"
- />
- </FormControl_Shadcn_>
- {fields.length > 1 && (
- <Button
- type="default"
- size="tiny"
- htmlType="button"
- icon={<Trash size={12} />}
- onClick={() => remove(index)}
- />
- )}
- </div>
- )}
- />
- ))}
- <Button
- type="default"
- htmlType="button"
- icon={<Plus />}
- onClick={() => append({ value: '' })}
- >
- Add redirect URI
- </Button>
- </div>
+ <SingleValueFieldArray
+ control={form.control}
+ name="redirectUris"
+ valueFieldName="value"
+ createEmptyRow={() => ({ value: '' })}
+ placeholder="https://example.com/callback"
+ addLabel="Add redirect URI"
+ removeLabel="Remove redirect URI"
+ />
</FormItemLayout>
)}
/>
diff --git a/apps/design-system/registry/default/example/form-patterns-sidepanel.tsx b/apps/design-system/registry/default/example/form-patterns-sidepanel.tsx
index 52794b904b4..6cfa7b74b82 100644
--- a/apps/design-system/registry/default/example/form-patterns-sidepanel.tsx
+++ b/apps/design-system/registry/default/example/form-patterns-sidepanel.tsx
@@ -1,8 +1,8 @@
import { zodResolver } from '@hookform/resolvers/zod'
import { format } from 'date-fns'
-import { CalendarIcon, ExternalLink, Plus, Trash, Upload } from 'lucide-react'
+import { CalendarIcon, ExternalLink, Trash, Upload } from 'lucide-react'
import { useRef, useState } from 'react'
-import { useFieldArray, useForm } from 'react-hook-form'
+import { useForm } from 'react-hook-form'
import {
Button,
Calendar,
@@ -38,6 +38,7 @@ import {
import { Input } from 'ui-patterns/DataInputs/Input'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
import { KeyValueFieldArray } from 'ui-patterns/form/KeyValueFieldArray/KeyValueFieldArray'
+import { SingleValueFieldArray } from 'ui-patterns/form/SingleValueFieldArray/SingleValueFieldArray'
import {
MultiSelector,
MultiSelectorContent,
@@ -99,11 +100,6 @@ export default function FormPatternsSidePanel() {
},
})
- const { fields, append, remove } = useFieldArray({
- control: form.control,
- name: 'redirectUris',
- })
-
function onSubmit(values: z.infer<typeof formSchema>) {
console.log(values)
setOpen(false)
@@ -693,41 +689,16 @@ export default function FormPatternsSidePanel() {
label="Field Array"
description="Dynamic list for adding/removing items"
>
- <div className="col-span-6 space-y-2">
- {fields.map((field, index) => (
- <FormField_Shadcn_
- key={field.id}
- control={form.control}
- name={`redirectUris.${index}.value`}
- render={({ field: inputField }) => (
- <div className="flex gap-2">
- <FormControl_Shadcn_>
- <Input_Shadcn_
- {...inputField}
- placeholder="https://example.com/callback"
- />
- </FormControl_Shadcn_>
- {fields.length > 1 && (
- <Button
- type="default"
- size="tiny"
- htmlType="button"
- icon={<Trash size={12} />}
- onClick={() => remove(index)}
- />
- )}
- </div>
- )}
- />
- ))}
- <Button
- type="default"
- htmlType="button"
- icon={<Plus />}
- onClick={() => append({ value: '' })}
- >
- Add redirect URI
- </Button>
+ <div className="col-span-6">
+ <SingleValueFieldArray
+ control={form.control}
+ name="redirectUris"
+ valueFieldName="value"
+ createEmptyRow={() => ({ value: '' })}
+ placeholder="https://example.com/callback"
+ addLabel="Add redirect URI"
+ removeLabel="Remove redirect URI"
+ />
</div>
</FormItemLayout>
)}
diff --git a/apps/design-system/registry/default/example/single-value-field-array-demo.tsx b/apps/design-system/registry/default/example/single-value-field-array-demo.tsx
new file mode 100644
index 00000000000..fa142a0d161
--- /dev/null
+++ b/apps/design-system/registry/default/example/single-value-field-array-demo.tsx
@@ -0,0 +1,55 @@
+import { zodResolver } from '@hookform/resolvers/zod'
+import { useForm } from 'react-hook-form'
+import { Button, Form_Shadcn_ } from 'ui'
+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
+import { SingleValueFieldArray } from 'ui-patterns/form/SingleValueFieldArray/SingleValueFieldArray'
+import { z } from 'zod'
+
+const formSchema = z.object({
+ redirectUris: z.array(
+ z.object({
+ value: z.string().url('Must be a valid URL'),
+ })
+ ),
+})
+
+export default function SingleValueFieldArrayDemo() {
+ const form = useForm<z.infer<typeof formSchema>>({
+ resolver: zodResolver(formSchema),
+ defaultValues: {
+ redirectUris: [{ value: 'https://example.com/callback' }],
+ },
+ })
+
+ function onSubmit(values: z.infer<typeof formSchema>) {
+ console.log(values)
+ }
+
+ return (
+ <Form_Shadcn_ {...form}>
+ <form className="w-full max-w-2xl" onSubmit={form.handleSubmit(onSubmit)}>
+ <FormItemLayout
+ label="Redirect URIs"
+ description="Use SingleValueFieldArray for repeated single-value rows."
+ >
+ <SingleValueFieldArray
+ control={form.control}
+ name="redirectUris"
+ valueFieldName="value"
+ createEmptyRow={() => ({ value: '' })}
+ placeholder="https://example.com/callback"
+ addLabel="Add redirect URI"
+ removeLabel="Remove redirect URI"
+ minimumRows={1}
+ />
+ </FormItemLayout>
+
+ <div className="mt-4">
+ <Button size="tiny" type="primary" htmlType="submit">
+ Submit
+ </Button>
+ </div>
+ </form>
+ </Form_Shadcn_>
+ )
+}
diff --git a/apps/design-system/registry/examples.ts b/apps/design-system/registry/examples.ts
index 4e221c2b19e..40644cb25be 100644
--- a/apps/design-system/registry/examples.ts
+++ b/apps/design-system/registry/examples.ts
@@ -235,6 +235,12 @@ export const examples: Registry = [
registryDependencies: ['calendar', 'form', 'popover'],
files: ['example/calendar-form.tsx'],
},
+ {
+ name: 'single-value-field-array-demo',
+ type: 'components:example',
+ registryDependencies: ['button', 'form', 'input'],
+ files: ['example/single-value-field-array-demo.tsx'],
+ },
// {
// name: 'card-demo',
// type: 'components:example',
diff --git a/apps/studio/components/interfaces/Auth/OAuthApps/CreateOrUpdateOAuthAppSheet.tsx b/apps/studio/components/interfaces/Auth/OAuthApps/CreateOrUpdateOAuthAppSheet.tsx
index a1212e54c68..174da2268ff 100644
--- a/apps/studio/components/interfaces/Auth/OAuthApps/CreateOrUpdateOAuthAppSheet.tsx
+++ b/apps/studio/components/interfaces/Auth/OAuthApps/CreateOrUpdateOAuthAppSheet.tsx
@@ -12,9 +12,9 @@ import { useOAuthServerAppCreateMutation } from 'data/oauth-server-apps/oauth-se
import { useOAuthServerAppRegenerateSecretMutation } from 'data/oauth-server-apps/oauth-server-app-regenerate-secret-mutation'
import { useOAuthServerAppUpdateMutation } from 'data/oauth-server-apps/oauth-server-app-update-mutation'
import { DOCS_URL } from 'lib/constants'
-import { Plus, Trash2, Upload, X } from 'lucide-react'
+import { Trash2, Upload, X } from 'lucide-react'
import { useEffect, useRef, useState, type ChangeEvent } from 'react'
-import { useFieldArray, useForm } from 'react-hook-form'
+import { useForm } from 'react-hook-form'
import { toast } from 'sonner'
import {
Button,
@@ -23,9 +23,7 @@ import {
FormControl_Shadcn_,
FormDescription_Shadcn_,
FormField_Shadcn_,
- FormItem_Shadcn_,
FormLabel_Shadcn_,
- FormMessage_Shadcn_,
Input_Shadcn_,
Separator,
Sheet,
@@ -40,6 +38,7 @@ import {
import { Input } from 'ui-patterns/DataInputs/Input'
import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
+import { SingleValueFieldArray } from 'ui-patterns/form/SingleValueFieldArray/SingleValueFieldArray'
import * as z from 'zod'
interface CreateOrUpdateOAuthAppSheetProps {
@@ -102,15 +101,6 @@ export const CreateOrUpdateOAuthAppSheet = ({
defaultValues: initialValues,
})
- const {
- fields: redirectUriFields,
- append: appendRedirectUri,
- remove: removeRedirectUri,
- } = useFieldArray({
- name: 'redirect_uris',
- control: form.control,
- })
-
const { hostEndpoint: clientEndpoint } = useProjectApiUrl({ projectRef })
const { mutate: createOAuthApp, isPending: isCreating } = useOAuthServerAppCreateMutation({
@@ -407,50 +397,17 @@ export const CreateOrUpdateOAuthAppSheet = ({
<div className="px-5 gap-2 flex flex-col">
<FormLabel_Shadcn_ className="text-foreground">Redirect URIs</FormLabel_Shadcn_>
-
- <div className="space-y-2">
- {redirectUriFields.map((fieldItem, index) => (
- <FormField_Shadcn_
- control={form.control}
- key={fieldItem.id}
- name={`redirect_uris.${index}.value`}
- render={({ field: inputField }) => (
- <FormItem_Shadcn_>
- <div className="flex flex-row gap-2">
- <FormControl_Shadcn_>
- <Input_Shadcn_
- {...inputField}
- placeholder={'https://example.com/callback'}
- onChange={(e) => {
- inputField.onChange(e)
- }}
- />
- </FormControl_Shadcn_>
- {redirectUriFields.length > 1 && (
- <Button
- type="default"
- size="tiny"
- className="h-[34px]"
- icon={<Trash2 size={12} />}
- onClick={() => removeRedirectUri(index)}
- />
- )}
- </div>
- <FormMessage_Shadcn_ />
- </FormItem_Shadcn_>
- )}
- />
- ))}
- </div>
- <div>
- <Button
- type="default"
- icon={<Plus strokeWidth={1.5} />}
- onClick={() => appendRedirectUri({ value: '' })}
- >
- Add redirect URI
- </Button>
- </div>
+ <SingleValueFieldArray
+ control={form.control}
+ name="redirect_uris"
+ valueFieldName="value"
+ createEmptyRow={() => ({ value: '' })}
+ placeholder="https://example.com/callback"
+ addLabel="Add redirect URI"
+ removeLabel="Remove redirect URI"
+ minimumRows={1}
+ rowsClassName="space-y-2"
+ />
<FormDescription_Shadcn_ className="text-foreground-lighter">
URLs where users will be redirected after authentication.
</FormDescription_Shadcn_>
diff --git a/apps/studio/components/interfaces/Auth/RedirectUrls/AddNewURLModal.test.tsx b/apps/studio/components/interfaces/Auth/RedirectUrls/AddNewURLModal.test.tsx
new file mode 100644
index 00000000000..56fcd9aa3ba
--- /dev/null
+++ b/apps/studio/components/interfaces/Auth/RedirectUrls/AddNewURLModal.test.tsx
@@ -0,0 +1,134 @@
+import { fireEvent, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { toast } from 'sonner'
+
+import { render } from 'tests/helpers'
+
+import { AddNewURLModal } from './AddNewURLModal'
+
+const { mutateMock, useAuthConfigUpdateMutationMock } = vi.hoisted(() => ({
+ mutateMock: vi.fn(),
+ useAuthConfigUpdateMutationMock: vi.fn(),
+}))
+
+vi.mock(import('common'), async (importOriginal) => {
+ const actual = await importOriginal()
+
+ return {
+ ...actual,
+ useParams: vi.fn().mockReturnValue({ ref: 'project-ref' }),
+ }
+})
+
+vi.mock('data/auth/auth-config-update-mutation', () => ({
+ useAuthConfigUpdateMutation: useAuthConfigUpdateMutationMock,
+}))
+
+vi.mock('sonner', () => ({
+ toast: {
+ success: vi.fn(),
+ error: vi.fn(),
+ },
+}))
+
+describe('AddNewURLModal', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ useAuthConfigUpdateMutationMock.mockReturnValue({
+ mutate: mutateMock,
+ isPending: false,
+ })
+ })
+
+ it('adds and removes URL rows before submitting the current values', async () => {
+ const user = userEvent.setup()
+ mutateMock.mockImplementation((_vars, callbacks) => callbacks?.onSuccess?.())
+
+ render(
+ <AddNewURLModal visible allowList={['https://existing.example.com']} onClose={vi.fn()} />
+ )
+
+ await screen.findByRole('dialog')
+
+ expect(screen.getAllByPlaceholderText('https://mydomain.com')).toHaveLength(1)
+
+ await user.type(screen.getByPlaceholderText('https://mydomain.com'), 'https://app.example.com')
+ await user.click(screen.getByRole('button', { name: 'Add URL' }))
+
+ const urlInputs = screen.getAllByPlaceholderText('https://mydomain.com')
+ expect(urlInputs).toHaveLength(2)
+
+ await user.type(urlInputs[1], 'https://dashboard.example.com')
+ await user.click(screen.getAllByRole('button', { name: 'Remove URL' })[1])
+
+ expect(screen.getAllByPlaceholderText('https://mydomain.com')).toHaveLength(1)
+
+ fireEvent.submit(screen.getByRole('dialog').querySelector('form') as HTMLFormElement)
+
+ await waitFor(() =>
+ expect(mutateMock).toHaveBeenCalledWith(
+ {
+ projectRef: 'project-ref',
+ config: {
+ URI_ALLOW_LIST: 'https://existing.example.com,https://app.example.com',
+ },
+ },
+ expect.any(Object)
+ )
+ )
+
+ expect(toast.success).toHaveBeenCalledWith('Successfully added 1 URL')
+ })
+
+ it('dedupes URLs after normalising a trailing comma before submitting', async () => {
+ const user = userEvent.setup()
+ mutateMock.mockImplementation((_vars, callbacks) => callbacks?.onSuccess?.())
+
+ render(<AddNewURLModal visible allowList={[]} onClose={vi.fn()} />)
+
+ await screen.findByRole('dialog')
+
+ await user.type(screen.getByPlaceholderText('https://mydomain.com'), 'https://app.example.com')
+ await user.click(screen.getByRole('button', { name: 'Add URL' }))
+
+ const urlInputs = screen.getAllByPlaceholderText('https://mydomain.com')
+ await user.type(urlInputs[1], 'https://app.example.com,')
+
+ fireEvent.submit(screen.getByRole('dialog').querySelector('form') as HTMLFormElement)
+
+ await waitFor(() =>
+ expect(mutateMock).toHaveBeenCalledWith(
+ {
+ projectRef: 'project-ref',
+ config: {
+ URI_ALLOW_LIST: 'https://app.example.com',
+ },
+ },
+ expect.any(Object)
+ )
+ )
+
+ expect(toast.success).toHaveBeenCalledWith('Successfully added 1 URL')
+ })
+
+ it('rejects a trailing-comma URL when it already exists in the allow list', async () => {
+ const user = userEvent.setup()
+
+ render(
+ <AddNewURLModal visible allowList={['https://existing.example.com']} onClose={vi.fn()} />
+ )
+
+ await screen.findByRole('dialog')
+
+ await user.type(
+ screen.getByPlaceholderText('https://mydomain.com'),
+ 'https://existing.example.com,'
+ )
+
+ fireEvent.submit(screen.getByRole('dialog').querySelector('form') as HTMLFormElement)
+
+ expect(await screen.findByText('URL already exists in the allow list')).toBeInTheDocument()
+ expect(mutateMock).not.toHaveBeenCalled()
+ })
+})
diff --git a/apps/studio/components/interfaces/Auth/RedirectUrls/AddNewURLModal.tsx b/apps/studio/components/interfaces/Auth/RedirectUrls/AddNewURLModal.tsx
index 0bf6ba0e790..5dc944bfe70 100644
--- a/apps/studio/components/interfaces/Auth/RedirectUrls/AddNewURLModal.tsx
+++ b/apps/studio/components/interfaces/Auth/RedirectUrls/AddNewURLModal.tsx
@@ -1,25 +1,15 @@
import { zodResolver } from '@hookform/resolvers/zod'
-import { Plus, Trash } from 'lucide-react'
import { useEffect } from 'react'
-import { useFieldArray, useForm } from 'react-hook-form'
+import { useForm } from 'react-hook-form'
import { toast } from 'sonner'
import * as z from 'zod'
import { Label } from '@ui/components/shadcn/ui/label'
import { useParams } from 'common'
import { useAuthConfigUpdateMutation } from 'data/auth/auth-config-update-mutation'
-import {
- Button,
- cn,
- DialogSectionSeparator,
- Form_Shadcn_,
- FormControl_Shadcn_,
- FormField_Shadcn_,
- Modal,
- ScrollArea,
-} from 'ui'
-import { Input } from 'ui-patterns/DataInputs/Input'
+import { Button, cn, DialogSectionSeparator, Form_Shadcn_, Modal, ScrollArea } from 'ui'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
+import { SingleValueFieldArray } from 'ui-patterns/form/SingleValueFieldArray/SingleValueFieldArray'
import { urlRegex } from '../Auth.constants'
const MAX_URLS_LENGTH = 2 * 1024
@@ -30,9 +20,12 @@ interface AddNewURLModalProps {
onClose: () => void
}
+const normaliseUrl = (value: string) => value.replace(/,\s*$/, '')
+
export const AddNewURLModal = ({ visible, allowList, onClose }: AddNewURLModalProps) => {
const { ref } = useParams()
const { mutate: updateAuthConfig, isPending: isUpdatingConfig } = useAuthConfigUpdateMutation()
+ const redirectUrlRegex = urlRegex()
const FormSchema = z.object({
urls: z
@@ -40,8 +33,11 @@ export const AddNewURLModal = ({ visible, allowList, onClose }: AddNewURLModalPr
value: z
.string()
.min(1, 'Please provide a value')
- .regex(urlRegex(), 'Please provide a valid URL')
- .refine((value) => !allowList.includes(value), {
+ .refine(
+ (value) => redirectUrlRegex.test(normaliseUrl(value)),
+ 'Please provide a valid URL'
+ )
+ .refine((value) => !allowList.includes(normaliseUrl(value)), {
message: 'URL already exists in the allow list',
}),
})
@@ -54,15 +50,13 @@ export const AddNewURLModal = ({ visible, allowList, onClose }: AddNewURLModalPr
resolver: zodResolver(FormSchema),
defaultValues: initialValues,
})
-
- const { fields, append, remove } = useFieldArray({
- name: 'urls',
- control: form.control,
- })
+ const urls = form.watch('urls')
const onSubmit = (data: z.infer<typeof FormSchema>) => {
- const dedupedData = [...new Set(data.urls.map((url) => url.value))]
- const payload = allowList.concat(dedupedData.map((url) => url.replace(/,\s*$/, ''))).toString()
+ const dedupedUrls = [...new Set(data.urls.map((url) => normaliseUrl(url.value)))]
+ const payloadUrls = allowList.concat(dedupedUrls)
+ const addedCount = dedupedUrls.length
+ const payload = payloadUrls.toString()
if (payload.length > MAX_URLS_LENGTH) {
return toast.error('Too many redirect URLs, please remove some or try to use wildcards')
@@ -74,7 +68,7 @@ export const AddNewURLModal = ({ visible, allowList, onClose }: AddNewURLModalPr
toast.error(`Failed to add URL(s): ${error?.message}`)
},
onSuccess: () => {
- toast.success(`Successfully added ${fields.length} URL${fields.length > 1 ? 's' : ''}`)
+ toast.success(`Successfully added ${addedCount} URL${addedCount > 1 ? 's' : ''}`)
form.reset(initialValues)
onClose()
},
@@ -104,44 +98,24 @@ export const AddNewURLModal = ({ visible, allowList, onClose }: AddNewURLModalPr
<form onSubmit={form.handleSubmit(onSubmit)}>
<Modal.Content className="flex flex-col gap-y-2 px-0">
<Label className="px-5">URL</Label>
- <ScrollArea className={cn(fields.length > 4 ? 'h-[220px]' : '')}>
- <div className="px-5 py-1 flex flex-col gap-y-2">
- {fields.map((field, index) => (
- <FormField_Shadcn_
+ <ScrollArea className={cn(urls.length > 4 ? 'h-[220px]' : '')}>
+ <div className="px-5 py-1">
+ <FormItemLayout className="[&>div>div]:mt-0">
+ <SingleValueFieldArray
control={form.control}
- key={field.id}
- name={`urls.${index}.value`}
- render={({ field: inputField }) => (
- <FormItemLayout className="[&>div>div]:mt-0">
- <FormControl_Shadcn_>
- <div className="flex items-center gap-x-2 [&>div]:w-full">
- <Input placeholder="https://mydomain.com" {...inputField} />
- <Button
- type="default"
- size="small"
- icon={<Trash />}
- className="px-2"
- disabled={fields.length === 1}
- onClick={() => remove(index)}
- />
- </div>
- </FormControl_Shadcn_>
- </FormItemLayout>
- )}
+ name="urls"
+ valueFieldName="value"
+ createEmptyRow={() => ({ value: '' })}
+ placeholder="https://mydomain.com"
+ addLabel="Add URL"
+ removeLabel="Remove URL"
+ minimumRows={1}
+ rowsClassName="space-y-2"
+ addButtonClassName="w-min"
/>
- ))}
+ </FormItemLayout>
</div>
</ScrollArea>
- <div className="px-5">
- <Button
- type="default"
- className="w-min"
- icon={<Plus strokeWidth={1.5} />}
- onClick={() => append({ value: '' })}
- >
- Add URL
- </Button>
- </div>
</Modal.Content>
<DialogSectionSeparator />
<Modal.Content>
diff --git a/apps/studio/components/interfaces/Organization/SSO/AttributeMapping.tsx b/apps/studio/components/interfaces/Organization/SSO/AttributeMapping.tsx
index 0acdfea2e44..3bb981d807b 100644
--- a/apps/studio/components/interfaces/Organization/SSO/AttributeMapping.tsx
+++ b/apps/studio/components/interfaces/Organization/SSO/AttributeMapping.tsx
@@ -1,15 +1,7 @@
-import { Plus, Trash } from 'lucide-react'
-import { useFieldArray, UseFormReturn } from 'react-hook-form'
-import {
- Button,
- FormControl_Shadcn_,
- FormField_Shadcn_,
- FormItem_Shadcn_,
- FormMessage_Shadcn_,
- Input_Shadcn_,
-} from 'ui'
+import { UseFormReturn } from 'react-hook-form'
+import { Button } from 'ui'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
-
+import { SingleValueFieldArray } from 'ui-patterns/form/SingleValueFieldArray/SingleValueFieldArray'
import type { SSOConfigFormSchema } from './SSOConfig'
type ProviderAttribute = 'emailMapping' | 'userNameMapping' | 'firstNameMapping' | 'lastNameMapping'
@@ -169,55 +161,26 @@ const MappingFieldArray = ({
required: boolean
placeholder?: string
}) => {
- const { fields, append, remove } = useFieldArray({
- control: form.control,
- name: fieldName,
- })
-
return (
<div className="w-full min-w-0 space-y-1">
<div className="flex items-center justify-between gap-2">
<span className="text-foreground-light">{label}</span>
{!required ? <span className="text-foreground-muted">Optional</span> : null}
</div>
- <div className="grid w-full min-w-0 gap-2">
- {fields.map((field, idx) => (
- <div key={field.id} className="flex min-w-0 items-start gap-2">
- <FormField_Shadcn_
- name={`${fieldName}.${idx}.value`}
- render={({ field }) => (
- <FormItem_Shadcn_ className="min-w-0 flex-1">
- <FormControl_Shadcn_>
- <Input_Shadcn_
- {...field}
- className="min-w-0"
- placeholder={placeholder}
- autoComplete="off"
- />
- </FormControl_Shadcn_>
- <FormMessage_Shadcn_ />
- </FormItem_Shadcn_>
- )}
- />
- <Button
- type="default"
- icon={<Trash size={12} />}
- className="h-[34px] w-[34px] shrink-0"
- disabled={fields.length <= 1}
- onClick={() => remove(idx)}
- />
- </div>
- ))}
-
- <Button
- type="default"
- icon={<Plus className="w-4 h-4" />}
- onClick={() => append({ value: '' })}
- className="w-auto self-start justify-self-start"
- >
- Add another
- </Button>
- </div>
+ <SingleValueFieldArray
+ control={form.control}
+ name={fieldName}
+ valueFieldName="value"
+ createEmptyRow={() => ({ value: '' })}
+ placeholder={placeholder ?? ''}
+ addLabel="Add another"
+ removeLabel={`Remove ${label} mapping`}
+ minimumRows={1}
+ inputAutoComplete="off"
+ rowsClassName="grid gap-2 w-full"
+ addButtonType="default"
+ addButtonClassName="w-auto self-start justify-self-start"
+ />
</div>
)
}
diff --git a/apps/studio/components/interfaces/Organization/SSO/SSODomains.tsx b/apps/studio/components/interfaces/Organization/SSO/SSODomains.tsx
index 53b10c8dfb9..cc5f5c7eb2b 100644
--- a/apps/studio/components/interfaces/Organization/SSO/SSODomains.tsx
+++ b/apps/studio/components/interfaces/Organization/SSO/SSODomains.tsx
@@ -1,66 +1,31 @@
-import { Plus, Trash } from 'lucide-react'
-import { useFieldArray, useForm } from 'react-hook-form'
-import {
- Button,
- FormControl_Shadcn_,
- FormField_Shadcn_,
- FormItem_Shadcn_,
- FormMessage_Shadcn_,
- Input_Shadcn_,
-} from 'ui'
+import { useForm } from 'react-hook-form'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
-
+import { SingleValueFieldArray } from 'ui-patterns/form/SingleValueFieldArray/SingleValueFieldArray'
import { SSOConfigFormSchema } from './SSOConfig'
export const SSODomains = ({ form }: { form: ReturnType<typeof useForm<SSOConfigFormSchema>> }) => {
- const { fields, append, remove } = useFieldArray({
- control: form.control,
- name: 'domains',
- })
-
return (
- <>
- <FormItemLayout
- label="Domains"
- layout="flex-row-reverse"
- description="Provide one or more domains"
- >
- <div className="grid gap-2 w-96">
- {fields.map((field, idx) => (
- <div key={field.id} className="flex gap-2 items-top">
- <FormField_Shadcn_
- name={`domains.${idx}.value`}
- render={({ field }) => (
- <FormItem_Shadcn_ className="flex-1">
- <FormControl_Shadcn_>
- <Input_Shadcn_ {...field} autoComplete="off" placeholder="example.com" />
- </FormControl_Shadcn_>
- <FormMessage_Shadcn_ />
- </FormItem_Shadcn_>
- )}
- />
-
- <Button
- type="default"
- icon={<Trash size={12} />}
- className="h-[34px] w-[34px]"
- disabled={fields.length <= 1}
- onClick={() => remove(idx)}
- />
- </div>
- ))}
- <div>
- <Button
- type="default"
- icon={<Plus className="w-4 h-4" />}
- size="tiny"
- onClick={() => append({ value: '' })}
- >
- Add another
- </Button>
- </div>
- </div>
- </FormItemLayout>
- </>
+ <FormItemLayout
+ label="Domains"
+ layout="flex-row-reverse"
+ description="Provide one or more domains"
+ >
+ <SingleValueFieldArray
+ control={form.control}
+ name="domains"
+ valueFieldName="value"
+ createEmptyRow={() => ({ value: '' })}
+ placeholder="example.com"
+ addLabel="Add another"
+ removeLabel="Remove domain"
+ minimumRows={1}
+ inputAutoComplete="off"
+ className="w-96"
+ rowsClassName="grid gap-2 w-full"
+ addButtonType="default"
+ addButtonSize="tiny"
+ addButtonClassName="w-auto"
+ />
+ </FormItemLayout>
)
}
diff --git a/packages/ui-patterns/package.json b/packages/ui-patterns/package.json
index 76cef55abab..3d0fc398dd0 100644
--- a/packages/ui-patterns/package.json
+++ b/packages/ui-patterns/package.json
@@ -730,6 +730,14 @@
"import": "./src/form/KeyValueFieldArray/KeyValueFieldArray.tsx",
"types": "./src/form/KeyValueFieldArray/KeyValueFieldArray.tsx"
},
+ "./form/SingleValueFieldArray/SingleValueFieldArray.test": {
+ "import": "./src/form/SingleValueFieldArray/SingleValueFieldArray.test.tsx",
+ "types": "./src/form/SingleValueFieldArray/SingleValueFieldArray.test.tsx"
+ },
+ "./form/SingleValueFieldArray/SingleValueFieldArray": {
+ "import": "./src/form/SingleValueFieldArray/SingleValueFieldArray.tsx",
+ "types": "./src/form/SingleValueFieldArray/SingleValueFieldArray.tsx"
+ },
"./form/Layout/FormLayout": {
"import": "./src/form/Layout/FormLayout.tsx",
"types": "./src/form/Layout/FormLayout.tsx"
diff --git a/packages/ui-patterns/src/form/SingleValueFieldArray/SingleValueFieldArray.test.tsx b/packages/ui-patterns/src/form/SingleValueFieldArray/SingleValueFieldArray.test.tsx
new file mode 100644
index 00000000000..19bfaa04900
--- /dev/null
+++ b/packages/ui-patterns/src/form/SingleValueFieldArray/SingleValueFieldArray.test.tsx
@@ -0,0 +1,160 @@
+import { zodResolver } from '@hookform/resolvers/zod'
+import { render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { useForm } from 'react-hook-form'
+import { describe, expect, it, vi } from 'vitest'
+import { z } from 'zod'
+
+import { Button, Form_Shadcn_ } from 'ui'
+
+import { SingleValueFieldArray } from './SingleValueFieldArray'
+
+const valueSchema = z.object({
+ urls: z.array(
+ z.object({
+ value: z.string().min(1, 'URL is required'),
+ })
+ ),
+})
+
+const nameSchema = z.object({
+ domains: z.array(
+ z.object({
+ id: z.string(),
+ domain: z.string().min(1, 'Domain is required'),
+ })
+ ),
+})
+
+type ValueFormValues = z.infer<typeof valueSchema>
+type NameFormValues = z.infer<typeof nameSchema>
+
+const ValueForm = ({
+ defaultValues = { urls: [] },
+ onSubmit = vi.fn(),
+}: {
+ defaultValues?: ValueFormValues
+ onSubmit?: (values: ValueFormValues) => void
+}) => {
+ const form = useForm<ValueFormValues>({
+ resolver: zodResolver(valueSchema),
+ defaultValues,
+ })
+
+ return (
+ <Form_Shadcn_ {...form}>
+ <form onSubmit={form.handleSubmit(onSubmit)}>
+ <SingleValueFieldArray
+ control={form.control}
+ name="urls"
+ valueFieldName="value"
+ createEmptyRow={() => ({ value: '' })}
+ placeholder="https://example.com/callback"
+ addLabel="Add URL"
+ removeLabel="Remove URL"
+ minimumRows={1}
+ />
+ <Button htmlType="submit">Submit</Button>
+ </form>
+ </Form_Shadcn_>
+ )
+}
+
+const NameForm = ({ onSubmit = vi.fn() }: { onSubmit?: (values: NameFormValues) => void }) => {
+ const form = useForm<NameFormValues>({
+ resolver: zodResolver(nameSchema),
+ defaultValues: {
+ domains: [{ id: 'row-1', domain: 'example.com' }],
+ },
+ })
+
+ return (
+ <Form_Shadcn_ {...form}>
+ <form onSubmit={form.handleSubmit(onSubmit)}>
+ <SingleValueFieldArray
+ control={form.control}
+ name="domains"
+ valueFieldName="domain"
+ createEmptyRow={() => ({ id: crypto.randomUUID(), domain: '' })}
+ placeholder="example.com"
+ addLabel="Add domain"
+ removeLabel="Remove domain"
+ minimumRows={1}
+ />
+ <Button htmlType="submit">Submit</Button>
+ </form>
+ </Form_Shadcn_>
+ )
+}
+
+describe('SingleValueFieldArray', () => {
+ it('appends an empty row', async () => {
+ const user = userEvent.setup()
+
+ render(<ValueForm defaultValues={{ urls: [{ value: '' }] }} />)
+
+ await user.click(screen.getByRole('button', { name: 'Add URL' }))
+
+ expect(screen.getAllByPlaceholderText('https://example.com/callback')).toHaveLength(2)
+ })
+
+ it('removes a row', async () => {
+ const user = userEvent.setup()
+
+ render(
+ <ValueForm defaultValues={{ urls: [{ value: 'https://example.com' }, { value: '' }] }} />
+ )
+
+ expect(screen.getAllByPlaceholderText('https://example.com/callback')).toHaveLength(2)
+
+ await user.click(screen.getAllByRole('button', { name: 'Remove URL' })[1])
+
+ expect(screen.getAllByPlaceholderText('https://example.com/callback')).toHaveLength(1)
+ })
+
+ it('renders and submits value field names', async () => {
+ const user = userEvent.setup()
+ const onSubmit = vi.fn()
+
+ render(<ValueForm defaultValues={{ urls: [{ value: '' }] }} onSubmit={onSubmit} />)
+
+ await user.type(
+ screen.getByPlaceholderText('https://example.com/callback'),
+ 'https://example.com/auth'
+ )
+ await user.click(screen.getByRole('button', { name: 'Submit' }))
+
+ await waitFor(() =>
+ expect(onSubmit).toHaveBeenCalledWith(
+ { urls: [{ value: 'https://example.com/auth' }] },
+ expect.anything()
+ )
+ )
+ })
+
+ it('renders and submits custom field names while preserving row ids', async () => {
+ const user = userEvent.setup()
+ const onSubmit = vi.fn()
+
+ render(<NameForm onSubmit={onSubmit} />)
+
+ await user.click(screen.getByRole('button', { name: 'Submit' }))
+
+ await waitFor(() =>
+ expect(onSubmit).toHaveBeenCalledWith(
+ { domains: [{ id: 'row-1', domain: 'example.com' }] },
+ expect.anything()
+ )
+ )
+ })
+
+ it('shows RHF field errors through FormMessage', async () => {
+ const user = userEvent.setup()
+
+ render(<ValueForm defaultValues={{ urls: [{ value: '' }] }} />)
+
+ await user.click(screen.getByRole('button', { name: 'Submit' }))
+
+ expect(await screen.findByText('URL is required')).toBeInTheDocument()
+ })
+})
diff --git a/packages/ui-patterns/src/form/SingleValueFieldArray/SingleValueFieldArray.tsx b/packages/ui-patterns/src/form/SingleValueFieldArray/SingleValueFieldArray.tsx
new file mode 100644
index 00000000000..2bcd6b74e97
--- /dev/null
+++ b/packages/ui-patterns/src/form/SingleValueFieldArray/SingleValueFieldArray.tsx
@@ -0,0 +1,149 @@
+import { Plus, Trash } from 'lucide-react'
+import {
+ Control,
+ FieldArray,
+ FieldArrayPath,
+ FieldArrayWithId,
+ FieldPath,
+ FieldValues,
+ useFieldArray,
+} from 'react-hook-form'
+import {
+ Button,
+ cn,
+ FormControl_Shadcn_,
+ FormField_Shadcn_,
+ FormItem_Shadcn_,
+ FormMessage_Shadcn_,
+ Input_Shadcn_,
+} from 'ui'
+
+export interface SingleValueFieldArrayProps<
+ TFieldValues extends FieldValues,
+ TFieldArrayName extends FieldArrayPath<TFieldValues>,
+ TItem extends FieldArray<TFieldValues, TFieldArrayName> = FieldArray<
+ TFieldValues,
+ TFieldArrayName
+ >,
+> {
+ control: Control<TFieldValues>
+ name: TFieldArrayName
+ valueFieldName: Extract<keyof TItem, string>
+ createEmptyRow: () => TItem
+ placeholder: string
+ addLabel: string
+ removeLabel?: string
+ disabled?: boolean
+ minimumRows?: number
+ inputSize?: React.ComponentProps<typeof Input_Shadcn_>['size']
+ inputAutoComplete?: string
+ className?: string
+ rowsClassName?: string
+ rowClassName?: string
+ inputClassName?: string
+ addButtonClassName?: string
+ addButtonType?: React.ComponentProps<typeof Button>['type']
+ addButtonSize?: React.ComponentProps<typeof Button>['size']
+ removeButtonClassName?: string
+ removeButtonType?: React.ComponentProps<typeof Button>['type']
+ removeButtonSize?: React.ComponentProps<typeof Button>['size']
+}
+
+const toFieldPath = <TFieldValues extends FieldValues>(path: string) => {
+ return path as FieldPath<TFieldValues>
+}
+
+export const SingleValueFieldArray = <
+ TFieldValues extends FieldValues,
+ TFieldArrayName extends FieldArrayPath<TFieldValues>,
+ TItem extends FieldArray<TFieldValues, TFieldArrayName> = FieldArray<
+ TFieldValues,
+ TFieldArrayName
+ >,
+>({
+ control,
+ name,
+ valueFieldName,
+ createEmptyRow,
+ placeholder,
+ addLabel,
+ removeLabel = 'Remove row',
+ disabled = false,
+ minimumRows = 0,
+ inputSize = 'small',
+ inputAutoComplete,
+ className,
+ rowsClassName = 'space-y-3 mt-1',
+ rowClassName,
+ inputClassName,
+ addButtonClassName,
+ addButtonType = 'default',
+ addButtonSize,
+ removeButtonClassName,
+ removeButtonType = 'default',
+ removeButtonSize = 'tiny',
+}: SingleValueFieldArrayProps<TFieldValues, TFieldArrayName, TItem>) => {
+ const { fields, append, remove } = useFieldArray<TFieldValues, TFieldArrayName, 'fieldId'>({
+ control,
+ name,
+ keyName: 'fieldId',
+ })
+
+ const typedFields = fields as FieldArrayWithId<TFieldValues, TFieldArrayName, 'fieldId'>[]
+ const disableRemove = disabled || typedFields.length <= minimumRows
+
+ return (
+ <div className={cn('space-y-3', className)}>
+ <div className={rowsClassName}>
+ {typedFields.map((field, index) => (
+ <div key={field.fieldId} className={cn('flex items-start space-x-2', rowClassName)}>
+ <FormField_Shadcn_
+ control={control}
+ name={toFieldPath<TFieldValues>(`${name}.${index}.${valueFieldName}`)}
+ render={({ field }) => (
+ <FormItem_Shadcn_ className="flex-1">
+ <FormControl_Shadcn_>
+ <Input_Shadcn_
+ {...field}
+ size={inputSize}
+ autoComplete={inputAutoComplete}
+ className={cn('w-full', inputClassName)}
+ placeholder={placeholder}
+ disabled={disabled}
+ />
+ </FormControl_Shadcn_>
+ <FormMessage_Shadcn_ />
+ </FormItem_Shadcn_>
+ )}
+ />
+
+ <Button
+ type={removeButtonType}
+ size={removeButtonSize}
+ htmlType="button"
+ icon={<Trash size={12} />}
+ aria-label={removeLabel}
+ disabled={disableRemove}
+ onClick={() => remove(index)}
+ className={cn('h-[34px] w-[34px] shrink-0', removeButtonClassName)}
+ />
+ </div>
+ ))}
+ </div>
+
+ <div className="flex items-center">
+ <Button
+ type={addButtonType}
+ size={addButtonSize}
+ htmlType="button"
+ icon={<Plus strokeWidth={1.5} />}
+ disabled={disabled}
+ onClick={() => append(createEmptyRow())}
+ className={addButtonClassName}
+ >
+ {addLabel}
+ </Button>
+ </div>
+ </div>
+ )
+}