LCOV - code coverage report
Current view: top level - src/renderer/extensions/vueNodes/widgets/components - WidgetSelectDefault.vue Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 95.2 % 104 99
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1           16 : <template>
       2         5352 :   <WidgetLayoutField
       3              :     :widget
       4              :     :input-id
       5              :     :value-text="selectedSummary"
       6              :     :root-class="
       7              :       cn(
       8              :         !disabled && 'cursor-pointer',
       9              :         isInvalid && 'ring-1 ring-destructive focus-within:ring-destructive'
      10              :       )
      11              :     "
      12              :   >
      13              :     <template #leading>
      14              :       <Button
      15              :         type="button"
      16              :         tabindex="-1"
      17              :         :aria-label="`${widgetLabel}: ${$t('g.previous')}`"
      18              :         :disabled="isStepDisabled(-1)"
      19              :         class="h-full w-6 shrink-0 rounded-(--node-widget-radius)"
      20              :         variant="muted-textonly"
      21              :         size="icon-sm"
      22              :         @click="stepOption(-1)"
      23              :       >
      24              :         <i
      25              :           class="icon-[lucide--chevron-left] triangle-icons:icon-[comfy--play] triangle-icons:size-2.5 triangle-icons:rotate-180"
      26              :           aria-hidden="true"
      27              :         />
      28              :       </Button>
      29              :     </template>
      30              :     <template #between><slot name="between" /></template>
      31              :     <ComboboxRoot
      32              :       ref="combobox"
      33              :       :open="isOpen"
      34              :       :model-value="selectedOption ?? null"
      35              :       by="key"
      36              :       :disabled
      37              :       ignore-filter
      38              :       selection-behavior="replace"
      39              :       :reset-search-term-on-select="false"
      40              :       @update:model-value="selectOption"
      41              :       @update:open="handleOpenChange"
      42              :     >
      43              :       <ComboboxAnchor as-child>
      44              :         <div
      45              :           data-capture-wheel="true"
      46              :           :class="
      47              :             cn(
      48              :               WidgetInputBaseClass,
      49              :               'flex w-full min-w-0 items-center overflow-hidden not-disabled:bg-transparent',
      50              :               useWidgetHeight(),
      51              :               disabled && 'opacity-50'
      52              :             )
      53              :           "
      54              :         >
      55              :           <ComboboxTrigger as-child>
      56              :             <Button
      57              :               :id="inputId"
      58              :               type="button"
      59              :               role="combobox"
      60              :               aria-haspopup="listbox"
      61              :               :aria-controls="listboxId"
      62              :               :aria-label="widgetLabel"
      63              :               :aria-invalid="isInvalid || undefined"
      64              :               :aria-expanded="isOpen"
      65              :               :disabled
      66              :               tabindex="0"
      67              :               data-testid="widget-select-default-trigger"
      68              :               variant="textonly"
      69              :               size="sm"
      70              :               class="h-full min-w-0 flex-1 overflow-hidden rounded-none p-0 font-normal"
      71              :             >
      72              :               <span class="min-w-[4ch] flex-1 truncate px-2 text-right">
      73              :                 {{ selectedSummary || placeholder || '\u00a0' }}
      74              :               </span>
      75              :             </Button>
      76              :           </ComboboxTrigger>
      77              :           <slot />
      78              :           <Button
      79              :             type="button"
      80              :             tabindex="-1"
      81              :             :aria-label="`${widgetLabel}: ${$t('g.next')}`"
      82              :             :disabled="isStepDisabled(1)"
      83              :             class="h-full w-6 shrink-0 rounded-(--node-widget-radius)"
      84              :             variant="muted-textonly"
      85              :             size="icon-sm"
      86              :             @click="stepOption(1)"
      87              :           >
      88              :             <i
      89              :               class="icon-[lucide--chevron-right] triangle-icons:icon-[comfy--play] triangle-icons:size-2.5"
      90              :               aria-hidden="true"
      91              :             />
      92              :           </Button>
      93              :         </div>
      94              :       </ComboboxAnchor>
      95              : 
      96              :       <ComboboxPortal :key="Number(isOpen)">
      97              :         <ComboboxContent
      98              :           data-capture-wheel="true"
      99              :           data-testid="widget-select-default-overlay"
     100              :           role="presentation"
     101              :           :aria-orientation="undefined"
     102              :           :aria-multiselectable="undefined"
     103              :           position="popper"
     104              :           :side-offset="1"
     105              :           align="end"
     106              :           prioritize-position
     107              :           sticky="always"
     108              :           :collision-padding="8"
     109              :           :class="
     110              :             cn(
     111              :               'z-overlay overflow-hidden rounded-lg border border-solid border-border bg-background p-0 shadow-md',
     112              :               'max-w-(--reka-combobox-content-available-width) min-w-[min(var(--reka-combobox-trigger-width),var(--reka-combobox-content-available-width))]'
     113              :             )
     114              :           "
     115              :           @keydown.capture="replayComboboxNavigation"
     116              :           @keydown.escape.stop="handleOpenChange(false)"
     117              :           @focus-outside="handleFocusOutside"
     118              :         >
     119              :           <div
     120              :             v-if="isFilterable"
     121              :             ref="searchInputContainerRef"
     122              :             class="m-1 flex items-center gap-2 rounded-md border px-2 py-1.5 transition-colors focus-within:border-ring"
     123              :           >
     124              :             <i
     125              :               class="icon-[lucide--search] text-sm text-muted-foreground"
     126              :               aria-hidden="true"
     127              :             />
     128              :             <ComboboxInput
     129              :               v-model="searchQuery"
     130              :               :placeholder="filterPlaceholder"
     131              :               auto-focus
     132              :               :aria-label="$t('g.search')"
     133              :               :aria-controls="listboxId"
     134              :               :aria-activedescendant="activeDescendant"
     135              :               data-testid="widget-select-default-search-input"
     136              :               class="w-full border-none bg-transparent text-xs outline-none"
     137              :             />
     138              :           </div>
     139              : 
     140              :           <div
     141              :             :id="listboxId"
     142              :             data-testid="widget-select-default-viewport"
     143              :             role="listbox"
     144              :             :aria-label="widgetLabel"
     145              :             class="max-h-[min(30.5rem,max(2rem,calc(var(--reka-combobox-content-available-height,100dvh)-3rem)))] min-w-full scrollbar-thin scrollbar-thumb-smoke-500/50 scrollbar-track-transparent scrollbar-gutter-stable overflow-y-auto p-1 text-xs"
     146              :             @pointerdown.capture.self="handleViewportPointerDown"
     147              :           >
     148              :             <div
     149              :               aria-hidden="true"
     150              :               class="invisible flex h-0 gap-3 overflow-hidden px-2"
     151              :             >
     152              :               <span class="whitespace-nowrap">{{ longestLabel }}</span>
     153              :               <span class="size-3.5 shrink-0" />
     154              :             </div>
     155              :             <ComboboxVirtualizer
     156              :               :key="`${directory.join('/')}:${searchQuery}`"
     157              :               v-slot="{ option }"
     158              :               :options="browseOptions"
     159              :               :estimate-size="32"
     160              :               :text-content="(option) => option.label"
     161              :             >
     162              :               <ComboboxItem
     163              :                 :value="option"
     164              :                 :text-value="option.label"
     165              :                 :aria-label="
     166              :                   option.kind === 'value'
     167              :                     ? option.label
     168              :                     : $t(
     169              :                         option.kind === 'folder'
     170              :                           ? 'widgets.selectFolder'
     171              :                           : 'widgets.backFromFolder',
     172              :                         { name: option.label },
     173              :                         { escapeParameter: false }
     174              :                       )
     175              :                 "
     176              :                 :class="
     177              :                   cn(
     178              :                     'flex h-8 w-full cursor-pointer items-center justify-between gap-3 rounded-sm p-2 outline-none select-none',
     179              :                     'hover:bg-secondary data-highlighted:bg-secondary',
     180              :                     'data-[state=checked]:bg-foreground/10 data-[state=checked]:hover:bg-foreground/10 data-[state=checked]:data-highlighted:bg-foreground/20'
     181              :                   )
     182              :                 "
     183              :                 @select="handleOptionSelect($event, option)"
     184              :               >
     185              :                 <i
     186              :                   v-if="option.kind !== 'value'"
     187              :                   :class="
     188              :                     cn(
     189              :                       'text-muted-foreground',
     190              :                       option.kind === 'back'
     191              :                         ? 'icon-[lucide--arrow-left]'
     192              :                         : 'icon-[lucide--folder]'
     193              :                     )
     194              :                   "
     195              :                   aria-hidden="true"
     196              :                 />
     197              :                 <span class="min-w-0 flex-1 truncate">{{ option.label }}</span>
     198              :                 <i
     199              :                   v-if="option.kind === 'folder'"
     200              :                   class="icon-[lucide--chevron-right] text-muted-foreground"
     201              :                   aria-hidden="true"
     202              :                 />
     203              :                 <ComboboxItemIndicator
     204              :                   class="flex shrink-0 items-center justify-center"
     205              :                 >
     206              :                   <i
     207              :                     class="icon-[lucide--check] size-3.5 text-foreground"
     208              :                     aria-hidden="true"
     209              :                   />
     210              :                 </ComboboxItemIndicator>
     211              :               </ComboboxItem>
     212              :             </ComboboxVirtualizer>
     213              :           </div>
     214              :           <div
     215              :             v-if="browseOptions.length === 0"
     216              :             role="status"
     217              :             aria-live="polite"
     218              :             class="p-2 text-xs text-muted-foreground"
     219              :           >
     220              :             {{ $t('g.noResultsFound') }}
     221              :           </div>
     222              :         </ComboboxContent>
     223              :       </ComboboxPortal>
     224              :     </ComboboxRoot>
     225              :   </WidgetLayoutField>
     226              : </template>
     227              : 
     228              : <script setup lang="ts">
     229              : import { countBy } from 'es-toolkit'
     230              : import {
     231              :   ComboboxPortal,
     232              :   ComboboxAnchor,
     233              :   ComboboxContent,
     234              :   ComboboxInput,
     235              :   ComboboxItem,
     236              :   ComboboxItemIndicator,
     237              :   ComboboxRoot,
     238              :   ComboboxTrigger,
     239              :   ComboboxVirtualizer
     240              : } from 'reka-ui'
     241              : import { computed, nextTick, ref, useId, useTemplateRef } from 'vue'
     242              : 
     243              : import Button from '@comfyorg/design-system/button/Button'
     244              : import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore'
     245              : import { useComboStepping } from '@/renderer/extensions/vueNodes/widgets/composables/useComboStepping'
     246              : import { useRestoreFocusOnViewportPointer } from '@/renderer/extensions/vueNodes/widgets/composables/useRestoreFocusOnViewportPointer'
     247              : import { replayComboboxNavigation } from '@/renderer/extensions/vueNodes/widgets/utils/replayComboboxNavigation'
     248              : import type { SimplifiedWidget, WidgetValue } from '@/types/simplifiedWidget'
     249              : import { useWidgetHeight } from '@/types/widgetTypes'
     250              : import { cn } from '@comfyorg/tailwind-utils'
     251              : 
     252              : import { WidgetInputBaseClass } from './layout'
     253              : import WidgetLayoutField from './layout/WidgetLayoutField.vue'
     254              : 
     255              : interface Props {
     256              :   widget: SimplifiedWidget<string | undefined>
     257              :   filenameSummary?: boolean
     258              : }
     259              : 
     260              : interface SelectOption {
     261              :   kind: 'value'
     262              :   key: string
     263              :   label: string
     264              :   rawValue: NonNullable<WidgetValue>
     265              :   value: string
     266              : }
     267              : 
     268              : interface SelectFolder {
     269              :   kind: 'folder' | 'back'
     270              :   key: string
     271              :   label: string
     272              :   directory: string[]
     273              : }
     274              : 
     275              : type SelectWidgetOptions = NonNullable<Props['widget']['options']> & {
     276              :   filterPlaceholder?: string
     277              : }
     278              : 
     279              : const { widget, filenameSummary = false } = defineProps<Props>()
     280         3598 : const inputId = useId()
     281         3598 : const widgetLabel = computed(() => widget.label || widget.name)
     282         3598 : const listboxId = useId()
     283              : 
     284         5411 : function resolveRawValues(values: unknown): unknown[] {
     285         5411 :   try {
     286         5411 :     const resolved = typeof values === 'function' ? values() : values
     287         5411 :     return Array.isArray(resolved) ? resolved : []
     288              :   } catch (error) {
     289            0 :     console.error('[WidgetSelectDefault] Failed to resolve options', error)
     290            0 :     return []
     291              :   }
     292              : }
     293              : 
     294       413453 : function toWidgetValue(value: unknown): NonNullable<WidgetValue> {
     295       413453 :   if (
     296              :     typeof value === 'string' ||
     297              :     typeof value === 'number' ||
     298              :     typeof value === 'boolean' ||
     299              :     (typeof value === 'object' && value !== null)
     300              :   ) {
     301       413453 :     return value
     302              :   }
     303              : 
     304            0 :   return String(value)
     305              : }
     306              : 
     307         5411 : function resolveValues(values: unknown) {
     308         5411 :   return resolveRawValues(values)
     309              :     .filter((value) => value !== null && value !== undefined)
     310              :     .map((rawValue) => ({
     311              :       rawValue: toWidgetValue(rawValue),
     312              :       value: String(rawValue)
     313              :     }))
     314              : }
     315              : 
     316         3598 : const modelValue = defineModel<WidgetValue>({
     317              :   default(modelProps: Record<string, unknown>) {
     318              :     try {
     319              :       const modelWidget = modelProps.widget as Props['widget'] | undefined
     320              :       const values = modelWidget?.options?.values
     321              :       const resolved = typeof values === 'function' ? values() : values
     322              :       const firstValue = Array.isArray(resolved)
     323              :         ? resolved.find((value) => value !== null && value !== undefined)
     324              :         : undefined
     325              :       return firstValue === undefined ? '' : firstValue
     326              :     } catch (error) {
     327              :       console.error('[WidgetSelectDefault] Failed to resolve options', error)
     328              :       return ''
     329              :     }
     330              :   }
     331              : })
     332              : 
     333         3598 : const searchQuery = ref('')
     334         3598 : const directory = ref<string[]>([])
     335         3598 : const combobox = useTemplateRef('combobox')
     336         3598 : const optionsRefreshKey = ref(0)
     337         3598 : const isOpen = ref(false)
     338         3598 : const searchInputContainerRef = ref<HTMLElement>()
     339         3598 : const { handleFocusOutside, handleViewportPointerDown } =
     340              :   useRestoreFocusOnViewportPointer(focusSearchInput)
     341              : 
     342         3598 : const widgetOptions = computed(
     343              :   () => widget.options as SelectWidgetOptions | undefined
     344              : )
     345              : 
     346         3598 : const dynamicOptions = computed(
     347              :   () => typeof widgetOptions.value?.values === 'function'
     348              : )
     349         3598 : const disabled = computed(() => Boolean(widgetOptions.value?.disabled))
     350         3598 : const placeholder = computed(() => widgetOptions.value?.placeholder ?? '')
     351         3598 : const filterPlaceholder = computed(
     352              :   () => widgetOptions.value?.filterPlaceholder ?? placeholder.value
     353              : )
     354              : 
     355           71 : function refreshOptions() {
     356           71 :   optionsRefreshKey.value++
     357              : }
     358              : 
     359       413453 : function getOptionLabel(value: string) {
     360       413453 :   const labeler = widgetOptions.value?.getOptionLabel
     361       413453 :   if (!labeler) return value
     362              : 
     363       413453 :   try {
     364       413453 :     return labeler(value) || value
     365              :   } catch (error) {
     366            0 :     console.error('[WidgetSelectDefault] Failed to map option label', error)
     367            0 :     return value
     368              :   }
     369              : }
     370              : 
     371         3598 : const normalizedOptions = computed<SelectOption[]>(() => {
     372         5411 :   void optionsRefreshKey.value
     373              : 
     374         5411 :   return resolveValues(widgetOptions.value?.values).map(
     375              :     ({ rawValue, value }) => ({
     376              :       kind: 'value',
     377              :       key: `value:${value}`,
     378              :       label: getOptionLabel(value),
     379              :       rawValue,
     380              :       value
     381              :     })
     382              :   )
     383              : })
     384              : 
     385         3598 : const hasFolders = computed(
     386              :   () =>
     387              :     !widgetOptions.value?.getOptionLabel &&
     388              :     normalizedOptions.value.some((option) => isFilePath(option.value))
     389              : )
     390              : 
     391        90854 : function isFilePath(value: string) {
     392        90854 :   return /[/\\][^/\\]+\.[a-z][a-z0-9]{0,15}$/i.test(value)
     393              : }
     394              : 
     395         3598 : const isFilterable = computed(
     396              :   () => hasFolders.value || normalizedOptions.value.length > 4
     397              : )
     398              : 
     399         3598 : const filteredOptions = computed(() => {
     400           85 :   if (!isFilterable.value) return normalizedOptions.value
     401              : 
     402           45 :   const query = searchQuery.value.trim().toLocaleLowerCase()
     403           45 :   if (!query) return normalizedOptions.value
     404              : 
     405           25 :   return normalizedOptions.value.filter(
     406              :     (option) =>
     407              :       option.value.toLocaleLowerCase().includes(query) ||
     408              :       option.label.toLocaleLowerCase().includes(query)
     409              :   )
     410              : })
     411              : 
     412         3598 : const browseOptions = computed<Array<SelectOption | SelectFolder>>(() => {
     413          102 :   if (!hasFolders.value || searchQuery.value.trim())
     414           85 :     return filteredOptions.value
     415              : 
     416           17 :   const folders = new Map<string, SelectFolder>()
     417           17 :   const files: SelectOption[] = []
     418           39 :   for (const option of normalizedOptions.value) {
     419        90032 :     const parts = isFilePath(option.value)
     420              :       ? option.value.split(/[/\\]/).filter(Boolean)
     421              :       : [option.value]
     422        90032 :     if (!directory.value.every((part, index) => parts[index] === part)) continue
     423        43871 :     const label = parts[directory.value.length]
     424        90032 :     if (label === undefined) continue
     425        90032 :     if (parts.length === directory.value.length + 1) {
     426         3863 :       files.push({ ...option, label })
     427        40008 :     } else if (!folders.has(label)) {
     428           35 :       const path = [...directory.value, label]
     429           35 :       folders.set(label, {
     430              :         kind: 'folder',
     431              :         key: `folder:${path.join('/')}`,
     432              :         label,
     433              :         directory: path
     434              :       })
     435              :     }
     436              :   }
     437           17 :   const labelCounts = countBy(files, (option) => option.label)
     438          102 :   return [
     439              :     ...(directory.value.length
     440              :       ? [
     441              :           {
     442              :             kind: 'back' as const,
     443              :             key: 'back',
     444              :             label: directory.value.join(' / '),
     445              :             directory: directory.value.slice(0, -1)
     446              :           }
     447              :         ]
     448              :       : []),
     449              :     ...folders.values(),
     450              :     ...files.map((option) =>
     451              :       labelCounts[option.label] > 1
     452              :         ? { ...option, label: option.value }
     453              :         : option
     454              :     )
     455              :   ]
     456              : })
     457              : 
     458         3598 : const activeDescendant = computed((): string | undefined =>
     459              :   browseOptions.value.length
     460              :     ? combobox.value?.highlightedElement?.id
     461              :     : undefined
     462              : )
     463              : 
     464         3598 : const normalizedModelValue = computed(() =>
     465              :   modelValue.value == null ? undefined : String(modelValue.value)
     466              : )
     467              : 
     468         3598 : const selectedOption = computed(() =>
     469              :   normalizedOptions.value.find(
     470              :     (option) => option.value === normalizedModelValue.value
     471              :   )
     472              : )
     473              : 
     474         3598 : const longestLabel = computed(() =>
     475              :   normalizedOptions.value.reduce(
     476              :     (longest, { label }) => (label.length > longest.length ? label : longest),
     477              :     ''
     478              :   )
     479              : )
     480              : 
     481         3598 : const isInvalid = computed(
     482              :   () =>
     483              :     widgetOptions.value?.values !== undefined &&
     484              :     modelValue.value != null &&
     485              :     modelValue.value !== '' &&
     486              :     !selectedOption.value
     487              : )
     488              : 
     489         3598 : const selectedLabel = computed(() => {
     490         4917 :   if (selectedOption.value) return selectedOption.value.label
     491         1234 :   if (isInvalid.value) return String(modelValue.value)
     492            7 :   return ''
     493              : })
     494              : 
     495         3598 : const selectedSummary = computed(() =>
     496              :   filenameSummary && !widgetOptions.value?.getOptionLabel
     497              :     ? selectedLabel.value.split(/[/\\]/).at(-1)
     498              :     : selectedLabel.value
     499              : )
     500              : 
     501           52 : async function handleOptionSelect(
     502              :   event: Event,
     503              :   option: SelectOption | SelectFolder
     504              : ) {
     505           52 :   if (option.kind === 'value') return
     506            5 :   event.preventDefault()
     507            5 :   directory.value = option.directory
     508            5 :   await nextTick()
     509            5 :   focusSearchInput()
     510           52 :   combobox.value?.highlightFirstItem?.()
     511              : }
     512              : 
     513           47 : function selectOption(option: SelectOption | SelectFolder | null) {
     514           47 :   if (!option || option.kind !== 'value') return
     515              : 
     516           47 :   modelValue.value = option.rawValue
     517           47 :   useWorkflowStore().activeWorkflow?.changeTracker.captureCanvasState()
     518           47 :   searchQuery.value = ''
     519           47 :   isOpen.value = false
     520              : }
     521              : 
     522         3598 : const { isStepDisabled, stepOption } = useComboStepping({
     523              :   options: normalizedOptions,
     524              :   selectedOption,
     525              :   disabled,
     526              :   dynamicOptions,
     527              :   refreshOptions,
     528              :   onSelect: selectOption
     529              : })
     530              : 
     531            5 : function focusSearchInput() {
     532            5 :   const input =
     533              :     searchInputContainerRef.value?.querySelector<HTMLInputElement>('input')
     534            5 :   if (!input) return false
     535              : 
     536            5 :   input.focus({ preventScroll: true })
     537            5 :   return true
     538              : }
     539              : 
     540          130 : function handleOpenChange(open: boolean) {
     541          130 :   isOpen.value = open
     542              : 
     543          130 :   if (open) {
     544           71 :     refreshOptions()
     545           71 :     const value = selectedOption.value?.value ?? ''
     546           71 :     directory.value =
     547              :       hasFolders.value && isFilePath(value)
     548              :         ? value.split(/[/\\]/).filter(Boolean).slice(0, -1)
     549              :         : []
     550              :   } else {
     551           59 :     searchQuery.value = ''
     552              :   }
     553              : }
     554              : </script>
        

Generated by: LCOV version 2.0-1