Skip to content

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

chore: use dndkit for enumerated types sorting (#44521)

Gildas Garciabebd98a6132f
diff --git a/apps/studio/components/interfaces/Database/EnumeratedTypes/CreateEnumeratedTypeSidePanel.tsx b/apps/studio/components/interfaces/Database/EnumeratedTypes/CreateEnumeratedTypeSidePanel.tsx
index 1a45bc97185..82cd53d6472 100644
--- a/apps/studio/components/interfaces/Database/EnumeratedTypes/CreateEnumeratedTypeSidePanel.tsx
+++ b/apps/studio/components/interfaces/Database/EnumeratedTypes/CreateEnumeratedTypeSidePanel.tsx
@@ -1,8 +1,21 @@
+import {
+ closestCenter,
+ DndContext,
+ DragEndEvent,
+ KeyboardSensor,
+ PointerSensor,
+ useSensor,
+ useSensors,
+} from '@dnd-kit/core'
+import {
+ SortableContext,
+ sortableKeyboardCoordinates,
+ verticalListSortingStrategy,
+} from '@dnd-kit/sortable'
import { zodResolver } from '@hookform/resolvers/zod'
import { AlertCircle, ExternalLink, Plus } from 'lucide-react'
import Link from 'next/link'
import { useEffect, useRef } from 'react'
-import { DragDropContext, Droppable, DroppableProvided } from 'react-beautiful-dnd'
import { useFieldArray, useForm } from 'react-hook-form'
import { toast } from 'sonner'
import {
@@ -34,12 +47,13 @@ interface CreateEnumeratedTypeSidePanelProps {
schema: string
}
+const initialValues = { name: '', description: '', values: [{ value: '' }] }
+
const CreateEnumeratedTypeSidePanel = ({
visible,
onClose,
schema,
}: CreateEnumeratedTypeSidePanelProps) => {
- const initialValues = { name: '', description: '', values: [{ value: '' }] }
const submitRef = useRef<HTMLButtonElement>(null)
const { data: project } = useSelectedProjectQuery()
const { mutate: createEnumeratedType, isPending: isCreating } = useEnumeratedTypeCreateMutation({
@@ -49,10 +63,6 @@ const CreateEnumeratedTypeSidePanel = ({
},
})
- useEffect(() => {
- form.reset(initialValues)
- }, [visible])
-
const FormSchema = z.object({
name: z
.string()
@@ -72,16 +82,26 @@ const CreateEnumeratedTypeSidePanel = ({
resolver: zodResolver(FormSchema),
defaultValues: initialValues,
})
+ const { reset } = form
+ const { isDirty } = form.formState
+
+ useEffect(() => {
+ reset(initialValues)
+ }, [reset, visible])
const { fields, append, remove, move } = useFieldArray({
name: 'values',
control: form.control,
})
- const updateOrder = (result: any) => {
- // Dropped outside of the list
- if (!result.destination) return
- move(result.source.index, result.destination.index)
+ const handleDragEnd = (event: DragEndEvent) => {
+ if (event.over == null) return
+ const overIndex = fields.findIndex((item) => item.id === event.over?.id)
+ if (overIndex < 0) return
+ const activeIndex = fields.findIndex((item) => item.id === event.active.id)
+ if (activeIndex < 0) return
+
+ move(activeIndex, overIndex)
}
const onSubmit = (data: z.infer<typeof FormSchema>) => {
@@ -104,9 +124,17 @@ const CreateEnumeratedTypeSidePanel = ({
onClose()
}
+ const sensors = useSensors(
+ useSensor(PointerSensor),
+ useSensor(KeyboardSensor, {
+ coordinateGetter: sortableKeyboardCoordinates,
+ })
+ )
+
return (
<SidePanel
loading={isCreating}
+ disabled={!isDirty}
visible={visible}
onCancel={closePanel}
header="Create a new enumerated type"
@@ -145,67 +173,62 @@ const CreateEnumeratedTypeSidePanel = ({
)}
/>
- <DragDropContext onDragEnd={(result: any) => updateOrder(result)}>
- <Droppable droppableId="enum_type_values_droppable">
- {(droppableProvided: DroppableProvided) => (
- <div ref={droppableProvided.innerRef}>
- {fields.map((field, index) => (
- <FormField_Shadcn_
- control={form.control}
- key={field.id}
- name={`values.${index}.value`}
- render={({ field: inputField }) => (
- <FormItem_Shadcn_>
- <FormLabel_Shadcn_ className={cn(index !== 0 && 'sr-only')}>
- Values
- </FormLabel_Shadcn_>
- {index === 0 && (
- <Alert_Shadcn_>
- <AlertCircle strokeWidth={1.5} />
- <AlertTitle_Shadcn_>
- After creation, values cannot be deleted or sorted
- </AlertTitle_Shadcn_>
- <AlertDescription_Shadcn_>
- <p className="!leading-normal track">
- You will need to delete and recreate the enumerated type with
- the updated values instead.
- </p>
- <Button
- asChild
- type="default"
- icon={<ExternalLink strokeWidth={1.5} />}
- className="mt-2"
- >
- <Link
- href="https://www.postgresql.org/message-id/21012.1459434338%40sss.pgh.pa.us"
- target="_blank"
- rel="noreferrer"
- >
- Learn more
- </Link>
- </Button>
- </AlertDescription_Shadcn_>
- </Alert_Shadcn_>
- )}
- <FormControl_Shadcn_>
- <EnumeratedTypeValueRow
- index={index}
- id={field.id}
- field={inputField}
- isDisabled={fields.length < 2}
- onRemoveValue={() => remove(index)}
- />
- </FormControl_Shadcn_>
- <FormMessage_Shadcn_ className="ml-6" />
- </FormItem_Shadcn_>
- )}
- />
- ))}
- {droppableProvided.placeholder}
- </div>
+ <div>
+ <span
+ className={cn(
+ 'text-foreground-light text-sm',
+ 'transition-colors',
+ 'leading-normal'
)}
- </Droppable>
- </DragDropContext>
+ >
+ Values
+ </span>
+ <Alert_Shadcn_>
+ <AlertCircle strokeWidth={1.5} />
+ <AlertTitle_Shadcn_>
+ After creation, values cannot be deleted or sorted
+ </AlertTitle_Shadcn_>
+ <AlertDescription_Shadcn_>
+ <p className="!leading-normal track">
+ You will need to delete and recreate the enumerated type with the updated values
+ instead.
+ </p>
+ <Button
+ asChild
+ type="default"
+ icon={<ExternalLink strokeWidth={1.5} />}
+ className="mt-2"
+ >
+ <Link
+ href="https://www.postgresql.org/message-id/21012.1459434338%40sss.pgh.pa.us"
+ target="_blank"
+ rel="noreferrer"
+ >
+ Learn more
+ </Link>
+ </Button>
+ </AlertDescription_Shadcn_>
+ </Alert_Shadcn_>
+ <DndContext
+ sensors={sensors}
+ collisionDetection={closestCenter}
+ onDragEnd={handleDragEnd}
+ >
+ <SortableContext items={fields} strategy={verticalListSortingStrategy}>
+ {fields.map((field, index) => (
+ <EnumeratedTypeValueRow
+ key={field.id}
+ id={field.id}
+ name={`values.${index}.value`}
+ index={index}
+ control={form.control}
+ isDisabled={fields.length < 2}
+ onRemoveValue={() => remove(index)}
+ />
+ ))}
+ </SortableContext>
+ </DndContext>
+ </div>
<Button
type="default"
diff --git a/apps/studio/components/interfaces/Database/EnumeratedTypes/EditEnumeratedTypeSidePanel.tsx b/apps/studio/components/interfaces/Database/EnumeratedTypes/EditEnumeratedTypeSidePanel.tsx
index ebc768dec03..80c6e778f23 100644
--- a/apps/studio/components/interfaces/Database/EnumeratedTypes/EditEnumeratedTypeSidePanel.tsx
+++ b/apps/studio/components/interfaces/Database/EnumeratedTypes/EditEnumeratedTypeSidePanel.tsx
@@ -1,8 +1,21 @@
+import {
+ closestCenter,
+ DndContext,
+ DragEndEvent,
+ KeyboardSensor,
+ PointerSensor,
+ useSensor,
+ useSensors,
+} from '@dnd-kit/core'
+import {
+ SortableContext,
+ sortableKeyboardCoordinates,
+ verticalListSortingStrategy,
+} from '@dnd-kit/sortable'
import { zodResolver } from '@hookform/resolvers/zod'
import { AlertCircle, ExternalLink, Plus } from 'lucide-react'
import Link from 'next/link'
import { useEffect, useRef } from 'react'
-import { DragDropContext, Droppable, DroppableProvided } from 'react-beautiful-dnd'
import { useFieldArray, useForm } from 'react-hook-form'
import { toast } from 'sonner'
import {
@@ -66,26 +79,29 @@ const EditEnumeratedTypeSidePanel = ({
defaultValues: {
name: '',
description: '',
- values: [{ isNew: true, originalValue: '', updatedValue: '' }],
+ values: (selectedEnumeratedType?.enums ?? []).map((x) => ({
+ isNew: false,
+ originalValue: x,
+ updatedValue: x,
+ })),
},
})
-
+ const { reset } = form
+ const { isDirty } = form.formState
const { fields, append, remove, move } = useFieldArray({
name: 'values',
control: form.control,
})
- const updateOrder = (result: any) => {
- // Dropped outside of the list
- if (!result.destination) return
- move(result.source.index, result.destination.index)
- }
+ const handleDragEnd = (event: DragEndEvent) => {
+ if (event.over == null) return
+ const overIndex = fields.findIndex((item) => item.id === event.over?.id)
+ if (overIndex < 0) return
+ const activeIndex = fields.findIndex((item) => item.id === event.active.id)
+ if (activeIndex < 0) return
- const originalEnumeratedTypes = (selectedEnumeratedType?.enums ?? []).map((x) => ({
- isNew: false,
- originalValue: x,
- updatedValue: x,
- }))
+ move(activeIndex, overIndex)
+ }
const onSubmit = (data: z.infer<typeof FormSchema>) => {
if (project?.ref === undefined) return console.error('Project ref required')
@@ -122,8 +138,14 @@ const EditEnumeratedTypeSidePanel = ({
}
useEffect(() => {
+ const originalEnumeratedTypes = (selectedEnumeratedType?.enums ?? []).map((x) => ({
+ isNew: false,
+ originalValue: x,
+ updatedValue: x,
+ }))
+
if (selectedEnumeratedType !== undefined) {
- form.reset({
+ reset({
name: selectedEnumeratedType.name,
description: selectedEnumeratedType.comment ?? '',
values: originalEnumeratedTypes,
@@ -131,16 +153,23 @@ const EditEnumeratedTypeSidePanel = ({
}
if (selectedEnumeratedType == undefined) {
- form.reset({
+ reset({
values: originalEnumeratedTypes,
})
}
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [selectedEnumeratedType])
+ }, [reset, selectedEnumeratedType, visible])
+
+ const sensors = useSensors(
+ useSensor(PointerSensor),
+ useSensor(KeyboardSensor, {
+ coordinateGetter: sortableKeyboardCoordinates,
+ })
+ )
return (
<SidePanel
loading={isCreating}
+ disabled={!isDirty}
visible={visible}
onCancel={onClose}
header={`Update type "${selectedEnumeratedType?.name}"`}
@@ -179,67 +208,60 @@ const EditEnumeratedTypeSidePanel = ({
)}
/>
- <DragDropContext onDragEnd={(result: any) => updateOrder(result)}>
- <Droppable droppableId="enum_type_values_droppable">
- {(droppableProvided: DroppableProvided) => (
- <div ref={droppableProvided.innerRef}>
- {fields.map((field, index) => (
- <FormField_Shadcn_
- control={form.control}
- key={field.id}
- name={`values.${index}.updatedValue`}
- render={({ field: inputField }) => (
- <FormItem_Shadcn_>
- <FormLabel_Shadcn_ className={cn(index !== 0 && 'sr-only')}>
- Values
- </FormLabel_Shadcn_>
- {index === 0 && (
- <Alert_Shadcn_>
- <AlertCircle strokeWidth={1.5} />
- <AlertTitle_Shadcn_>
- Existing values cannot be deleted or sorted
- </AlertTitle_Shadcn_>
- <AlertDescription_Shadcn_>
- <p className="!leading-normal track">
- You will need to delete and recreate the enumerated type with
- the updated values instead.
- </p>
- <Button
- asChild
- type="default"
- icon={<ExternalLink strokeWidth={1.5} />}
- className="mt-2"
- >
- <Link
- href="https://www.postgresql.org/message-id/21012.1459434338%40sss.pgh.pa.us"
- target="_blank"
- rel="noreferrer"
- >
- Learn more
- </Link>
- </Button>
- </AlertDescription_Shadcn_>
- </Alert_Shadcn_>
- )}
- <FormControl_Shadcn_>
- <EnumeratedTypeValueRow
- index={index}
- id={field.id}
- field={inputField}
- isDisabled={!field.isNew}
- onRemoveValue={() => remove(index)}
- />
- </FormControl_Shadcn_>
- <FormMessage_Shadcn_ className="ml-6" />
- </FormItem_Shadcn_>
- )}
- />
- ))}
- {droppableProvided.placeholder}
- </div>
+ <div>
+ <span
+ className={cn(
+ 'text-foreground-light text-sm',
+ 'transition-colors',
+ 'leading-normal'
)}
- </Droppable>
- </DragDropContext>
+ >
+ Values
+ </span>
+ <Alert_Shadcn_>
+ <AlertCircle strokeWidth={1.5} />
+ <AlertTitle_Shadcn_>Existing values cannot be deleted or sorted</AlertTitle_Shadcn_>
+ <AlertDescription_Shadcn_>
+ <p className="!leading-normal track">
+ You will need to delete and recreate the enumerated type with the updated values
+ instead.
+ </p>
+ <Button
+ asChild
+ type="default"
+ icon={<ExternalLink strokeWidth={1.5} />}
+ className="mt-2"
+ >
+ <Link
+ href="https://www.postgresql.org/message-id/21012.1459434338%40sss.pgh.pa.us"
+ target="_blank"
+ rel="noreferrer"
+ >
+ Learn more
+ </Link>
+ </Button>
+ </AlertDescription_Shadcn_>
+ </Alert_Shadcn_>
+ <DndContext
+ sensors={sensors}
+ collisionDetection={closestCenter}
+ onDragEnd={handleDragEnd}
+ >
+ <SortableContext items={fields} strategy={verticalListSortingStrategy}>
+ {fields.map((field, index) => (
+ <EnumeratedTypeValueRow
+ key={field.id}
+ id={field.id}
+ name={`values.${index}.updatedValue`}
+ index={index}
+ control={form.control}
+ isDisabled={!field.isNew}
+ onRemoveValue={() => remove(index)}
+ />
+ ))}
+ </SortableContext>
+ </DndContext>
+ </div>
<Button
type="default"
diff --git a/apps/studio/components/interfaces/Database/EnumeratedTypes/EnumeratedTypeValueRow.tsx b/apps/studio/components/interfaces/Database/EnumeratedTypes/EnumeratedTypeValueRow.tsx
index f01ec7f026a..200e8a8527b 100644
--- a/apps/studio/components/interfaces/Database/EnumeratedTypes/EnumeratedTypeValueRow.tsx
+++ b/apps/studio/components/interfaces/Database/EnumeratedTypes/EnumeratedTypeValueRow.tsx
@@ -1,50 +1,81 @@
+import { useSortable } from '@dnd-kit/sortable'
+import { CSS } from '@dnd-kit/utilities'
import { GripVertical, Trash } from 'lucide-react'
-import { Draggable, DraggableProvided } from 'react-beautiful-dnd'
-import { Button, Input_Shadcn_ } from 'ui'
+import { Control } from 'react-hook-form'
+import {
+ Button,
+ FormControl_Shadcn_,
+ FormField_Shadcn_,
+ FormItem_Shadcn_,
+ FormLabel_Shadcn_,
+ FormMessage_Shadcn_,
+ Input_Shadcn_,
+} from 'ui'
interface EnumeratedTypeValueRowProps {
+ control: Control<any>
index: number
id: string
- field: any
+ name: string
isDisabled?: boolean
onRemoveValue: () => void
}
const EnumeratedTypeValueRow = ({
+ control,
index,
id,
- field,
+ name,
isDisabled = false,
onRemoveValue,
}: EnumeratedTypeValueRowProps) => {
+ const { attributes, listeners, setNodeRef, setActivatorNodeRef, transform, transition } =
+ useSortable({
+ disabled: isDisabled,
+ id,
+ })
+
+ const style = {
+ transform: CSS.Transform.toString(transform),
+ transition,
+ }
+
return (
- <Draggable draggableId={id} index={index} isDragDisabled={isDisabled}>
- {(draggableProvided: DraggableProvided) => (
- <div
- ref={draggableProvided.innerRef}
- {...draggableProvided.draggableProps}
- className="flex items-center space-x-2 space-y-2"
- >
- <div
- {...draggableProvided.dragHandleProps}
- className={`opacity-50 hover:opacity-100 transition ${
- isDisabled ? 'text-foreground-lighter !cursor-default' : 'text-foreground'
- }`}
- >
- <GripVertical size={16} strokeWidth={1.5} />
- </div>
- <Input_Shadcn_ {...field} className="w-full" />
- <Button
- type="default"
- size="small"
- disabled={isDisabled}
- icon={<Trash strokeWidth={1.5} size={16} />}
- className="px-2"
- onClick={() => onRemoveValue()}
- />
- </div>
+ <FormField_Shadcn_
+ control={control}
+ name={name}
+ render={({ field: inputField }) => (
+ <FormItem_Shadcn_ ref={setNodeRef} style={style}>
+ <FormLabel_Shadcn_ className="sr-only">Value {index}</FormLabel_Shadcn_>
+ <FormControl_Shadcn_>
+ <div className="flex items-center space-x-2 space-y-2">
+ <button
+ ref={setActivatorNodeRef}
+ {...attributes}
+ {...listeners}
+ className={`opacity-50 hover:opacity-100 disabled:hover:opacity-50 transition cursor-grab ${
+ isDisabled ? 'text-foreground-lighter !cursor-default' : 'text-foreground'
+ }`}
+ type="button"
+ disabled={isDisabled}
+ >
+ <GripVertical size={16} strokeWidth={1.5} />
+ </button>
+ <Input_Shadcn_ {...inputField} className="w-full" />
+ <Button
+ type="default"
+ size="small"
+ disabled={isDisabled}
+ icon={<Trash strokeWidth={1.5} size={16} />}
+ className="px-2"
+ onClick={() => onRemoveValue()}
+ />
+ </div>
+ </FormControl_Shadcn_>
+ <FormMessage_Shadcn_ className="ml-6" />
+ </FormItem_Shadcn_>
)}
- </Draggable>
+ />
)
}