All files / src/components RichReferenceSelect.vue

99.11% Statements 112/113
93.02% Branches 80/86
100% Functions 36/36
100% Lines 98/98

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 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381  56x   4x           1x     2x 4x                 5x                                         13x             2x     2x       13x                                           19x                                                     19x         19x   19x 19x 19x 19x 19x 19x   19x 17x 4x     19x 20x 16x 13x   3x     19x 8x             8x     19x 9x 7x     2x 4x     19x 19x 19x     26x           34x 24x 5x 5x 3x         10x 9x 9x       9x 9x       1x 1x 1x       2x 1x   1x         5x   4x 3x 3x 1x   1x   1x     2x 1x     1x 1x     1x 1x 1x       18x 18x 18x   17x 14x     1x   18x         9x 9x 9x 8x       19x 28x   9x 2x   9x 2x         19x 20x   20x         19x 19x 19x 19x 6x       19x 3x 3x 1x                                                                                                                                                                                                              
<template>
  <div ref="rootRef" class="rich-reference-select" @keydown.esc="closeDropdown">
    <div v-if="multiple && selectedOptions.length" class="selected-chips mb-2">
      <button
        v-for="option in selectedOptions"
        :key="option.value"
        type="button"
        class="chip"
        :disabled="disabled"
        @click="removeOption(option.value)"
      >
        <slot name="selected" :option="option">
          <span class="chip-label">{{ option.label }}</span>
        </slot>
        <span class="chip-remove" aria-hidden="true">x</span>
      </button>
    </div>
 
    <div class="search-wrapper" :class="{ open: isOpen }">
      <input
        :id="inputId"
        ref="inputRef"
        v-model="query"
        type="search"
        class="form-control form-control-sm search-input"
        :placeholder="resolvedSearchPlaceholder"
        :disabled="disabled"
        @focus="openDropdown"
      />
      <button
        v-if="!multiple && !required && normalizedSingleValue"
        type="button"
        class="clear-btn"
        :disabled="disabled"
        @click="clearSingle"
      >
        x
      </button>
    </div>
 
    <div v-if="isOpen" class="dropdown-panel" role="listbox">
      <div v-if="loading" class="dropdown-message">{{ resolvedLoadingLabel }}</div>
      <template v-else>
        <button
          v-for="option in visibleOptions"
          :key="option.value"
          type="button"
          class="dropdown-option"
          :class="{ selected: isSelected(option.value), disabled: !!option.disabled }"
          :disabled="!!option.disabled"
          @click="toggleOption(option)"
        >
          <slot name="option" :option="option" :selected="isSelected(option.value)">
            <div class="option-default-label">{{ option.label }}</div>
            <div v-if="option.description" class="option-default-description">
              {{ option.description }}
            </div>
          </slot>
        </button>
        <div v-if="!visibleOptions.length" class="dropdown-message">
          {{ resolvedNoResultsLabel }}
        </div>
      </template>
    </div>
 
    <div
      v-if="minValues && normalizedMultiValue.length < minValues"
      class="text-warning small mt-1"
    >
      {{ t('field.referenceMinValuesHint').replace('{min}', String(minValues)) }}
    </div>
  </div>
</template>
 
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { useUILanguage } from '@/composables/useUILanguage'
import type { ReferenceOption } from '@/composables/useFlowMemberReference'
 
const props = withDefaults(
  defineProps<{
    modelValue: string | string[] | null | undefined
    multiple?: boolean
    required?: boolean
    disabled?: boolean
    inputId?: string
    minValues?: number
    maxValues?: number
    searchPlaceholder?: string
    loadingLabel?: string
    noResultsLabel?: string
    loadOptions: (query: string) => Promise<ReferenceOption[]>
  }>(),
  {
    multiple: false,
    required: false,
    disabled: false,
    inputId: '',
    minValues: undefined,
    maxValues: undefined,
    searchPlaceholder: '',
    loadingLabel: '',
    noResultsLabel: ''
  }
)
 
const emit = defineEmits<{
  'update:modelValue': [value: string | string[] | null]
  blur: []
}>()
 
const { t } = useUILanguage()
 
const rootRef = ref<HTMLElement | null>(null)
const isOpen = ref(false)
const query = ref('')
const loading = ref(false)
const options = ref<ReferenceOption[]>([])
let searchTimer: ReturnType<typeof setTimeout> | null = null
 
const normalizedMultiValue = computed(() => {
  if (!props.multiple) return [] as string[]
  return Array.isArray(props.modelValue) ? props.modelValue.map((v) => String(v)) : []
})
 
const normalizedSingleValue = computed(() => {
  if (props.multiple) return null
  if (props.modelValue === undefined || props.modelValue === null || props.modelValue === '') {
    return null
  }
  return String(props.modelValue)
})
 
const selectedOptions = computed(() => {
  const selectedSet = new Set(
    props.multiple
      ? normalizedMultiValue.value
      : normalizedSingleValue.value
        ? [normalizedSingleValue.value]
        : []
  )
  return options.value.filter((option) => selectedSet.has(option.value))
})
 
const visibleOptions = computed(() => {
  if (!props.multiple) {
    return options.value
  }
 
  const selectedSet = new Set(normalizedMultiValue.value)
  return options.value.filter((option) => !selectedSet.has(option.value))
})
 
const resolvedSearchPlaceholder = computed(() => props.searchPlaceholder || t('common.search'))
const resolvedLoadingLabel = computed(() => props.loadingLabel || t('common.loading'))
const resolvedNoResultsLabel = computed(() => props.noResultsLabel || t('common.noResults'))
 
function isSelected(value: string): boolean {
  return props.multiple
    ? normalizedMultiValue.value.includes(value)
    : normalizedSingleValue.value === value
}
 
function syncSingleQueryFromModel() {
  if (props.multiple) return
  if (!normalizedSingleValue.value) return
  const selected = options.value.find((option) => option.value === normalizedSingleValue.value)
  if (selected) {
    query.value = selected.label
  }
}
 
function openDropdown() {
  if (props.disabled) return
  isOpen.value = true
  void refreshOptions()
}
 
function closeDropdown() {
  isOpen.value = false
  emit('blur')
}
 
function clearSingle() {
  emit('update:modelValue', null)
  query.value = ''
  void refreshOptions()
}
 
function removeOption(value: string) {
  if (!props.multiple) return
  emit(
    'update:modelValue',
    normalizedMultiValue.value.filter((entry) => entry !== value)
  )
}
 
function toggleOption(option: ReferenceOption) {
  if (option.disabled) return
 
  if (props.multiple) {
    const current = normalizedMultiValue.value
    if (current.includes(option.value)) {
      emit(
        'update:modelValue',
        current.filter((entry) => entry !== option.value)
      )
      return
    }
 
    if (props.maxValues !== undefined && current.length >= props.maxValues) {
      return
    }
 
    emit('update:modelValue', [...current, option.value])
    return
  }
 
  emit('update:modelValue', option.value)
  query.value = option.label
  closeDropdown()
}
 
async function refreshOptions() {
  loading.value = true
  try {
    options.value = await props.loadOptions(query.value.trim())
    // Keep the input label in sync for edit mode once async options are available.
    if (!query.value || query.value === normalizedSingleValue.value) {
      syncSingleQueryFromModel()
    }
  } catch {
    options.value = []
  } finally {
    loading.value = false
  }
}
 
function onClickOutside(event: MouseEvent) {
  Iif (!rootRef.value) return
  const target = event.target as Node | null
  if (target && !rootRef.value.contains(target)) {
    closeDropdown()
  }
}
 
watch(
  () => query.value,
  () => {
    if (searchTimer) {
      clearTimeout(searchTimer)
    }
    searchTimer = setTimeout(() => {
      void refreshOptions()
    }, 250)
  }
)
 
watch(
  () => [props.multiple, props.modelValue],
  () => {
    syncSingleQueryFromModel()
  },
  { immediate: true }
)
 
onMounted(() => {
  document.addEventListener('mousedown', onClickOutside)
  const hasInitialSelection = !!normalizedSingleValue.value || normalizedMultiValue.value.length > 0
  if (hasInitialSelection) {
    void refreshOptions()
  }
})
 
onBeforeUnmount(() => {
  document.removeEventListener('mousedown', onClickOutside)
  if (searchTimer) {
    clearTimeout(searchTimer)
  }
})
</script>
 
<style scoped>
.rich-reference-select {
  position: relative;
}
 
.selected-chips {
  display: flex;
  flex-wrap: wrap;
  gap: 0.35rem;
}
 
.chip {
  border: 1px solid #d0d9e2;
  background: #f4f7fa;
  border-radius: 999px;
  padding: 0.2rem 0.5rem;
  display: inline-flex;
  align-items: center;
  gap: 0.35rem;
  max-width: 100%;
}
 
.chip-label {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
 
.chip-remove {
  opacity: 0.7;
  font-size: 0.8rem;
}
 
.search-wrapper {
  position: relative;
}
 
.search-input {
  padding-right: 1.8rem;
}
 
.clear-btn {
  position: absolute;
  top: 50%;
  right: 0.4rem;
  transform: translateY(-50%);
  border: 0;
  background: transparent;
  color: #6b7280;
}
 
.dropdown-panel {
  position: absolute;
  z-index: 30;
  left: 0;
  right: 0;
  margin-top: 0.25rem;
  border: 1px solid #d6dee6;
  border-radius: 0.5rem;
  background: #fff;
  max-height: 260px;
  overflow-y: auto;
  box-shadow: 0 10px 24px rgba(12, 19, 31, 0.12);
}
 
.dropdown-option {
  width: 100%;
  text-align: left;
  border: 0;
  background: transparent;
  padding: 0.5rem 0.6rem;
  border-bottom: 1px solid #f0f3f6;
}
 
.dropdown-option:hover,
.dropdown-option.selected {
  background: #f8fbff;
}
 
.dropdown-option.disabled {
  opacity: 0.55;
}
 
.option-default-label {
  font-weight: 600;
}
 
.option-default-description {
  font-size: 0.8rem;
  color: #6b7280;
}
 
.dropdown-message {
  padding: 0.6rem;
  color: #6b7280;
  font-size: 0.85rem;
}
</style>