Skip to content

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

Update MultiSelect component to support selecting duplicate value

Joshen Limee7754fbdc6d
diff --git a/studio/components/grid/components/editor/MultiSelectEditor.tsx b/studio/components/grid/components/editor/MultiSelectEditor.tsx
index cf6d0eb9691..5d444eed758 100644
--- a/studio/components/grid/components/editor/MultiSelectEditor.tsx
+++ b/studio/components/grid/components/editor/MultiSelectEditor.tsx
@@ -3,26 +3,12 @@ import { Popover, IconX, IconPlus } from '@supabase/ui'
import { EditorProps } from '@supabase/react-data-grid'
import { useTrackedState } from 'components/grid/store'
-import { tryParseJson } from 'lib/helpers'
+import { convertPgArrayToJsArray, convertJsArraytoPgArray } from 'lib/helpers'
interface Props<TRow, TSummaryRow = unknown> extends EditorProps<TRow, TSummaryRow> {
options?: { label: string; value: string }[]
}
-const convertPgArrayToJsArray = (value: string): string[] => {
- const valueArray = value
- .slice(1, value.length - 1)
- .split(',')
- .map((x) => `"${x}"`)
- const formattedValue = `[${valueArray.join(',')}]`
- return tryParseJson(formattedValue) ?? []
-}
-
-const convertJsArraytoPgArray = (value: string[]) => {
- if (value.length === 0) return null
- else return `{${value.join(',')}}`
-}
-
// Mainly for arrays (specifically enums)
// Array elements are not unique, so this supports selecting an option more than once
export function MultiSelectEditor<TRow, TSummaryRow = unknown>({
diff --git a/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/InputField.tsx b/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/InputField.tsx
index 7fb90d8e9d5..f72b4eec940 100644
--- a/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/InputField.tsx
+++ b/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/InputField.tsx
@@ -5,6 +5,8 @@ import { Button, Select, Input, IconLink, IconArrowRight, IconEdit2 } from '@sup
import { RowField } from './RowEditor.types'
import DateTimeInput from './DateTimeInput'
import { TEXT_TYPES, JSON_TYPES, DATETIME_TYPES } from '../SidePanelEditor.constants'
+import MultiSelect from 'components/ui/MultiSelect'
+import { convertPgArrayToJsArray, convertJsArraytoPgArray, uuidv4 } from 'lib/helpers'
interface Props {
field: RowField
@@ -23,29 +25,68 @@ const InputField: FC<Props> = ({
onEditJson = () => {},
onViewForeignKey = () => {},
}) => {
- if (field.enums.length > 0) {
+ // Hardcode for now
+ if (field.name === 'test') {
+ const formattedValue = convertPgArrayToJsArray(field.value)
+ const options = [
+ { id: uuidv4(), value: 'VALUE_0', name: 'VALUE_0', disabled: false },
+ { id: uuidv4(), value: 'VALUE_1', name: 'VALUE_1', disabled: false },
+ { id: uuidv4(), value: 'VALUE_2', name: 'VALUE_2', disabled: false },
+ ]
return (
- <Select
- size="medium"
- layout="horizontal"
- value={field.value}
- label={field.name}
- labelOptional={field.format}
- descriptionText={field.comment}
- disabled={!isEditable}
- error={errors[field.name]}
- onChange={(event: any) => onUpdateField({ [field.name]: event.target.value })}
- >
- <Select.Option value="">---</Select.Option>
- {field.enums.map((value: string) => (
- <Select.Option key={value} value={value}>
- {value}
- </Select.Option>
- ))}
- </Select>
+ <div className="grid gap-x-2 md:grid-cols-12 md:gap-x-4">
+ <div className="col-span-4">
+ <label className="block text-scale-1100 text-sm break-all">{field.name}</label>
+ <span className="text-scale-900 text-sm" id="-optional">
+ {field.format}
+ </span>
+ </div>
+ <div className="col-span-8">
+ <MultiSelect
+ allowDuplicateSelection
+ options={options}
+ value={formattedValue}
+ searchPlaceholder="Search for a value"
+ placeholder="NULL"
+ onChange={(values) => {
+ const formattedValues = convertJsArraytoPgArray(values)
+ onUpdateField({ [field.name]: formattedValues })
+ }}
+ />
+ </div>
+ </div>
)
}
+ if (field.enums.length > 0) {
+ const isArray = field.format[0] === '_'
+
+ if (isArray) {
+ console.log('Render')
+ } else {
+ return (
+ <Select
+ size="medium"
+ layout="horizontal"
+ value={field.value}
+ label={field.name}
+ labelOptional={field.format}
+ descriptionText={field.comment}
+ disabled={!isEditable}
+ error={errors[field.name]}
+ onChange={(event: any) => onUpdateField({ [field.name]: event.target.value })}
+ >
+ <Select.Option value="">---</Select.Option>
+ {field.enums.map((value: string) => (
+ <Select.Option key={value} value={value}>
+ {value}
+ </Select.Option>
+ ))}
+ </Select>
+ )
+ }
+ }
+
if (!isUndefined(field.foreignKey)) {
return (
<Input
diff --git a/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/RowEditor.tsx b/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/RowEditor.tsx
index 5b3bfb9d459..cee28f3d3cc 100644
--- a/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/RowEditor.tsx
+++ b/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/RowEditor.tsx
@@ -147,6 +147,7 @@ const RowEditor: FC<Props> = ({
return (
<SidePanel
+ hideFooter
size="large"
key="RowEditor"
visible={visible}
@@ -155,7 +156,6 @@ const RowEditor: FC<Props> = ({
isEditingJson || isViewingReferenceRow ? ' mr-32' : ''
}`}
onCancel={closePanel}
- hideFooter
onInteractOutside={(event) => {
const isToast = (event.target as Element)?.closest('#toast')
if (isToast) {
diff --git a/studio/components/ui/MultiSelect/index.tsx b/studio/components/ui/MultiSelect/index.tsx
index 5a649240349..871eac8b8c1 100644
--- a/studio/components/ui/MultiSelect/index.tsx
+++ b/studio/components/ui/MultiSelect/index.tsx
@@ -1,6 +1,6 @@
import { useRef, useEffect, useState, FormEvent, KeyboardEvent, ReactNode } from 'react'
import { orderBy, filter, without } from 'lodash'
-import { Popover, IconCheck, IconAlertCircle, IconSearch } from '@supabase/ui'
+import { Popover, IconCheck, IconAlertCircle, IconSearch, IconPlus } from '@supabase/ui'
import { BadgeDisabled, BadgeSelected } from './Badges'
@@ -8,7 +8,7 @@ export interface MultiSelectOption {
id: string | number
value: string
name: string
- disabled?: boolean
+ disabled: boolean
}
interface Props {
@@ -20,6 +20,7 @@ interface Props {
descriptionText?: string | ReactNode
emptyMessage?: string | ReactNode
disabled?: boolean
+ allowDuplicateSelection?: boolean
onChange?(x: string[]): void
}
@@ -37,6 +38,7 @@ export default function MultiSelect({
searchPlaceholder = 'Search for option',
emptyMessage,
disabled,
+ allowDuplicateSelection = false,
onChange = () => {},
}: Props) {
const ref = useRef(null)
@@ -51,7 +53,7 @@ export default function MultiSelect({
// Calculate width of the Popover
useEffect(() => {
setInputWidth(ref.current ? (ref.current as any).offsetWidth : inputWidth)
- }, [])
+ }, [ref.current])
const width = `${inputWidth}px`
@@ -69,11 +71,19 @@ export default function MultiSelect({
return isOptionSelected !== undefined
}
+ const handleRemove = (idx: number) => {
+ const updatedSelected = selected.filter((x, index) => index !== idx)
+ setSelected(updatedSelected)
+ onChange(updatedSelected)
+ }
+
const handleChange = (option: MultiSelectOption) => {
const _selected = selectedOptions
const isActive = checkIfActive(option)
- const updatedPayload = isActive
+ const updatedPayload = allowDuplicateSelection
+ ? [..._selected.concat([option.value])]
+ : isActive
? [...without(_selected, option.value)]
: [..._selected.concat([option.value])]
@@ -81,7 +91,10 @@ export default function MultiSelect({
const compulsoryOptions = options
.filter((option) => option.disabled)
.map((option) => option.name)
- const formattedPayload = [...new Set(updatedPayload.concat(compulsoryOptions))]
+
+ const formattedPayload = allowDuplicateSelection
+ ? updatedPayload.concat(compulsoryOptions)
+ : [...new Set(updatedPayload.concat(compulsoryOptions))]
setSelected(formattedPayload)
onChange(formattedPayload)
@@ -131,6 +144,7 @@ export default function MultiSelect({
{filteredOptions.length >= 1 ? (
filteredOptions.map((option) => {
const active =
+ !allowDuplicateSelection &&
selectedOptions &&
selectedOptions.find((selected) => {
return selected === option.value
@@ -140,11 +154,11 @@ export default function MultiSelect({
return (
<div
- key={`multiselect-option-${option.value}`}
+ key={`multiselect-option-${option.id}`}
onClick={() => handleChange(option)}
className={[
'text-typography-body-light dark:text-typography-body-dark',
- 'flex cursor-pointer items-center justify-between transition',
+ 'group flex cursor-pointer items-center justify-between transition',
'space-x-1 rounded bg-transparent p-2 px-4 text-sm hover:bg-gray-600',
`${active ? ' dark:bg-green-600 dark:bg-opacity-25' : ''}`,
].join(' ')}
@@ -159,6 +173,12 @@ export default function MultiSelect({
}`}
/>
)}
+ {allowDuplicateSelection && (
+ <div className="flex items-center opacity-0 group-hover:opacity-100 transition space-x-1">
+ <IconPlus size={14} />
+ <p className="text-sm">Add value</p>
+ </div>
+ )}
</div>
)
})
@@ -207,21 +227,22 @@ export default function MultiSelect({
{selectedOptions.length === 0 && placeholder && (
<div className="text-scale-1000 px-2 text-sm">{placeholder}</div>
)}
- {formattedOptions.map((option) => {
- const active =
- selectedOptions &&
- selectedOptions.find((selected) => {
- return selected === option.value
- })
-
- if (option.disabled) {
- return <BadgeDisabled key={option.id} name={option.name} />
- } else if (active) {
+ {selectedOptions.map((value, idx) => {
+ const id = `${value}-${idx}`
+ const option = formattedOptions.find((x) => x.value === value)
+ const isDisabled = option?.disabled ?? false
+ if (!option) {
+ return <></>
+ } else if (isDisabled) {
+ return <BadgeDisabled key={id} name={value} />
+ } else {
return (
<BadgeSelected
- key={option.id}
- name={option.name}
- handleRemove={() => handleChange(option)}
+ key={id}
+ name={value}
+ handleRemove={() =>
+ allowDuplicateSelection ? handleRemove(idx) : handleChange(option)
+ }
/>
)
}
diff --git a/studio/lib/helpers.ts b/studio/lib/helpers.ts
index 7797cce3830..1883401f9b8 100644
--- a/studio/lib/helpers.ts
+++ b/studio/lib/helpers.ts
@@ -168,31 +168,33 @@ export async function passwordStrength(value: string) {
let strength = 0
if (value && value !== '') {
- if(value.length > 99){
+ if (value.length > 99) {
message = `${PASSWORD_STRENGTH[0]} Maximum length of password exceeded`
warning = `Password should be less than 100 characters`
} else {
- const response = await post(`${API_URL}/profile/password-check`, { password: value })
- if (!response.error) {
- const { result } = response
- const score = (PASSWORD_STRENGTH as any)[result.score]
- const suggestions = result.feedback?.suggestions ? result.feedback.suggestions.join(' ') : ''
-
- // set message :string
- message = `${score} ${suggestions}`
-
- // set strength :number
- strength = result.score
-
- // warning message for anything below 4 strength :string
- if (result.score < DEFAULT_MINIMUM_PASSWORD_STRENGTH) {
- warning = `${
- result?.feedback?.warning ? result?.feedback?.warning + '.' : ''
- } You need a stronger password.`
+ const response = await post(`${API_URL}/profile/password-check`, { password: value })
+ if (!response.error) {
+ const { result } = response
+ const score = (PASSWORD_STRENGTH as any)[result.score]
+ const suggestions = result.feedback?.suggestions
+ ? result.feedback.suggestions.join(' ')
+ : ''
+
+ // set message :string
+ message = `${score} ${suggestions}`
+
+ // set strength :number
+ strength = result.score
+
+ // warning message for anything below 4 strength :string
+ if (result.score < DEFAULT_MINIMUM_PASSWORD_STRENGTH) {
+ warning = `${
+ result?.feedback?.warning ? result?.feedback?.warning + '.' : ''
+ } You need a stronger password.`
+ }
}
}
}
-}
return {
message,
@@ -212,3 +214,17 @@ export const detectBrowser = () => {
return 'Safari'
}
}
+
+export const convertPgArrayToJsArray = (value: string): string[] => {
+ const valueArray = value
+ .slice(1, value.length - 1)
+ .split(',')
+ .map((x) => `"${x}"`)
+ const formattedValue = `[${valueArray.join(',')}]`
+ return tryParseJson(formattedValue) ?? []
+}
+
+export const convertJsArraytoPgArray = (value: string[]) => {
+ if (value.length === 0) return null
+ else return `{${value.join(',')}}`
+}