Skip to content

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

chore: Migrate create-function store from `mobx` to `react-hook-form` (#21888)

Ivan Vasilova775e3ba69a3
diff --git a/apps/studio/components/interfaces/Database/Functions/CreateFunction.tsx b/apps/studio/components/interfaces/Database/Functions/CreateFunction.tsx
index 1fa4c50e6c8..a031f03a86d 100644
--- a/apps/studio/components/interfaces/Database/Functions/CreateFunction.tsx
+++ b/apps/studio/components/interfaces/Database/Functions/CreateFunction.tsx
@@ -1,481 +1,416 @@
-import { filter, has, isEmpty, isNull, isUndefined, keyBy, mapValues, partition } from 'lodash'
-import { makeAutoObservable } from 'mobx'
-import { observer, useLocalObservable } from 'mobx-react-lite'
-import { FormEvent, createContext, useContext, useEffect, useState } from 'react'
+import { zodResolver } from '@hookform/resolvers/zod'
+import { PostgresFunction } from '@supabase/postgres-meta'
+import { isEmpty, isNull, keyBy, mapValues, partition } from 'lodash'
+import { useEffect, useState } from 'react'
+import { SubmitHandler, useFieldArray, useForm } from 'react-hook-form'
import toast from 'react-hot-toast'
-import { Button, IconPlus, IconTrash, Input, Listbox, Modal, Radio, SidePanel, Toggle } from 'ui'
+import z from 'zod'
+import { Plus, Trash } from 'lucide-react'
import { POSTGRES_DATA_TYPES } from 'components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.constants'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
-import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
-import Panel from 'components/ui/Panel'
+import SchemaSelector from 'components/ui/SchemaSelector'
import SqlEditor from 'components/ui/SqlEditor'
import { useDatabaseExtensionsQuery } from 'data/database-extensions/database-extensions-query'
import { useDatabaseFunctionCreateMutation } from 'data/database-functions/database-functions-create-mutation'
import { useDatabaseFunctionUpdateMutation } from 'data/database-functions/database-functions-update-mutation'
-import { useSchemasQuery } from 'data/database/schemas-query'
import { EXCLUDED_SCHEMAS } from 'lib/constants/schemas'
-import type { Dictionary } from 'types'
-import { convertArgumentTypes, convertConfigParams, hasWhitespace } from './Functions.utils'
-
-// [Refactor] Remove local state, just use the Form component
-
-class CreateFunctionFormState {
- id: number | undefined
- originalName: string | undefined
- // @ts-ignore
- args: { value: { name: string; type: string; error?: string }[] }
- // @ts-ignore
- behavior: { value: string; error?: string }
- // @ts-ignore
- configParams: {
- value: { name: string; value: string; error?: { name?: string; value?: string } }[]
- }
- // @ts-ignore
- definition: { value: string; error?: string }
- // @ts-ignore
- language: { value: string; error?: string }
- // @ts-ignore
- name: { value: string; error?: string }
- // @ts-ignore
- returnType: { value: string; error?: string }
- // @ts-ignore
- schema: { value: string; error?: string }
- // @ts-ignore
- securityDefiner: { value: boolean; error?: string }
-
- constructor() {
- makeAutoObservable(this)
- this.reset()
- }
-
- get requestBody() {
- return {
- id: this.id,
- name: this.name.value,
- schema: this.schema.value,
- definition: this.definition.value,
- return_type: this.returnType.value,
- language: this.language.value,
- behavior: this.behavior.value as 'VOLATILE' | 'STABLE' | 'IMMUTABLE',
- security_definer: this.securityDefiner.value,
- args: this.args.value.map((x: any) => `${x.name} ${x.type}`),
- config_params: mapValues(keyBy(this.configParams.value, 'name'), 'value'),
- }
- }
-
- reset(func?: Dictionary<any>) {
- this.id = func?.id
- this.originalName = func?.name
- this.args = convertArgumentTypes(func?.argument_types)
- this.behavior = { value: func?.behavior ?? 'VOLATILE' }
- this.configParams = convertConfigParams(func?.config_params)
- this.definition = { value: func?.definition ?? '' }
- this.language = { value: func?.language ?? 'plpgsql' }
- this.name = { value: func?.name ?? '' }
- this.returnType = { value: func?.return_type ?? 'void' }
- this.schema = { value: func?.schema ?? 'public' }
- this.securityDefiner = { value: func?.security_definer ?? false }
- }
-
- update(state: Dictionary<any>) {
- this.args = state.args
- this.behavior = state.behavior
- this.configParams = state.configParams
- this.definition = state.definition
- this.language = state.language
- this.name = state.name
- this.returnType = state.returnType
- this.schema = state.schema
- this.securityDefiner = state.securityDefiner
- }
-}
-
-interface ICreateFunctionStore {
- formState: CreateFunctionFormState
- meta: any
- schemas: Dictionary<any>[]
- isEditing: boolean
- onFormChange: (value: { key: string; value: any }) => void
- onFormArrayChange: (value: {
- operation: 'add' | 'delete' | 'update'
- key: string
- idx?: number
- value?: any
- }) => void
- setSchemas: (value: Dictionary<any>[]) => void
- validateForm: () => boolean
-}
-
-class CreateFunctionStore implements ICreateFunctionStore {
- formState = new CreateFunctionFormState()
- meta = null
- schemas = []
- advancedVisible = false
- isDirty = false
-
- constructor() {
- makeAutoObservable(this)
- }
-
- get title() {
- return this.formState.id
- ? `Edit '${this.formState.originalName}' function`
- : 'Add a new function'
- }
-
- get isEditing() {
- return this.formState.id != undefined
- }
-
- toggleAdvancedVisible = () => {
- this.advancedVisible = !this.advancedVisible
- }
-
- setSchemas = (value: Dictionary<any>[]) => {
- this.schemas = value as any
- }
-
- setIsDirty = (value: boolean) => {
- this.isDirty = value
- }
-
- onFormChange = ({ key, value }: { key: string; value: any }) => {
- this.isDirty = true
- if (has(this.formState, key)) {
- const temp = (this.formState as any)[key] as any
- ;(this.formState as any)[key] = { ...temp, value, error: undefined }
- } else {
- ;(this.formState as any)[key] = { value }
- }
- }
-
- onFormArrayChange = ({
- operation,
- key,
- idx,
- value,
- }: {
- operation: 'add' | 'delete' | 'update'
- key: string
- idx?: number
- value?: any
- }) => {
- switch (operation) {
- case 'add': {
- if (has(this.formState, key)) {
- // @ts-ignore
- this.formState[key].value.push(value)
- } else {
- const values = [value]
- // @ts-ignore
- this.formState[key] = { value: [value] }
- }
- break
- }
- case 'delete': {
- if (has(this.formState, key)) {
- const temp = filter(
- // @ts-ignore
- this.formState[key].value,
- (_: any, index: number) => index != idx
- ) as any
- // @ts-ignore
- this.formState[key].value = temp
- }
- break
- }
- default: {
- if (has(this.formState, key) && !isUndefined(idx)) {
- // @ts-ignore
- this.formState[key].value[idx] = value
- } else {
- // @ts-ignore
- this.formState[key] = { value: [value] }
- }
- }
- }
- }
-
- validateForm = () => {
- let isValidated = true
- const _state = mapValues(this.formState, (x: { value: any }, key: string) => {
- switch (key) {
- case 'name': {
- if (isEmpty(x.value) || hasWhitespace(x.value)) {
- isValidated = false
- return { ...x, error: 'Invalid function name' }
- } else {
- return x
- }
- }
- case 'args': {
- const temp = x.value?.map((i: Dictionary<any>) => {
- if (isEmpty(i.name) || hasWhitespace(i.name)) {
- isValidated = false
- return { ...i, error: 'Invalid argument name' }
- } else {
- return i
- }
- })
- x.value = temp
- return x
- }
- case 'configParams': {
- const temp = x.value?.map((i: Dictionary<any>) => {
- const error: any = { name: undefined, value: undefined }
- if (isEmpty(i.name) || hasWhitespace(i.name)) {
- isValidated = false
- error.name = 'Invalid config name'
- }
- if (isEmpty(i.value)) {
- isValidated = false
- error.value = 'Missing config value'
- }
- return { ...i, error }
- })
- x.value = temp
- return x
- }
- default:
- return x
- }
- })
- if (!isValidated) {
- this.formState.update(_state)
- }
- return isValidated
- }
-}
+import { FormSchema } from 'types'
+import {
+ Button,
+ FormControl_Shadcn_,
+ FormDescription_Shadcn_,
+ FormField_Shadcn_,
+ FormItem_Shadcn_,
+ FormLabel_Shadcn_,
+ FormMessage_Shadcn_,
+ Form_Shadcn_,
+ Input_Shadcn_,
+ Modal,
+ Radio,
+ ScrollArea,
+ SelectContent_Shadcn_,
+ SelectItem_Shadcn_,
+ SelectTrigger_Shadcn_,
+ SelectValue_Shadcn_,
+ Select_Shadcn_,
+ SidePanel,
+ Toggle,
+} from 'ui'
+import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
+import { convertArgumentTypes, convertConfigParams } from './Functions.utils'
-const CreateFunctionContext = createContext<ICreateFunctionStore | null>(null)
+const FORM_ID = 'create-function-sidepanel'
interface CreateFunctionProps {
- func: any
+ func?: PostgresFunction
visible: boolean
setVisible: (value: boolean) => void
}
+const FormSchema = z.object({
+ name: z.string().trim().min(1),
+ schema: z.string().trim().min(1),
+ args: z.array(z.object({ name: z.string().trim().min(1), type: z.string().trim() })),
+ behavior: z.enum(['IMMUTABLE', 'STABLE', 'VOLATILE']),
+ definition: z.string().trim(),
+ language: z.string().trim(),
+ return_type: z.string().trim(),
+ security_definer: z.boolean(),
+ config_params: z
+ .array(z.object({ name: z.string().trim().min(1), value: z.string().trim().min(1) }))
+ .optional(),
+})
+
const CreateFunction = ({ func, visible, setVisible }: CreateFunctionProps) => {
const { project } = useProjectContext()
- const _localState = useLocalObservable(() => new CreateFunctionStore())
-
- const [isClosingPanel, setIsClosingPanel] = useState<boolean>(false)
-
- useSchemasQuery(
- {
- projectRef: project?.ref,
- connectionString: project?.connectionString,
- },
- {
- onSuccess(schemas) {
- _localState.setSchemas(schemas)
- },
- }
- )
+ const [isClosingPanel, setIsClosingPanel] = useState(false)
+ const [advancedSettingsShown, setAdvancedSettingsShown] = useState(false)
+
+ const isEditing = !!func?.id
+
+ const form = useForm<z.infer<typeof FormSchema>>({
+ resolver: zodResolver(FormSchema),
+ })
const { mutate: createDatabaseFunction, isLoading: isCreating } =
useDatabaseFunctionCreateMutation()
const { mutate: updateDatabaseFunction, isLoading: isUpdating } =
useDatabaseFunctionUpdateMutation()
- useEffect(() => {
- _localState.formState.reset(func)
- _localState.setIsDirty(false)
- }, [visible, func])
+ function isClosingSidePanel() {
+ form.formState.isDirty ? setIsClosingPanel(true) : setVisible(!visible)
+ }
- async function handleSubmit() {
+ const onSubmit: SubmitHandler<z.infer<typeof FormSchema>> = async (data) => {
if (!project) return console.error('Project is required')
- if (_localState.validateForm()) {
- const body = _localState.formState.requestBody
- if (body.id) {
- updateDatabaseFunction(
- {
- id: body.id,
- projectRef: project.ref,
- connectionString: project.connectionString,
- payload: body as any,
+ const payload = {
+ ...data,
+ args: data.args.map((x) => `${x.name} ${x.type}`),
+ config_params: mapValues(keyBy(data.config_params, 'name'), 'value') as Record<string, never>,
+ }
+
+ if (isEditing) {
+ updateDatabaseFunction(
+ {
+ id: func.id,
+ projectRef: project.ref,
+ connectionString: project.connectionString,
+ payload,
+ },
+ {
+ onSuccess: () => {
+ toast.success(`Successfully updated function ${data.name}`)
+ setVisible(!visible)
},
- {
- onSuccess: () => {
- toast.success(`Successfully updated function ${body.name}`)
- setVisible(!visible)
- },
- }
- )
- } else {
- createDatabaseFunction(
- {
- projectRef: project.ref,
- connectionString: project.connectionString,
- payload: body,
+ }
+ )
+ } else {
+ createDatabaseFunction(
+ {
+ projectRef: project.ref,
+ connectionString: project.connectionString,
+ payload,
+ },
+ {
+ onSuccess: () => {
+ toast.success(`Successfully created function ${data.name}`)
+ setVisible(!visible)
},
- {
- onSuccess: () => {
- toast.success(`Successfully created function ${body.name}`)
- setVisible(!visible)
- },
- }
- )
- }
+ }
+ )
}
}
- function isClosingSidePanel() {
- _localState.isDirty ? setIsClosingPanel(true) : setVisible(!visible)
- }
+ useEffect(() => {
+ if (visible) {
+ form.reset({
+ name: func?.name ?? '',
+ schema: func?.schema ?? 'public',
+ args: convertArgumentTypes(func?.argument_types || '').value,
+ behavior: func?.behavior ?? 'VOLATILE',
+ definition: func?.definition ?? '',
+ language: func?.language ?? 'plpgsql',
+ return_type: func?.return_type ?? 'void',
+ security_definer: func?.security_definer ?? false,
+ config_params: convertConfigParams(func?.config_params).value,
+ })
+ }
+ }, [visible, func])
return (
- <>
- <SidePanel
- size="large"
- visible={visible}
- onCancel={isClosingSidePanel}
- header={_localState.title}
- className="hooks-sidepanel mr-0 transform transition-all duration-300 ease-in-out"
- loading={isCreating || isUpdating}
- onConfirm={handleSubmit}
- >
- <CreateFunctionContext.Provider value={_localState}>
- <div className="mt-4 space-y-10">
- {_localState.isEditing ? (
- <>
- <SidePanel.Content>
- <div className="space-y-4">
- <InputName />
- <SelectSchema />
+ <SidePanel
+ size="large"
+ visible={visible}
+ header={isEditing ? `Edit '${func.name}' function` : 'Add a new function'}
+ className="mr-0 transform transition-all duration-300 ease-in-out"
+ onCancel={() => isClosingSidePanel()}
+ customFooter={
+ <div className="flex justify-end gap-2 p-4 bg-overlay border-t border-overlay">
+ <Button disabled={isCreating || isUpdating} type="default" onClick={isClosingSidePanel}>
+ Cancel
+ </Button>
+
+ <Button
+ form={FORM_ID}
+ htmlType="submit"
+ disabled={isCreating || isUpdating}
+ loading={isCreating || isUpdating}
+ >
+ Confirm
+ </Button>
+ </div>
+ }
+ >
+ <Form_Shadcn_ {...form}>
+ <form id={FORM_ID} className="space-y-6 mt-4" onSubmit={form.handleSubmit(onSubmit)}>
+ <SidePanel.Content>
+ <FormField_Shadcn_
+ control={form.control}
+ name="name"
+ render={({ field }) => (
+ <FormItemLayout
+ label="Name of function"
+ description="Name will also be used for the function name in postgres"
+ layout="horizontal"
+ >
+ <FormControl_Shadcn_>
+ <Input_Shadcn_ {...field} />
+ </FormControl_Shadcn_>
+ </FormItemLayout>
+ )}
+ />
+ </SidePanel.Content>
+ <SidePanel.Separator />
+ <SidePanel.Content className="space-y-4">
+ <FormField_Shadcn_
+ control={form.control}
+ name="schema"
+ render={({ field }) => (
+ <FormItemLayout
+ label="Schema"
+ description="Tables made in the table editor will be in 'public'"
+ layout="horizontal"
+ >
+ <FormControl_Shadcn_>
+ <SchemaSelector
+ selectedSchemaName={field.value}
+ excludedSchemas={EXCLUDED_SCHEMAS}
+ size="small"
+ onSelectSchema={(name) => field.onChange(name)}
+ />
+ </FormControl_Shadcn_>
+ </FormItemLayout>
+ )}
+ />
+ {!isEditing && (
+ <FormField_Shadcn_
+ control={form.control}
+ name="return_type"
+ render={({ field }) => (
+ <FormItemLayout label="Return type" layout="horizontal">
+ {/* Form selects don't need form controls, otherwise the CSS gets weird */}
+ <Select_Shadcn_ onValueChange={field.onChange} defaultValue={field.value}>
+ <SelectTrigger_Shadcn_ className="col-span-8">
+ <SelectValue_Shadcn_ />
+ </SelectTrigger_Shadcn_>
+ <SelectContent_Shadcn_>
+ {['void', 'record', 'trigger', 'integer', ...POSTGRES_DATA_TYPES].map(
+ (option) => (
+ <SelectItem_Shadcn_ value={option} key={option}>
+ {option}
+ </SelectItem_Shadcn_>
+ )
+ )}
+ </SelectContent_Shadcn_>
+ </Select_Shadcn_>
+ </FormItemLayout>
+ )}
+ />
+ )}
+ </SidePanel.Content>
+ <SidePanel.Separator />
+ <SidePanel.Content>
+ <FormFieldArgs readonly={isEditing} />
+ </SidePanel.Content>
+ <SidePanel.Separator />
+ <SidePanel.Content>
+ <FormField_Shadcn_
+ control={form.control}
+ name="definition"
+ render={({ field }) => (
+ <FormItem_Shadcn_ className="space-y-4">
+ <div>
+ <FormLabel_Shadcn_ className="text-base text-foreground">
+ Definition
+ </FormLabel_Shadcn_>
+ <FormDescription_Shadcn_ className="text-sm text-foreground-light">
+ <p>The language below should be written in `plpgsql`.</p>
+ {!isEditing && <p>Change the language in the advanced settings below.</p>}
+ </FormDescription_Shadcn_>
</div>
- </SidePanel.Content>
- <SidePanel.Separator />
- <SidePanel.Content>
- <InputMultiArguments readonly={true} />
- </SidePanel.Content>
- <SidePanel.Separator />
- <SidePanel.Content>
- <InputDefinition />
- </SidePanel.Content>
- </>
- ) : (
- <div className="space-y-6">
- <SidePanel.Content>
- <InputName />
- </SidePanel.Content>
- <SidePanel.Separator />
- <SidePanel.Content>
- <div className="space-y-4">
- <SelectSchema />
- <SelectReturnType />
+
+ <div className="h-60 resize-y border border-default">
+ <FormControl_Shadcn_>
+ <SqlEditor
+ defaultValue={field.value}
+ onInputChange={(value: string | undefined) => {
+ field.onChange(value)
+ }}
+ contextmenu={false}
+ />
+ </FormControl_Shadcn_>
</div>
- </SidePanel.Content>
- <SidePanel.Separator />
- <SidePanel.Content>
- <InputMultiArguments />
- </SidePanel.Content>
- <SidePanel.Separator />
- <SidePanel.Content>
- <InputDefinition />
- </SidePanel.Content>
- <SidePanel.Separator />
- <SidePanel.Content>
- <Panel>
- <div className={`space-y-8 rounded bg-studio py-4`}>
- <div className={`px-6`}>
- <Toggle
- onChange={() => _localState.toggleAdvancedVisible()}
- label="Show advanced settings"
- checked={_localState.advancedVisible}
- labelOptional="These are settings that might be familiar for postgres heavy users "
- />
- </div>
- {/* advanced selections */}
+
+ <FormMessage_Shadcn_ />
+ </FormItem_Shadcn_>
+ )}
+ />
+ </SidePanel.Content>
+ <SidePanel.Separator />
+ {isEditing ? null : (
+ <>
+ <SidePanel.Content className="!m-0 py-6">
+ <div className="space-y-8 rounded bg-studio py-4 px-6 border border-overlay">
+ <Toggle
+ onChange={() => setAdvancedSettingsShown(!advancedSettingsShown)}
+ label="Show advanced settings"
+ checked={advancedSettingsShown}
+ labelOptional="These are settings that might be familiar for Postgres developers"
+ />
+ </div>
+ </SidePanel.Content>
+ {advancedSettingsShown && (
+ <>
+ <SidePanel.Content className="!m-0">
+ <div className="space-y-2">
+ <FormFieldLanguage />
+ <FormField_Shadcn_
+ control={form.control}
+ name="behavior"
+ render={({ field }) => (
+ <FormItemLayout label="Behavior" layout="horizontal">
+ <Select_Shadcn_
+ defaultValue={field.value}
+ onValueChange={field.onChange}
+ >
+ <SelectTrigger_Shadcn_ className="col-span-8">
+ <SelectValue_Shadcn_ />
+ </SelectTrigger_Shadcn_>
+ <SelectContent_Shadcn_>
+ <SelectItem_Shadcn_ value="IMMUTABLE" key="IMMUTABLE">
+ immutable
+ </SelectItem_Shadcn_>
+ <SelectItem_Shadcn_ value="STABLE" key="STABLE">
+ stable
+ </SelectItem_Shadcn_>
+ <SelectItem_Shadcn_ value="VOLATILE" key="VOLATILE">
+ volatile
+ </SelectItem_Shadcn_>
+ </SelectContent_Shadcn_>
+ </Select_Shadcn_>
+ </FormItemLayout>
+ )}
+ />
</div>
- </Panel>
- </SidePanel.Content>
- {_localState.advancedVisible && (
- <>
- <SidePanel.Content>
- <div className="space-y-2">
- <SelectLanguage />
- <SelectBehavior />
- </div>
- </SidePanel.Content>
- <SidePanel.Separator />
- <SidePanel.Content>
- <InputMultiConfigParams />
- </SidePanel.Content>
- <SidePanel.Separator />
- <SidePanel.Content>
- <RadioSecurity />
- </SidePanel.Content>
- </>
- )}
- </div>
- )}
- </div>
- </CreateFunctionContext.Provider>
- <ConfirmationModal
- visible={isClosingPanel}
- header="Discard changes"
- buttonLabel="Discard"
- onSelectCancel={() => setIsClosingPanel(false)}
- onSelectConfirm={() => {
- setIsClosingPanel(false)
- setVisible(!visible)
- }}
- >
- <Modal.Content>
- <p className="py-4 text-sm text-foreground-light">
- There are unsaved changes. Are you sure you want to close the panel? Your changes will
- be lost.
- </p>
- </Modal.Content>
- </ConfirmationModal>
- </SidePanel>
- </>
+ </SidePanel.Content>
+ <SidePanel.Separator />
+ <SidePanel.Content>
+ <FormFieldConfigParams readonly={isEditing} />
+ </SidePanel.Content>
+ <SidePanel.Separator />
+ <SidePanel.Content className="!m-0 py-6">
+ <div className="space-y-4">
+ <h5 className="text-base text-foreground">Type of security</h5>
+ <FormField_Shadcn_
+ control={form.control}
+ name="security_definer"
+ render={({ field }) => (
+ <FormItem_Shadcn_>
+ <FormControl_Shadcn_ className="col-span-8">
+ {/* TODO: This RadioGroup imports Formik state, replace it with a clean component */}
+ <Radio.Group
+ type="cards"
+ layout="vertical"
+ onChange={(event) =>
+ field.onChange(event.target.value == 'SECURITY_DEFINER')
+ }
+ value={field.value ? 'SECURITY_DEFINER' : 'SECURITY_INVOKER'}
+ >
+ <Radio
+ id="SECURITY_INVOKER"
+ label="SECURITY INVOKER"
+ value="SECURITY_INVOKER"
+ checked={!field.value}
+ description={
+ <>
+ Function is to be executed with the privileges of the user
+ that <span className="text-foreground">calls it</span>.
+ </>
+ }
+ />
+ <Radio
+ id="SECURITY_DEFINER"
+ label="SECURITY DEFINER"
+ value="SECURITY_DEFINER"
+ checked={field.value}
+ description={
+ <>
+ Function is to be executed with the privileges of the user
+ that <span className="text-foreground">created it</span>.
+ </>
+ }
+ />
+ </Radio.Group>
+ </FormControl_Shadcn_>
+ <FormMessage_Shadcn_ />
+ </FormItem_Shadcn_>
+ )}
+ />
+ </div>
+ </SidePanel.Content>
+ </>
+ )}
+ </>
+ )}
+ </form>
+ </Form_Shadcn_>
+
+ <ConfirmationModal
+ visible={isClosingPanel}
+ header="Discard changes"
+ buttonLabel="Discard"
+ onSelectCancel={() => setIsClosingPanel(false)}
+ onSelectConfirm={() => {
+ setIsClosingPanel(false)
+ setVisible(!visible)
+ }}
+ >
+ <Modal.Content>
+ <p className="py-4 text-sm text-foreground-light">
+ There are unsaved changes. Are you sure you want to close the panel? Your changes will
+ be lost.
+ </p>
+ </Modal.Content>
+ </ConfirmationModal>
+ </SidePanel>
)
}
-export default observer(CreateFunction)
-
-const InputName = observer(({}) => {
- const _localState = useContext(CreateFunctionContext)
- return (
- <Input
- id="name"
- label="Name of function"
- layout="horizontal"
- placeholder="Name of function"
- value={_localState!.formState.name.value}
- onChange={(e) =>
- _localState!.onFormChange({
- key: 'name',
- value: e.target.value,
- })
- }
- size="small"
- error={_localState!.formState.name.error}
- descriptionText="Name will also be used for the function name in postgres"
- />
- )
-})
+export default CreateFunction
-interface InputMultiArgumentsProps {
+interface FormFieldConfigParamsProps {
readonly?: boolean
}
-const InputMultiArguments = observer(({ readonly }: InputMultiArgumentsProps) => {
- const _localState = useContext(CreateFunctionContext)
-
- function onAddArgument() {
- _localState!.onFormArrayChange({
- key: 'args',
- value: { name: '', type: 'bool' },
- operation: 'add',
- })
- }
+const FormFieldArgs = ({ readonly }: FormFieldConfigParamsProps) => {
+ const { fields, append, remove } = useFieldArray<z.infer<typeof FormSchema>>({
+ name: 'args',
+ })
return (
- <div>
+ <>
<div className="flex flex-col">
<h5 className="text-base text-foreground">Arguments</h5>
<p className="text-sm text-foreground-light">
@@ -483,276 +418,155 @@ const InputMultiArguments = observer(({ readonly }: InputMultiArgumentsProps) =>
</p>
</div>
<div className="space-y-2 pt-4">
- {readonly && isEmpty(_localState!.formState.args.value) && (
+ {readonly && isEmpty(fields) && (
<span className="text-foreground-lighter">No argument for this function</span>
)}
- {_localState!.formState.args.value.map(
- (x: { name: string; type: string; error?: string }, idx: number) => (
- <InputArgument
- key={`arg-${idx}`}
- idx={idx}
- name={x.name}
- type={x.type}
- error={x.error}
- readonly={readonly}
- />
+ {fields.map((field, index) => {
+ return (
+ <div className="flex flex-row space-x-1" key={field.id}>
+ <FormField_Shadcn_
+ name={`args.${index}.name`}
+ render={({ field }) => (
+ <FormItem_Shadcn_ className="flex-1">
+ <FormControl_Shadcn_>
+ <Input_Shadcn_ {...field} disabled={readonly} placeholder="argument_name" />
+ </FormControl_Shadcn_>
+ <FormMessage_Shadcn_ />
+ </FormItem_Shadcn_>
+ )}
+ />
+ <FormField_Shadcn_
+ name={`args.${index}.type`}
+ render={({ field }) => (
+ <FormItem_Shadcn_ className="flex-1">
+ <FormControl_Shadcn_>
+ {readonly ? (
+ <Input_Shadcn_ value={field.value} disabled readOnly className="h-auto" />
+ ) : (
+ <Select_Shadcn_
+ disabled={readonly}
+ onValueChange={field.onChange}
+ defaultValue={field.value}
+ >
+ <SelectTrigger_Shadcn_ className="h-[38px]">
+ <SelectValue_Shadcn_ />
+ </SelectTrigger_Shadcn_>
+ <SelectContent_Shadcn_>
+ <ScrollArea className="h-52">
+ {['integer', ...POSTGRES_DATA_TYPES].map((option) => (
+ <SelectItem_Shadcn_ value={option} key={option}>
+ {option}
+ </SelectItem_Shadcn_>
+ ))}
+ </ScrollArea>
+ </SelectContent_Shadcn_>
+ </Select_Shadcn_>
+ )}
+ </FormControl_Shadcn_>
+ <FormMessage_Shadcn_ />
+ </FormItem_Shadcn_>
+ )}
+ />
+
+ {!readonly && (
+ <Button
+ type="danger"
+ icon={<Trash size={12} />}
+ onClick={() => remove(index)}
+ size="small"
+ className="h-[38px]"
+ />
+ )}
+ </div>
)
- )}
+ })}
+
{!readonly && (
- <div>
- <Button type="default" icon={<IconPlus />} onClick={onAddArgument} disabled={readonly}>
- Add a new argument
- </Button>
- </div>
+ <Button
+ type="default"
+ icon={<Plus size={12} />}
+ onClick={() => append({ name: '', type: 'integer' })}
+ disabled={readonly}
+ >
+ Add a new argument
+ </Button>
)}
</div>
- </div>
+ </>
)
-})
+}
-interface InputArgumentProps {
- idx: number
- name: string
- type: string
- error?: string
+interface FormFieldConfigParamsProps {
readonly?: boolean
}
-const InputArgument = observer(({ idx, name, type, error, readonly }: InputArgumentProps) => {
- const _localState = useContext(CreateFunctionContext)
-
- function onNameChange(e: FormEvent<HTMLInputElement>) {
- const _value = e.currentTarget.value
- _localState!.onFormArrayChange({
- key: 'args',
- value: { name: _value, type },
- idx,
- operation: 'update',
- })
- }
-
- function onTypeChange(_value: string) {
- _localState!.onFormArrayChange({
- key: 'args',
- value: { name, type: _value },
- idx,
- operation: 'update',
- })
- }
-
- function onDelete() {
- _localState!.onFormArrayChange({
- key: 'args',
- idx,
- operation: 'delete',
- })
- }
-
- return (
- <div className="flex flex-row space-x-1 items-center">
- <Input
- id={`name-${idx}`}
- className="flex-1 flex-grow"
- value={name}
- placeholder="Name of argument"
- onChange={onNameChange}
- size="small"
- error={error}
- disabled={readonly}
- />
- {readonly ? (
- <Input disabled readOnly id={`type-${idx}`} size="small" value={type} className="flex-1" />
- ) : (
- <Listbox
- id={`type-${idx}`}
- className="flex-1"
- value={type}
- size="small"
- onChange={onTypeChange}
- disabled={readonly}
- >
- <Listbox.Option value="integer" label="integer">
- integer
- </Listbox.Option>
- {POSTGRES_DATA_TYPES.map((x: string) => (
- <Listbox.Option key={x} value={x} label={x}>
- {x}
- </Listbox.Option>
- ))}
- </Listbox>
- )}
- {!readonly && (
- <Button type="danger" icon={<IconTrash size="tiny" />} onClick={onDelete} size="small" />
- )}
- </div>
- )
-})
-
-const InputMultiConfigParams = observer(({}) => {
- const _localState = useContext(CreateFunctionContext)
- function onAddArgument() {
- _localState!.onFormArrayChange({
- key: 'configParams',
- value: { name: '', value: '' },
- operation: 'add',
- })
- }
+const FormFieldConfigParams = ({ readonly }: FormFieldConfigParamsProps) => {
+ const { fields, append, remove } = useFieldArray<z.infer<typeof FormSchema>>({
+ name: 'config_params',
+ })
return (
- <div>
- <div className="flex items-center justify-between">
- <h5 className="text-base text-foreground">Config Params</h5>
- </div>
+ <>
+ <h5 className="text-base text-foreground">Configuration parameters</h5>
<div className="space-y-2 pt-4">
- {_localState!.formState.configParams.value.map(
- (
- x: { name: string; value: string; error?: { name?: string; value?: string } },
- idx: number
- ) => (
- <InputConfigParam
- key={`configParam-${idx}`}
- idx={idx}
- name={x.name}
- value={x.value}
- error={x.error}
- />
- )
+ {readonly && isEmpty(fields) && (
+ <span className="text-foreground-lighter">No argument for this function</span>
)}
- </div>
- <div className="pt-2">
- <Button type="default" icon={<IconPlus />} onClick={onAddArgument}>
- Add a new config
- </Button>
- </div>
- </div>
- )
-})
-
-interface InputConfigParamProps {
- idx: number
- name: string
- value: string
- error?: { name?: string; value?: string }
-}
-const InputConfigParam = observer(({ idx, name, value, error }: InputConfigParamProps) => {
- const _localState = useContext(CreateFunctionContext)
-
- function onNameChange(e: FormEvent<HTMLInputElement>) {
- const _value = e.currentTarget.value
- _localState!.onFormArrayChange({
- key: 'configParams',
- value: { name: _value, value },
- idx,
- operation: 'update',
- })
- }
-
- function onValueChange(e: FormEvent<HTMLInputElement>) {
- const _value = e.currentTarget.value
- _localState!.onFormArrayChange({
- key: 'configParams',
- value: { name, value: _value },
- idx,
- operation: 'update',
- })
- }
-
- function onDelete() {
- _localState!.onFormArrayChange({
- key: 'configParams',
- idx,
- operation: 'delete',
- })
- }
-
- return (
- <div className="flex space-x-1 items-center">
- <Input
- id={`name-${idx}`}
- className="flex-1"
- placeholder="Name of config"
- value={name}
- onChange={onNameChange}
- size="small"
- error={error?.name}
- />
- <Input
- id={`value-${idx}`}
- className="flex-1"
- placeholder="Value of config"
- value={value}
- onChange={onValueChange}
- size="small"
- error={error?.value}
- />
- <Button type="danger" icon={<IconTrash size="tiny" />} onClick={onDelete} size="small" />
- </div>
- )
-})
+ {fields.map((field, index) => {
+ return (
+ <div className="flex flex-row space-x-1" key={field.id}>
+ <FormField_Shadcn_
+ name={`config_params.${index}.name`}
+ render={({ field }) => (
+ <FormItem_Shadcn_ className="flex-1">
+ <FormControl_Shadcn_>
+ <Input_Shadcn_ {...field} placeholder="parameter_name" />
+ </FormControl_Shadcn_>
+ <FormMessage_Shadcn_ />
+ </FormItem_Shadcn_>
+ )}
+ />
+ <FormField_Shadcn_
+ name={`config_params.${index}.value`}
+ render={({ field }) => (
+ <FormItem_Shadcn_ className="flex-1">
+ <FormControl_Shadcn_>
+ <Input_Shadcn_ {...field} placeholder="parameter_value" />
+ </FormControl_Shadcn_>
+ <FormMessage_Shadcn_ />
+ </FormItem_Shadcn_>
+ )}
+ />
+
+ {!readonly && (
+ <Button
+ type="danger"
+ icon={<Trash size={12} />}
+ onClick={() => remove(index)}
+ size="small"
+ className="h-[38px]"
+ />
+ )}
+ </div>
+ )
+ })}
-const InputDefinition = observer(({}) => {
- const _localState = useContext(CreateFunctionContext)
- return (
- <div className="space-y-4">
- <div className="flex flex-col">
- <h5 className="text-base text-foreground">Definition</h5>
- <p className="text-sm text-foreground-light">
- The language below should be written in `{_localState!.formState.language.value}`.
- </p>
- {!_localState?.isEditing && (
- <p className="text-sm text-foreground-light">
- Change the language in the Advanced Settings below.
- </p>
+ {!readonly && (
+ <Button
+ type="default"
+ icon={<Plus size={12} />}
+ onClick={() => append({ name: '', type: '' })}
+ disabled={readonly}
+ >
+ Add a new config
+ </Button>
)}
</div>
- <div className="h-60 resize-y border border-default">
- <SqlEditor
- defaultValue={_localState!.formState.definition.value}
- onInputChange={(value: string | undefined) => {
- _localState!.onFormChange({
- key: 'definition',
- value: value,
- })
- }}
- contextmenu={false}
- />
- </div>
- </div>
- )
-})
-
-const SelectSchema = observer(({}) => {
- const _localState = useContext(CreateFunctionContext)
-
- const { project } = useProjectContext()
- const { data } = useSchemasQuery({
- projectRef: project?.ref,
- connectionString: project?.connectionString,
- })
- const schemas = data?.filter((schema) => !EXCLUDED_SCHEMAS.includes(schema.name)) ?? []
-
- return (
- <Listbox
- id="schema"
- label="Schema"
- size="small"
- layout="horizontal"
- placeholder="Pick a schema"
- value={_localState!.formState.schema.value}
- descriptionText="Tables made in the table editor will be in 'public'"
- onChange={(value) => _localState!.onFormChange({ key: 'schema', value })}
- >
- {schemas.map((x) => (
- <Listbox.Option key={x.name} label={x.name} value={x.name}>
- {x.name}
- </Listbox.Option>
- ))}
- </Listbox>
+ </>
)
-})
+}
-const SelectLanguage = observer(({}) => {
- const _localState = useContext(CreateFunctionContext)
+const FormFieldLanguage = () => {
const { project } = useProjectContext()
const { data } = useDatabaseExtensionsQuery({
@@ -760,132 +574,32 @@ const SelectLanguage = observer(({}) => {
connectionString: project?.connectionString,
})
- const [enabledExtensions] = partition(data ?? [], (ext: any) => !isNull(ext.installed_version))
-
- return (
- <Listbox
- id="language"
- size="small"
- label="Language"
- layout="horizontal"
- value={_localState!.formState.language.value}
- placeholder="Pick a language"
- onChange={(value) => _localState!.onFormChange({ key: 'language', value })}
- >
- <Listbox.Option value="sql" label="sql">
- sql
- </Listbox.Option>
- {
- //map through all selected extensions that start with pl
- enabledExtensions
- .filter((ex: any) => {
- return ex.name.startsWith('pl')
- })
- .map((ex) => (
- <Listbox.Option key={ex.name} value={ex.name} label={ex.name}>
- {ex.name}
- </Listbox.Option>
- ))
- }
- </Listbox>
- )
-})
-
-const SelectReturnType = observer(({}) => {
- const _localState = useContext(CreateFunctionContext)
-
- return (
- <Listbox
- id="returnType"
- size="small"
- label="Return type"
- layout="horizontal"
- value={_localState!.formState.returnType.value}
- onChange={(value) => _localState!.onFormChange({ key: 'returnType', value })}
- >
- <Listbox.Option value="void" label="void">
- void
- </Listbox.Option>
- <Listbox.Option value="record" label="record">
- record
- </Listbox.Option>
- <Listbox.Option value="trigger" label="trigger">
- trigger
- </Listbox.Option>
- <Listbox.Option value="integer" label="integer">
- integer
- </Listbox.Option>
- {POSTGRES_DATA_TYPES.map((x: string) => (
- <Listbox.Option key={x} value={x} label={x}>
- {x}
- </Listbox.Option>
- ))}
- </Listbox>
- )
-})
-
-const SelectBehavior = observer(({}) => {
- const _localState = useContext(CreateFunctionContext)
-
- return (
- <Listbox
- id="behavior"
- size="small"
- label="Behavior"
- layout="horizontal"
- value={_localState!.formState.behavior.value}
- onChange={(value) => _localState!.onFormChange({ key: 'behavior', value })}
- >
- <Listbox.Option value="IMMUTABLE" label="immutable">
- immutable
- </Listbox.Option>
- <Listbox.Option value="STABLE" label="stable">
- stable
- </Listbox.Option>
- <Listbox.Option value="VOLATILE" label="volatile">
- volatile
- </Listbox.Option>
- </Listbox>
- )
-})
-
-const RadioSecurity = observer(({}) => {
- const _localState = useContext(CreateFunctionContext)
+ const [enabledExtensions] = partition(data ?? [], (ext) => !isNull(ext.installed_version))
return (
- <>
- <div className="space-y-4">
- <Radio.Group
- type="cards"
- label="Type of security"
- layout="vertical"
- onChange={(event) => {
- _localState!.onFormChange({
- key: 'securityDefiner',
- value: event.target.value == 'SECURITY_DEFINER',
- })
- }}
- value={
- _localState!.formState.securityDefiner.value ? 'SECURITY_DEFINER' : 'SECURITY_INVOKER'
- }
- error={_localState!.formState.securityDefiner.error}
- >
- <Radio
- id="SECURITY_INVOKER"
- label="SECURITY INVOKER"
- value="SECURITY_INVOKER"
- checked={!_localState!.formState.securityDefiner.value}
- description="Function is to be executed with the privileges of the user that calls it."
- />
- <Radio
- id="SECURITY_DEFINER"
- label="SECURITY DEFINER"
- value="SECURITY_DEFINER"
- checked={_localState!.formState.securityDefiner.value}
- description="Function is to be executed with the privileges of the user that created it."
- />
- </Radio.Group>
- </div>
- </>
+ <FormField_Shadcn_
+ name="language"
+ render={({ field }) => (
+ <FormItemLayout label="Language" layout="horizontal">
+ {/* Form selects don't need form controls, otherwise the CSS gets weird */}
+ <Select_Shadcn_ onValueChange={field.onChange} defaultValue={field.value}>
+ <SelectTrigger_Shadcn_ className="col-span-8">
+ <SelectValue_Shadcn_ />
+ </SelectTrigger_Shadcn_>
+ <SelectContent_Shadcn_>
+ {enabledExtensions
+ .filter((ex) => {
+ return ex.name.startsWith('pl')
+ })
+ .map((option) => (
+ <SelectItem_Shadcn_ value={option.name} key={option.name}>
+ {option.name}
+ </SelectItem_Shadcn_>
+ ))}
+ </SelectContent_Shadcn_>
+ </Select_Shadcn_>
+ </FormItemLayout>
+ )}
+ />
)
-})
+}
diff --git a/apps/studio/components/interfaces/Database/Functions/Functions.utils.ts b/apps/studio/components/interfaces/Database/Functions/Functions.utils.ts
index f342c295a78..ea8298366ba 100644
--- a/apps/studio/components/interfaces/Database/Functions/Functions.utils.ts
+++ b/apps/studio/components/interfaces/Database/Functions/Functions.utils.ts
@@ -1,4 +1,3 @@
-import type { Dictionary } from 'types'
import { isEmpty } from 'lodash'
/**
@@ -22,7 +21,7 @@ export function convertArgumentTypes(value: string) {
* convert config_params = {search_path: "auth, public"}
* to {value: [{name: 'search_path', value: 'auth, public'}]}
*/
-export function convertConfigParams(value: Dictionary<any>) {
+export function convertConfigParams(value: Record<string, string> | null | undefined) {
const temp = []
if (value) {
for (var key in value) {
diff --git a/apps/studio/components/ui/SchemaSelector.tsx b/apps/studio/components/ui/SchemaSelector.tsx
index a6a01069364..49ae9392028 100644
--- a/apps/studio/components/ui/SchemaSelector.tsx
+++ b/apps/studio/components/ui/SchemaSelector.tsx
@@ -1,4 +1,8 @@
+import { Check, ChevronsUpDown, Plus } from 'lucide-react'
import { useState } from 'react'
+
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { useSchemasQuery } from 'data/database/schemas-query'
import {
AlertDescription_Shadcn_,
AlertTitle_Shadcn_,
@@ -11,20 +15,12 @@ import {
CommandList_Shadcn_,
CommandSeparator_Shadcn_,
Command_Shadcn_,
- IconCheck,
- IconCode,
- IconLoader,
- IconPlus,
PopoverContent_Shadcn_,
PopoverTrigger_Shadcn_,
Popover_Shadcn_,
ScrollArea,
} from 'ui'
-import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
-import { useSchemasQuery } from 'data/database/schemas-query'
-import { ChevronDownIcon, ChevronsUpDown } from 'lucide-react'
-
interface SchemaSelectorProps {
className?: string
disabled?: boolean
@@ -32,6 +28,7 @@ interface SchemaSelectorProps {
showError?: boolean
selectedSchemaName: string
supportSelectAll?: boolean
+ excludedSchemas?: string[]
onSelectSchema: (name: string) => void
onSelectCreateSchema?: () => void
}
@@ -43,6 +40,7 @@ const SchemaSelector = ({
showError = true,
selectedSchemaName,
supportSelectAll = false,
+ excludedSchemas = [],
onSelectSchema,
onSelectCreateSchema,
}: SchemaSelectorProps) => {
@@ -61,7 +59,9 @@ const SchemaSelector = ({
connectionString: project?.connectionString,
})
- const schemas = (data ?? []).sort((a, b) => (a.name > b.name ? 0 : -1))
+ const schemas = (data || [])
+ .filter((schema) => !excludedSchemas.includes(schema.name))
+ .sort((a, b) => a.name.localeCompare(b.name))
return (
<div className={className}>
@@ -106,7 +106,7 @@ const SchemaSelector = ({
</div>
</Button>
</PopoverTrigger_Shadcn_>
- <PopoverContent_Shadcn_ className="p-0 w-64" side="bottom" align="start">
+ <PopoverContent_Shadcn_ className="p-0 popover-trigger-width" side="bottom" align="start">
<Command_Shadcn_>
<CommandInput_Shadcn_ placeholder="Find schema..." />
<CommandList_Shadcn_>
@@ -128,7 +128,7 @@ const SchemaSelector = ({
>
<span>All schemas</span>
{selectedSchemaName === '*' && (
- <IconCheck className="text-brand" strokeWidth={2} />
+ <Check className="text-brand" strokeWidth={2} size={16} />
)}
</CommandItem_Shadcn_>
)}
@@ -147,7 +147,7 @@ const SchemaSelector = ({
>
<span>{schema.name}</span>
{selectedSchemaName === schema.name && (
- <IconCheck className="text-brand" strokeWidth={2} />
+ <Check className="text-brand" strokeWidth={2} size={16} />
)}
</CommandItem_Shadcn_>
))}
@@ -168,7 +168,7 @@ const SchemaSelector = ({
setOpen(false)
}}
>
- <IconPlus />
+ <Plus size={12} />
Create a new schema
</CommandItem_Shadcn_>
</CommandGroup_Shadcn_>
diff --git a/apps/studio/pages/project/[ref]/database/functions.tsx b/apps/studio/pages/project/[ref]/database/functions.tsx
index bf2d66c8f28..1d425a91d41 100644
--- a/apps/studio/pages/project/[ref]/database/functions.tsx
+++ b/apps/studio/pages/project/[ref]/database/functions.tsx
@@ -1,3 +1,4 @@
+import { PostgresFunction } from '@supabase/postgres-meta'
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { useState } from 'react'
@@ -10,9 +11,9 @@ import { useCheckPermissions, usePermissionsLoaded } from 'hooks'
import type { NextPageWithLayout } from 'types'
const FunctionsPage: NextPageWithLayout = () => {
- const [selectedFunction, setSelectedFunction] = useState<any>()
- const [showCreateFunctionForm, setShowCreateFunctionForm] = useState<boolean>(false)
- const [showDeleteFunctionForm, setShowDeleteFunctionForm] = useState<boolean>(false)
+ const [selectedFunction, setSelectedFunction] = useState<PostgresFunction | undefined>()
+ const [showCreateFunctionForm, setShowCreateFunctionForm] = useState(false)
+ const [showDeleteFunctionForm, setShowDeleteFunctionForm] = useState(false)
const canReadFunctions = useCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_READ, 'functions')
const isPermissionsLoaded = usePermissionsLoaded()
diff --git a/apps/studio/styles/ui.scss b/apps/studio/styles/ui.scss
index 226be4a80b1..cc1890276ca 100644
--- a/apps/studio/styles/ui.scss
+++ b/apps/studio/styles/ui.scss
@@ -441,3 +441,8 @@
@apply stroke-foreground-lighter;
}
}
+
+// Used on radix popover contents so that the width matches the trigger
+.popover-trigger-width {
+ width: var(--radix-popover-trigger-width);
+}
diff --git a/packages/ui-patterns/form/FormItemLayout/FormItemLayout.stories.tsx b/packages/ui-patterns/form/FormItemLayout/FormItemLayout.stories.tsx
index ec47d60ea55..4858145c9ab 100644
--- a/packages/ui-patterns/form/FormItemLayout/FormItemLayout.stories.tsx
+++ b/packages/ui-patterns/form/FormItemLayout/FormItemLayout.stories.tsx
@@ -84,13 +84,11 @@ export const Primary: Story = {
name="username"
control={form.control}
render={({ field }) => (
- <FormItem_Shadcn_>
- <FormItemLayout {...args}>
- <FormControl_Shadcn_>
- <Input placeholder="mildtomato" {...field} />
- </FormControl_Shadcn_>
- </FormItemLayout>
- </FormItem_Shadcn_>
+ <FormItemLayout {...args}>
+ <FormControl_Shadcn_>
+ <Input placeholder="mildtomato" {...field} />
+ </FormControl_Shadcn_>
+ </FormItemLayout>
)}
/>
<Button size="small" type="primary" htmlType="submit">
@@ -138,20 +136,18 @@ export const withSelect: Story = {
control={form.control}
render={({ field }) => (
<FormItemLayout {...args}>
- <FormItem_Shadcn_>
- <Select_Shadcn_ onValueChange={field.onChange} defaultValue={field.value}>
- <FormControl_Shadcn_>
- <SelectTrigger_Shadcn_>
- <SelectValue_Shadcn_ placeholder="Select a verified email to display" />
- </SelectTrigger_Shadcn_>
- </FormControl_Shadcn_>
- <SelectContent_Shadcn_>
- <SelectItem_Shadcn_ value="[email protected]">[email protected]</SelectItem_Shadcn_>
- <SelectItem_Shadcn_ value="[email protected]">[email protected]</SelectItem_Shadcn_>
- <SelectItem_Shadcn_ value="[email protected]">[email protected]</SelectItem_Shadcn_>
- </SelectContent_Shadcn_>
- </Select_Shadcn_>
- </FormItem_Shadcn_>
+ <Select_Shadcn_ onValueChange={field.onChange} defaultValue={field.value}>
+ <FormControl_Shadcn_>
+ <SelectTrigger_Shadcn_>
+ <SelectValue_Shadcn_ placeholder="Select a verified email to display" />
+ </SelectTrigger_Shadcn_>
+ </FormControl_Shadcn_>
+ <SelectContent_Shadcn_>
+ <SelectItem_Shadcn_ value="[email protected]">[email protected]</SelectItem_Shadcn_>
+ <SelectItem_Shadcn_ value="[email protected]">[email protected]</SelectItem_Shadcn_>
+ <SelectItem_Shadcn_ value="[email protected]">[email protected]</SelectItem_Shadcn_>
+ </SelectContent_Shadcn_>
+ </Select_Shadcn_>
</FormItemLayout>
)}
/>
@@ -201,11 +197,9 @@ export const withLayoutChange: Story = {
control={form.control}
render={({ field }) => (
<FormItemLayout {...args}>
- <FormItem_Shadcn_>
- <FormControl_Shadcn_>
- <Input placeholder="mildtomato" {...field} />
- </FormControl_Shadcn_>
- </FormItem_Shadcn_>
+ <FormControl_Shadcn_>
+ <Input placeholder="mildtomato" {...field} />
+ </FormControl_Shadcn_>
</FormItemLayout>
)}
/>
@@ -251,30 +245,28 @@ export const withCalendar: Story = {
control={form.control}
render={({ field }) => (
<FormItemLayout {...args}>
- <FormItem_Shadcn_ className="flex flex-col">
- <Popover_Shadcn_>
- <PopoverTrigger_Shadcn_ asChild>
- <FormControl_Shadcn_>
- <Button
- icon={<CalendarIcon className="text-foreground-muted" size={16} />}
- type={'default'}
- className={cn(!field.value && 'text-muted-foreground', 'justify-start')}
- >
- {field.value ? format(field.value, 'PPP') : <span>Pick a date</span>}
- </Button>
- </FormControl_Shadcn_>
- </PopoverTrigger_Shadcn_>
- <PopoverContent_Shadcn_ className="w-auto p-0" align="start">
- <Calendar
- mode="single"
- selected={field.value}
- onSelect={field.onChange}
- disabled={(date) => date > new Date() || date < new Date('1900-01-01')}
- initialFocus
- />
- </PopoverContent_Shadcn_>
- </Popover_Shadcn_>
- </FormItem_Shadcn_>
+ <Popover_Shadcn_>
+ <PopoverTrigger_Shadcn_ asChild>
+ <FormControl_Shadcn_>
+ <Button
+ icon={<CalendarIcon className="text-foreground-muted" size={16} />}
+ type={'default'}
+ className={cn(!field.value && 'text-muted-foreground', 'justify-start')}
+ >
+ {field.value ? format(field.value, 'PPP') : <span>Pick a date</span>}
+ </Button>
+ </FormControl_Shadcn_>
+ </PopoverTrigger_Shadcn_>
+ <PopoverContent_Shadcn_ className="w-auto p-0" align="start">
+ <Calendar
+ mode="single"
+ selected={field.value}
+ onSelect={field.onChange}
+ disabled={(date) => date > new Date() || date < new Date('1900-01-01')}
+ initialFocus
+ />
+ </PopoverContent_Shadcn_>
+ </Popover_Shadcn_>
</FormItemLayout>
)}
/>
diff --git a/packages/ui-patterns/form/FormLayout.tsx b/packages/ui-patterns/form/FormLayout.tsx
index 15f37d21eac..7301a57a361 100644
--- a/packages/ui-patterns/form/FormLayout.tsx
+++ b/packages/ui-patterns/form/FormLayout.tsx
@@ -23,6 +23,9 @@ import { Input } from '../DataInputs/Input'
import { InfoTooltip } from '../InfoTooltip/InfoTooltip'
import { FormItemLayout } from './FormItemLayout/FormItemLayout'
+/**
+ * This is helper file for the FormLayout stories.
+ */
const items = [
{
id: 'recents',