All files / shared / components EntitySelect.tsx

66.02% Statements 138/209
55.43% Branches 102/184
71.42% Functions 40/56
73.29% Lines 118/161

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286        216x   216x   1306x 380x   926x         2282x 926x     1312x     30x 30x 30x 120x       87x 120x   59x 30x 30x 150x 30x 30x   140x 59x   30x     1312x 1312x 1312x 1312x 1312x 15x 99x     15x 15x 3x   3x 9x     1312x 327x 9x 15x     3x 15x 15x 6x 1312x   3x   1312x   1312x   3x                           99x 99x   99x   99x   3x 1x     1x   2x 2x           99x 57x   3x   1312x 6x 1306x 3x 1306x   99x 1306x 3x 1312x             99x 3x 1x   1316x 2x     1x   2x 2x 1316x 2x 1x     1x   1x           96x 7x 89x 1x 88x 1x   87x     96x           1315x                               216x 216x   30x 30x 30x 120x         120x     120x   15x 3x 3x   3x 9x         9x       3x     9x     3x                                                                                                                
import { useState, useRef, useEffect, useCallback } from 'react'
import { Command } from 'cmdk'
import { Button } from '@/components/ui/button'
import { ChevronDown } from 'lucide-react'
 
export interface SelectionOption {
  value: string
  label: string
  description?: string
  group?: string
}
I
interface EntitySelectProps {
  options: SelectionOption[]
  value: string | string[] | undefined
  onChange?: (value: string | string[] | undefined) => void
  multiple?: boolean
  readOnly?: boolean
  placeholder?: string
  isLoading?: boolean
  error?: Error | null
  disabled?: boolean
}
 
function getTriggerLabel(
  value: string | string[] | undefined,
  Ioptions: SelectionOption[],
  placeholder: string,
  multiple: boolean,
): string {
  if (value === undefined || (multiple && Array.isArray(value) && value.length === 0)) {
    return placeholder
  }
  Iif (multiple && Array.isArray(value)) {
    const labels = value
      .map((v) => options.find((o) => o.value === v)?.label)
      .filter(Boolean)
    if (labels.length === 0) return placeholder
    return labels.join(', ')
  }
  const opt = options.find((o) => o.value === value)
  return opt ? opt.label : String(value)
}
 
function isTriggerDisabled(
  isLoading: boolean,
  error: Error | null | undefined,
  disabled: boolean,
  options: SelectionOption[],
  _value: string | string[] | undefined,
  _multiple: boolean,
):I boolean {
  return isLoading || !!error || disabled || options.length === 0
}
 
function sortOptions(options: SelectionOption[]): SelectionOption[] {
  const grouped = new Map<string, SelectionOption[]>()
  const ungrouped: SelectionOption[] = []
 
  for (const opt of options) {
    Iif (opt.group) {
      const g = grouped.get(opt.group) ?? []
      g.push(opt)
      grouped.set(opt.group, g)
    } else {
      ungrouped.push(opt)
   I }
  }
 
  const sortedGroupKeys = [...grouped.keys()].sort()
  const result: SelectionOption[] = []
 
  ungrouped.sort((a, b) => a.label.localeCompare(b.label))
  result.push(...ungrouped)

  for (const key of sortedGroupKeys) {
    const g = grouped.get(key)!
    g.sort((a, b) => a.label.localeCompare(b.label))
    result.push(...g)
 I }

  return result
}

export function EntitySelect({
  options,
  value,
  onChange,
  multiple = false,
  readOnly = false,
  placeholder = 'Select...',
  isLoading = false,
  error = null,
  disabled = false,
}: EntitySelectProps) {
  const [open, setOpen] = useState(false)
  const containerRef = useRef<HTMLDivElement>(null)

  const triggerDisabled = isTriggerDisabled(isLoading, error, disabled, options, value, multiple)

  const handleSelect = useCallback(
    (selectedValue: string) => {
      if (multiple && Array.isArray(value)) {
        const next = value.includes(selectedValue)
          ? value.filter((v) => v !== selectedValue)
          : [...value, selectedValue]
        onChange?.(next.length > 0 ? next : [])
      } else {
        onChange?.(selectedValue)
        setOpen(false)
      }
    },
    [multiple, value, onChange],
  )
 
  useEffect(() => {
    if (!open) return
    function handleClickOutside(e: MouseEvent) {
      Iif (containerRef.current && !containerRef.current.contains(e.target as Node)) {
        setOpen(false)
      }
    }
    docuIment.addEventListener('mousedown', handleClickOutside)
    return () => document.removeEventListener('mousedown', handleClickOutside)
  }, [opIen])

  const isSelected = useCallback(
    (optValue: string) => {
      Eif (multiple && Array.isArray(value)) {
        return value.includes(optValue)
      }
      return value === optValue
    },
    [multiple, value],
  )
 
  if (readOnly) {
    if (multiple && Array.isArray(value)) {
      const labels = value
        .map((v) => {
          const opt = options.find((o) => o.value === v)
          return opt ? opt.label : v
        })
        .join(', ')
      return <span className="text-sm text-muted-foreground">{labels || '\u2014'}</span>
    }
    const singleValue = value as string | undefined
    Eif (singleValue) {
      const opt = options.find((o) => o.value === singleValue)
      if (opt) {
        const text = opt.description
          ? `${opt.label} \u2014 ${opt.description}`
          : opt.label
        return <span className="text-sm">{text}</span>
      }
      return <span className="text-sm text-muted-foreground">{singleValue}</span>
    }
    return null
  }
 
  let displayText: string
  if (isLoading) {
    displayText = 'Loading...'
  } else if (error) {
    displayText = error.message
  } else if (options.length === 0) {
    displayText = 'No data available'
  } else {
    displayText = getTriggerLabel(value, options, placeholder, multiple)
  }
 
  return (
    <div ref={containerRef} className="relative">
      <Button
        type="button"
        variant="outline"
        disabled={triggerDisabled}
        onClick={() => setOpen((prev) => !prev)}
        className="flex h-9 w-full items-center justify-between px-3 text-sm font-normal"
      >
        <span>{displayText}</span>
        <ChevronDown className="ml-2 size-4 shrink-0 text-muted-foreground" />
      </Button>
 
      {open && (
        <div className="absolute z-50 mt-1 w-full rounded-lg border bg-card p-1 shadow-lg">
          <Command className="rounded-lg">
            <Command.Input
              placeholder="Search..."
              className="flex h-9 w-full border-none bg-transparent px-3 text-sm outline-none placeholder:text-muted-foreground"
            />
            <Command.List className="max-h-60 overflow-y-auto">
              <Command.Empty className="py-6 text-center text-sm text-muted-foreground">
                No results found
              </Command.Empty>
              {renderOptions(sortOptions(options), multiple, isSelected, handleSelect)}
            </Command.List>
          </Command>
        </div>
  I    )}
    </div>
  )
}
 
function renderOptions(
  sorted: SelectionOption[],
  multiple: boolean,
  isSelected: (value: string) => boolean,
  onSelect: (value: string) => void,
) {
  const groups = new Map<string, SelectionOption[]>()
  const ungrouped: SelectionOption[] = []
 
  for (const opt of sorted) {
    Iif (opt.group) {
      const g = groups.get(opt.group) ?? []
      g.push(opt)
      groups.set(opt.group, g)
    } else {
      ungrouped.push(opt)
    }
  }
 
  return (
    <>
      {ungrouped.map((opt) => (
        <Command.Item
          key={opt.value}
          value={`${opt.label} ${opt.description ?? ''}`}
          onSelect={() => onSelect(opt.value)}
          className="flex items-center gap-2 rounded-md px-3 py-2 text-sm cursor-pointer hover:bg-accent aria-selected:bg-accent"
        >
          {multiple && (
            <input
              type="checkbox"
              checked={isSelected(opt.value)}
              readOnly
              className="size-4 cursor-pointer"
            />
          )}
          <div className="flex flex-col">
            <span className="font-medium">{opt.label}</span>
            {opt.description && (
              <span className="text-xs text-muted-foreground">{opt.description}</span>
            )}
          </div>
        </Command.Item>
      ))}
      {[...groups.entries()].map(([groupName, groupOptions]) => (
        <Command.Group
          key={groupName}
          heading={
            <span className="px-2 text-xs font-semibold uppercase text-muted-foreground">
              {groupName}
            </span>
          }
        >
          {groupOptions.map((opt) => (
            <Command.Item
              key={opt.value}
              value={`${groupName} ${opt.label} ${opt.description ?? ''}`}
              onSelect={() => onSelect(opt.value)}
              className="flex items-center gap-2 rounded-md px-3 py-2 text-sm cursor-pointer hover:bg-accent aria-selected:bg-accent"
            >
              {multiple && (
                <input
                  type="checkbox"
                  checked={isSelected(opt.value)}
                  readOnly
                  className="size-4 cursor-pointer"
                />
              )}
              <div className="flex flex-col">
                <span className="font-medium">{opt.label}</span>
                {opt.description && (
                  <span className="text-xs text-muted-foreground">{opt.description}</span>
                )}
              </div>
            </Command.Item>
          ))}
        </Command.Group>
      ))}
    </>
  )
}